logo

Quick Start - APIScript for Android

iPush On Android Made Possible - APIScript for Android

January 9, 2009, by Paul Lin, Technical Consultant of ICE Technology Corp.

Level: Beginning
Background

Follow this article, developer can learn how to develop iPush application for Google Android system with iPush Java client library.

Contents
  1. Before we start
  2. Creating the application skeleton
  3. Adding iPush Java library
  4. Enable the network access permission
  5. Designing the UI layout
  6. Get codes ready
  7. Run it
  8. Processing the user input
  9. Receiving response from iPush Server
  10. Packaging the application for deployment
  11. Install the APIScript to your Android device

1. Before we start

This article assumes that you have adequate knowledge on Java programming. Also, having experiences in iPush Server and Ardroid platform would serve the purpose of this article well. We will be converting the sample APIScript application found in most of the iPush client package. If you have not had the chance to try the APIScript application yet, here is a brief explanation on what it does. APIScript is a command-line driven utility through which users may interact with iPush Server by typing in text commands.

Though this article focuses on the iPush and Android integration, some prerequisites on setting up a working android developing environment are required. We will follow a fairly standardized approach to building such environment. The Google Android developer page has already contained extensive information on this topic so please consult the authoritative source to obtain the SDK and related plug-in.

Please review the following checklist before proceeding

2. Creating the application skeleton

The ADT plug-in for Eclipse provides an easy way to prepare the Android application layout. By following the ADT wizard, our APIScript application skeleton is set-up in a matter of few clicks.

When generating the application through ADT helper plug-in, refer to the property sheet shown below

Figure 1. create a new Android project for iPush APIScript

3. Adding iPush Java library

When the above items are satisfied, unzip the iPush Java client package 2.5.2, you will find iceipush2_jvm1.5.jar from unzipped_direcotry\Java\2.5.2\. A quick note on the iceipush2_jvm1.5.jar: this build is optimized for JDK 5 or above comparing to another jar file found in the same path.

While the ADT-generated application (should be named APIScript if you have followed along) is still open in Eclipse, right click on the APIScript in Package Explorer and choose Properties.

In the popped-up dialog window:

  1. Click on Java Build Path to the left then click on the <Libraries> tab.
  2. Click on the Add External JARs button.
  3. Locate where you previously saved iceipush2_jvm1.5.jar
  4. Click OK to dismiss the dialog window

Figure 2. add iPush Java client library to your APIScript project

That's it. iPush Java client library has been successfully referenced in the project.

4. Enable the network access permission

Because iPush client utilizes network resource to establish socket-level connection with iPush Server. This is inherently an operation not permissible on Android by default. We need to explicitly declare our intent by adding a security context permission entry in AndroidManifest.xml.

Opening the AndroidManifest.xml file in text edit mode, after </application> tag, add

<uses-permission android:name="android.permission.INTERNET" />

Or replace your AndroidManifest.xml with the one found in iPush Android APIScript package (the downloaded android_APIScript.zip)

Doing so gives the application the privilege to access network.

5. Designing the UI layout

The nature of APIScript is to allow users type in commands to interact with iPush Server. As such, we will provide a display area, a text input box, and a send button to fulfill the task. Please open the layout file res/layout/main.xml of your APIScript, then replace the existing code with the XML present here:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">

     <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" android:id="@+id/Scroller" android:scrollbars="vertical">
            <com.icetech.android.apiscript.CmdView
                android:id="@+id/List"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_marginBottom="10px"
                android:layout_width="wrap_content"/>
    </ScrollView>

    <RelativeLayout
        android:id="@+id/RelativeLayout01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        
        <EditText
            android:id="@+id/Console"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="55dip"
            android:lines="1"
            android:text="conn "/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send"
            android:id="@+id/Send" android:bufferType="normal" android:freezesText="true" android:layout_alignParentRight="true"/>        

    </RelativeLayout>
</LinearLayout>

The same file is also shipped with our iPush Android APIScript package under path unzipped_direcotry\APIScript\res\layout\main.xml.

The layout is seen in the following screen shot in its final form. The display surface will be auto-scrolled when the accumulated text exceeds the height of the screen.

Figure 3. the UI layout of APIScript

6. Get codes ready

Please copy all 4 source files in iPush Android APIScript package under path unzipped_direcotry\APIScript\src\com\icetech\android\apiscript\ to your APIScript project folder (your_workspace\APIScript\src\com\icetech\android\apiscript\ by default). Check the file list in red borderline below:

Figure 4. get the 4 source files for your APIScript

7. Run it

Make sure the computer runs Android Emulator is connecting to Internet, press F11 key in Eclipse to run your APIScript in Android Emulator. When APIScript is ready, you may play the publish/subscribe messaging functionality of iPush with a public account on Push4Free.com:

1. To connect to the server with a test account, please type the following command in the input field, then send it by clicking Send button or pressing Enter key:

conn www.push4free.com 443 android test foo bar

It should return doCmdConn = 1 if connection is successfully established.

Figure 5. status of connecting to iPush Server

To subscribe to a subject, type the following command in the input field, then click Send button or press Enter key:

sub ice

It should return <onException>: 700, ice - Subject Command OK if subscription completes successfully.

Figure 6. status of subscribing subject ice

2. Run a new Android Emulator as second instance by double click emulator.exe under the folder Android_SDK_root\tools. After the emulator starts, press F11 key in Eclipse again and select the second instance in the target device list (check out the number):

Figure 7. select the second Android Emulator instance

Connect and subscribe to iPush Server with the following command one at a time in the second emulator instance:

conn www.push4free.com 443 android test foo bar
sub ice

It should receive the same response message as with the first one:

Figure 8. status of connecting and subscribing to iPush Server

3. Send "hello" by subject ice with the following command in the second instance:

send ice hello

It should return Send Message: pos=0, len=5, chksum=xxxxxxx when sent successfully.

Figure 9. sent "hello" to iPush Server by subject ice from the second instance

Switch back to the first emulator instance, it should receive the string hello by showing <onSubj>: subj=ice, ......: hello as it subscribed to subject ice.

Figure 10. received the "hello" from iPush Server in the first instance

Please note the second emulator instance should receive the string hello too because it also subscribed to subject ice.

With this APIScript, we are demonstrating that the bi-directional communication of iPush application is working well on Android system by using iPush Java client library. We also had run it successfully on real Android device, the HTC G1 too.

To see a complete list of possible commands of APIScript please type help command in the emulator.

8. Processing the user input

The APIScript that ships with iPush Java client package has already provided the necessary logic and operation. We will not be reinventing the wheel to rewrite everything from scratch. Rather, we will modify the original APIScript to work with the APIScript for Android. We do not want to go into the code details too much so here are the highlights on what have been modified.

The original Java APIScript accepts the user input from system input stream (System.in) and writes the output to system out stream (System.out). For the Android APIScript application, the input stream effectively becomes the input received from input field and the display surface takes over the System.out.

In APIScript class, the method void doSend() processes the user input whenever user clicks on the Send button or presses Enter key in the input field. doSend() in turn calls the method public void parseCmd(String line)defined in Scripter class.

The logic flow is expressed as:

  1. Text is typed into the input field.
  2. Either Send button is clicked or Enter key is pressed while the input field is having the input focus.
  3. doSend() captures the inputted text.
  4. parseCmd()accepts the input as if the input came from System.in stream.
  5. Input is sent to iPush Server as command string.

9. Updating response from iPush Server

Displaying the response from iPush Server is the reverse of sending it, the method public void log(String msg) defined in Scripter class calls the method void queueMessage(String line) to have the UI thread display the response text on the display pane.

Under the hood, the iPush connection and communication is executed in a separate thread. The iPush thread cannot directly modify UI components created by the UI thread. If the iPush thread is to manipulate the UI component, such initiative must be resolved using Handler's scheduling message mechanism.

The logic flow is expressed as:

  1. Response text is received by iPush thread.
  2. iPush thread inserts the response text into UI thread's message queue.
  3. iPush thread notifies UI thread of the pending request.
  4. UI thread fetches the message from the queue and updates the display pane with the latest message.

10. Packaging the application for deployment

The ADT plug-in is also used to package the application. Doing so is an effortless and seamless operation.

Figure 11. export the unsigned package

Right click on the APIScript project brings up the menu, near the very bottom of it (as shown above) you will find the Android Tools. Clicking on the Export Unsigned Application Package, choosing where you would like the packaged file saved, and -- voila! -- you now have the application prepared for final deployment.

However, before we can actually install the application on real device running Android system, the application needs to be digitally signed to satisfy security concerns. Android application can be signed using keytool and jarsigner utilities shipped with Sun's Java distribution.

To sign the application, we obtain a self-signed private key generated by keytool. The following demonstrates a pseudo-example:

"%JAVA_HOME%"/bin/keytool -genkey -v -keystore icetech.keystore -alias icetech -keyalg RSA -validity 10500

You will be prompted to provide relevant information including password for this keystore. The private key will be generated and saved as icetech.keystore with which we use to sign our application. To sign the application, we change to the directory of the exported APIScript.apk and copy the icetech.keystore to that directory as well. After all is done, the following command signs it:

jarsigner -verbose -keystore icetech.keystore APIScript.apk icetech

This step requires you to enter the pass phrase associated with the private key. When provided correctly, the application will be signed and can be installed on real device running Android system.

Please be reminded that application signing is a non-trivial Android task whose detail is beyond the scope of this article. A complete reference guide can be found on http://code.google.com/android/devel/sign-publish.html.

 

11. Install the APIScript to your Android device

For your convenience, we has prepared the Android run-time package APIScript.apk, before you download and install it on your Android device, the device must be set to allow the install of non-Market applications. For setting this, take HTC G1 for example, run

[Settings] - [Applications] - check [Unknown sources]

For downloading and installing APIScript.apk, use the [Browser] on Android device, go to URL: http://www.icetechnology.com/developer/documents/APIScript.apk.

After download the package, just allow it for network accessing. Then you can play the APIScript on the device.

It takes only 34KB for download, 92KB for device storage.

 

Learn more