Doing Synchronization Using Pervasync Client for Android and Blackberry

We will first show the Pervasync client working in standalone mode and then describe how to embed the client in to your Android or Blackberry app.

Starting Sync Sessions and Viewing Sync History

Once the sync client is installed and setup, you can click on the “Start Sync” button on the Sync screen of the Pervasync client.

During synchronization, the Sync screen will show you the progress. Once completed, the sync history is available on the History screen. For Android, you switch between screens by clicking on the tabs while for Blackberry, you click on the menu items.

NOTE: If you see non-empty “Sent(bytes)” but empty “Received” and sync seems to get stuck, most likely you have a typo in sync URL or the sync server is not up. Use the “Setup” tab to correct the URL. Make sure you have the right IP and port number.

Below are Sync and History screen shots for Android and Blackberry respectively.

Updating Setup Info and Configuring Auto Sync

NOTE: In the following we will only show screen shots for Android. Blackberry screens are similar. The main difference is that instead of tabs, you usually use menu items to navigate to different screens on Blackberry.

The Setup screen allows you to update the setup info. It also allows you to reset the client to pre-setup state.

The Scheduler screen allows you to schedule sync jobs so that you don’t have to manually initiate each sync session. Normally you would turn on the “Repeat” flag to make the sync happen periodically with a preset sync interval. Note that you need to have both the Job Scheduler running and the job enabled for the auto sync to be on.

Database and File Browser

The Browser screen allows you to inspect the databases and files that are synced to the device. You may want to hide this functionality from end users after you compose your own user interface to the synced data. However, it’s a great tool to use during development of your application that uses Pervasync for data synchronization.

The Browser screen lists all the schemas/databases and folders. Clicking on a schema will bring up a dialogue with options to show tables or sequences that belong to the schema.

Following are the table list and sequence list.

Click on table to show table definition and table data. The table data screen will by default show 10 rows. You can change the Fetch Limit to show more or less than that. You can also put a predicate in the Where Clause box to show the desired rows, for example:

NAME like ‘%Jonh%’

Click on a row to bring up the row editor screen where you can delete or update the row data. You could also insert a new row using this screen.

Back to the main Browser screen, you can click on a sync folder to show the sub folders and files.

Syncing Data and Files to External Storage

If you run the sync client in standalone mode (as opposed to embedding it into your device app), your app usually won’t be able to access the synced data unless the data is on external storage. To sync data and files to external storage, prefix the client schema name and client folder name with “EXTERNAL;”. Note the trailing semi colon.

Embedding Pervasync Client into Your Android Application on Device

If you run the sync client in standalone mode, your app usually won’t be able to access the synced data unless the data is on external storage. Instead, if you embed the sync client into your own application, both the sync client code and your app code share the same permissions to the data and you would be able to store the data on internal and external storages.

The “android/lib” folder of your Pervasync server home has a Pervasync client library jar that you can easily include into your app.

Let’s assume you created an Android project “my_android_app” in your Eclipse workspace. Your package name is “com.mycorp.myapp” and your main Activity is “MyMainActivity”. The AndroidManifest.xml of your project would look like the following:

<?xml
version=“1.0”
encoding=“utf-8”?>

<manifest package=“com.mycorp.myapp” android:versionCode=“1”

    android:versionName=“1.0” xmlns:android=http://schemas.android.com/apk/res/android&#8221;>

    <application
android:icon=“@drawable/icon”

        android:label=“My Android App”>

        <activity
android:name=“.MyMainActivity”
android:label=“@string/app_name”>

            <intent-filter>

                <action
android:name=“android.intent.action.MAIN” />

                <category
android:name=“android.intent.category.LAUNCHER” />

            </intent-filter>

</application>

    <uses-sdk
android:minSdkVersion=“7”
android:targetSdkVersion=“7” />


</manifest>

Following are the steps to embed Pervasync client.

Add Pervasync Android client library to Java Build Path

Right click on your Eclipse project for your Android app and open the “Properties” window. Click on “Java Build Path” on the left panel and then click the “Libraries” tab on the right panel. Click on “Add External JARs…” button to add Pervasync Android client library “pervasync_android_lib-4.0.0.jar” which is located in the “android/lib” folder of Pervasync server home.

NOTE: If your Pervasync server and your Eclipse IDE are on different hosts, just copy the jar to your Eclipse host.

After adding the jar, click the “Order and Export” tab. Select the check box in front of “pervasync_android_lib-4.0.0.jar”.

Add Pervasync Activities and Permissions to AndroidManifest.xml

Copy-paste the “activity” and “uses-permission” elements from the following sample AndroidManifest.xml (see also android/AndroidManifest_sample.xml) to your AndroidManifest.xml.

NOTE: Don’t copy the grayed-out parts. Your AndroidManifest.xml should already have them.

<?xml version=“1.0” encoding=“utf-8”?>

<manifest package=“com.mycorp.myapp” android:versionCode=“1”

    android:versionName=”1.0″ xmlns:android=”http://schemas.android.com/apk/res/android”&gt;

    <application android:icon=“@drawable/icon”

        android:label=“My Android App”>

        <activity android:name=“.MyMainActivity” android:label=“@string/app_name”>

            <intent-filter>

                <action android:name=“android.intent.action.MAIN” />

                <category android:name=”android.intent.category.LAUNCHER” />

            </intent-filter>

        </activity>

        <activity android:name=“pervasync.ui.android.PervasyncClientActivity”

            android:label=“Pervasync”>

        </activity>


        <service
android:name=“pervasync.ui.android.PervasyncService”>

            <intent-filter>

                <action
android:name=“pervasync.ui.android.PervasyncService” />

            </intent-filter>

        </service>

        <activity android:name=“pervasync.ui.android.PervasyncSyncActivity”

            android:label=“Pervasync Sync”>

        </activity>

        <activity android:name=“pervasync.ui.android.AutoSyncSchedulerActivity”

            android:label=“Pervasync Scheduler”>

        </activity>

        <activity android:name=“pervasync.ui.android.PervasyncHistoryActivity”

            android:label=“Pervasync Sync History”>

        </activity>

        <activity android:name=“pervasync.ui.android.PervasyncSetupActivity”

            android:label=“Pervasync Setup”>

        </activity>

        <activity android:name=“pervasync.ui.android.PervasyncBrowserActivity”

            android:label=“Pervasync Browser”>

        </activity>

        <activity android:name=“pervasync.ui.android.SchemaTablesActivity”

            android:label=“Schema Tables”>

        </activity>


        <activity android:name=“pervasync.ui.android.FolderFilesActivity”

            android:label=“File Browser”>

        </activity>

        <activity android:name=“pervasync.ui.android.SchemaSequencesActivity”

            android:label=“Schema Sequences”>

        </activity>

        <activity android:name=“pervasync.ui.android.TableRowsActivity”

            android:label=“Table Data”>

        </activity>

        <activity android:name=“pervasync.ui.android.TableColumnsActivity”

            android:label=“Table Column Types”>

        </activity>

        <activity android:name=“pervasync.ui.android.RowEditActivity”

            android:label=“Row Edit”>

        </activity>

        <activity android:name=“pervasync.ui.android.ImageFileActivity”

            android:label=“Image File”>

        </activity>

        <activity android:name=“pervasync.ui.android.TextFileActivity”

            android:label=“TextFile”>

        </activity>

        <receiver
android:enabled=“true”
android:name=“pervasync.ui.android.BootUpReceiver”

            android:permission=“android.permission.RECEIVE_BOOT_COMPLETED”>

            <intent-filter>

                <action
android:name=“android.intent.action.BOOT_COMPLETED” />

                <category
android:name=“android.intent.category.DEFAULT” />

            </intent-filter>

        </receiver>

    </application>

    <uses-sdk android:minSdkVersion=“7” android:targetSdkVersion=“7” />

<uses-permission
android:name=“android.permission.RECEIVE_BOOT_COMPLETED” />

    <uses-permission
android:name=“android.permission.ACCESS_NETWORK_STATE”></uses-permission>

    <uses-permission
android:name=“android.permission.ACCESS_WIFI_STATE”></uses-permission>

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

    <uses-permission
android:name=“android.permission.WRITE_EXTERNAL_STORAGE”></uses-permission>

</manifest>

Invoke Pervasync Client from Your App Code

With the inclusion of the library and the additions to the manifest file, Pervasync is now part of your application. You can now invoke Perasync. In the main activity of your app, you should start the Pervasync service so that it can perform auto-sync in the background:

if (!PervasyncService.isStarted()) {

    startService(new Intent(this, PervasyncService.class));

}

To show the Pervasync UI, start the Pervasync client activity:

Intent intent = new Intent(myMainActivity,

PervasyncClientActivity.class);

startActivity(intent);

Following is a sample main activity:

package com.mycorp.myapp;

import pervasync.ui.android.PervasyncService;

import pervasync.ui.android.PervasyncClientActivity;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.Gravity;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.LinearLayout;

import android.widget.TextView;

import android.widget.LinearLayout.LayoutParams;

/*

* This is the main screen of your app

*/

public
class MyMainActivity extends Activity {

    private
static
final
int
SYNC_CLIENT_ID = 0;

    private
final MyMainActivity myMainActivity = this;

    /** Called when the activity is first created. */

    @Override

    public
void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // start Pervasync service if not already started.

        if (!PervasyncService.isStarted()) {

            startService(new Intent(this, PervasyncService.class));

        }

        // set title

        setTitle(“Pervasync Sample App”);

        // contentView is a LinearLayout

        LinearLayout contentView = new LinearLayout(this);

        contentView.setOrientation(LinearLayout.VERTICAL);

        this.setContentView(contentView);

        // empty line

        contentView.addView(new TextView(myMainActivity));

        // description

        String description = “This is a place holder main screen for your application. “

                + “You can replace the title, add UI components to the screen and add “

                + “child screens that can be linked from this main screen.\n\n”

                + “We added a button below that invokes the Pervasync Client main screen where users can setup “

                + “Pervasync and perform synchronization.\n\n”

                + “The Pervasync Client also includes a database browser for you to explore the “

                + “synced databases during developemnt time. You could hide the browser in the production “

                + “version of your app.”;

        TextView textView = new TextView(this);

        textView.setText(description);

        contentView.addView(textView);

        // empty line

        contentView.addView(new TextView(myMainActivity));

        // buttonBar

        LinearLayout buttonBar = new LinearLayout(myMainActivity);

        buttonBar.setGravity(Gravity.CENTER); // How button bar aligns its

                                                // children

        buttonBar.setOrientation(LinearLayout.HORIZONTAL);

        contentView.addView(buttonBar, new LinearLayout.LayoutParams(

                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        // Launch Pervasync Client button

        Button pervasyncButton = new Button(this);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(

                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        pervasyncButton.setLayoutParams(params);

        pervasyncButton.setText(“Launch Pervasync Client”);

        pervasyncButton.setTag(“Pervasync”);

        pervasyncButton.setOnClickListener(new OnClickListener() {

            public
void onClick(View view) {

                Button button = (Button) view;

                if (“Pervasync”.equalsIgnoreCase((String) button.getTag())) {

                    Intent intent = new Intent(myMainActivity,

                            PervasyncClientActivity.class);

                    startActivity(intent);

                }

            }

        });

        buttonBar.addView(pervasyncButton);

    }

    @Override

    public
boolean onCreateOptionsMenu(Menu menu) {

        menu.add(Menu.NONE, SYNC_CLIENT_ID, Menu.CATEGORY_CONTAINER,

                “Launch Pervasync Client”);

        return (super.onCreateOptionsMenu(menu));

    }

    @Override

    public
boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

        case
SYNC_CLIENT_ID:

            startActivity(new Intent(myMainActivity,

                    PervasyncClientActivity.class));

            return (true);

        default:

            ;

        }

        return
super.onOptionsItemSelected(item);

    }

}

You can now build and run your Android app.

Advanced Topics

OTA Deployment

Once you package and sign your app with Android signature tool, you will have an apk file generated. Copy the apk file, e.g. my_android_app.apk, to <Pervasync Server Home>/web/pervasync/download and your users can install the app over-the-air (OTA) by entering the following URL in their mobile browser:

http://<Pervasync_Host&gt;:<port>/pervasync/download/my_android_app.apk

Javadoc

You can find Javadoc of the Pervasync client interface in <Pervasync Server Home>/android/doc. Open the index.html in a browser.

Embedding Pervasync Client into Your Blackberry Application on Device

If you embed the sync client into your own application, both the sync client code and your app code share the same permissions to the data. This allows you to secure the data so that only your app (including sync code) can access the data.

The “blackberry/lib” folder of your Pervasync server home has a Pervasync client library jar that you can easily include into your app.

Let’s assume you created a Blackberry project “my_blackberry_app” in your Eclipse workspace. Your package name is “com.mycorp.myapp” and your UIApplication is “MyBlackberryApp”. You also have a MainScreen called “MyMainScreen”.

Following are the steps to embed Pervasync client.

Add Pervasync Blackberry client library to Java Build Path

Right click on your Eclipse project for your Blackberry app and open the “Properties” window. Click on “Java Build Path” on the left panel and then click the “Libraries” tab on the right panel. Click on “Add External JARs…” button to add Pervasync Blackberry client library “pervasync_blackberry_lib-4.0.0.jar” which is located in the “blackberry/lib” folder of Pervasync server home.

NOTE: If your Pervasync server and your Eclipse IDE are on different hosts, just copy the jar to your Eclipse host.

After adding the jar, click the “Order and Export” tab. Select the check box in front of “pervasync_blackberry_lib-4.0.0.jar”.

Enable Auto-Run

Open Blackberry_App_Descriptor.xml under your app project and select the checkbox “Auto-run on start”. This is to auto start your app after a device re-boot so that your app can do auto-sync in the background.

Invoke Pervasync Client from Your App Code

With the inclusion of the library, Pervasync is now part of your application. In the UIApplication “MyBlackberryApp” of your app, you should start the Pervasync JobScheduler so that it can perform auto-sync in the background:

if(!SyncClient.needSetup()){

SyncClient.restartJobScheduler();

}

To show the Pervasync UI, push PervasyncSyncScreen in your MyMainScreen class:

UiApplication.getUiApplication().pushScreen(

                    new PervasyncSyncScreen());

Following is a sample UIApplication “MyBlackberryApp”:

package com.mycorp.myapp;

import pervasync.client.SyncClient;

import net.rim.device.api.ui.UiApplication;

public
class MyBlackberryApp extends UiApplication {

    /**

     * This is a place holder for your Blackberry application.

     * You could replace the package name and class name.

     * @param args

     * @throws Exception

     */

    public
static
void main(String[] args) throws Exception {

        MyBlackberryApp myBlackberryApp = new MyBlackberryApp();

        myBlackberryApp.enterEventDispatcher();

    }

    /**

     * Constructor. Displays the main screen of your application

     * @throws Exception

     */

    public MyBlackberryApp() throws Exception {

        // start Pervasync job scheduler if you want to have auto sync

        if(!SyncClient.needSetup()){

            SyncClient.restartJobScheduler();

        }


        // show the app main screen

        pushScreen(new MyMainScreen());

    }

}

Following is a sample MainScreen “MyMainScreen”:

package com.mycorp.myapp;

import net.rim.device.api.ui.Font;

import net.rim.device.api.ui.MenuItem;

import net.rim.device.api.ui.UiApplication;

import net.rim.device.api.ui.component.Dialog;

import net.rim.device.api.ui.component.LabelField;

import net.rim.device.api.ui.component.RichTextField;

import net.rim.device.api.ui.component.SeparatorField;

import net.rim.device.api.ui.container.MainScreen;

import pervasync.client.SyncClient;

import pervasync.ui.blackberry.PervasyncSyncScreen;

public
class MyMainScreen extends MainScreen {

    /**

     * Constructor

     */

    public MyMainScreen() {

        // set page title

        LabelField title = new LabelField(“My Blackberry App”,

                LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);

        setTitle(title);

        // set header

        addHeader(“My Blackberry App Main Screen”);

        // set description

        String description = “This is a place holder main screen for your application. “

            + “You can replace the title, add UI components to the screen and add “

            + “child screens that can be linked from this main screen.\n\n” +

            “We added a menu item that invokes the Pervasync Client main screen where users can setup “+

            “Pervasync and perform synchronization.\n\n” +

            “The Pervasync Client also includes a database browser for you to explore the “+

            “synced databases during developemnt time. You could hide the browser in the production “ +

            “version of your app”;

        RichTextField richTextField = new RichTextField(description,

                RichTextField.READONLY);

        add(richTextField);

    }

    /**

     * Helper to add a bold typed header

     * @param labelStr

     */

    private
void addHeader(String labelStr) {

        LabelField labelField = new LabelField(labelStr,

                LabelField.FIELD_HCENTER);

        labelField.setFont(labelField.getFont().derive(Font.BOLD));

        this.add(labelField);

        this.add(new SeparatorField());

    }

    /**

     * Put the app in the background when closing.

     */

    public
boolean onClose() {

        UiApplication.getUiApplication().requestBackground();

        return
true;

    }

    /**

     * Kill the app on exit

     */

    private
void exit() {

        if (SyncClient.isSynchronizing()) {

            int retVal = Dialog

                    .ask(Dialog.D_YES_NO,

                            “Exiting will kill the on-going sync session. Are you sure you want to exit?”);

            if (retVal == Dialog.YES) {

                System.exit(0);

            }

        } else {

            System.exit(0);

        }

    }

    /**

     * Pervasync Client Menu Item

     */

    private
final
class PervasyncMenuItem extends MenuItem {

        private PervasyncMenuItem() {

            super(“Pervasync Client”, 1, 1);

        }

        public
void run() {

            UiApplication.getUiApplication().pushScreen(

                    new PervasyncSyncScreen());

        }

    }

    /**

     * Exit Menu Item

     */

    private
final
class ExitMenuItem extends MenuItem {

        private ExitMenuItem() {

            super(“Exit”, Integer.MAX_VALUE, 1);

        }

        public
void run() {

            exit();

        }

    }

    /**

     * This is called when user invokes menu

     */

    public
boolean onMenu(int instance) {

        removeAllMenuItems();

        addMenuItems();

        return
super.onMenu(instance);

    }

    private
void addMenuItems() {

            PervasyncMenuItem pervasyncMenuItem = new PervasyncMenuItem();

            this.addMenuItem(pervasyncMenuItem);

        ExitMenuItem exitMenuItem = new ExitMenuItem();

        this.addMenuItem(exitMenuItem);

    }

}

You can now build and run your Blackberry app.

Advanced Topics

Encryption

To encrypt the database, prefix the client schema name with “ENCRYPT;” when you publish the sync schema. If you want it be both encrypted and stored on external storage, use prefix “EXTERNAL; ENCRYPT;”.

Note that other apps on the device can still access the databases when it’s encrypted. To further secure your DB so that only your app can access it, use prefix “PROTECT;”.

OTA Deployment

Once you package and sign your app with Blackberry signature tool, you will have a jad file and some cod files generated (e.g. in <your project root>/deliverables/Web/6.0.0). Copy these files to <Pervasync Server Home>/web/pervasync/download and your users can install the app over-the-air (OTA) by entering the following URL in their mobile browser:

http://<Pervasync_Host&gt;:<port>/pervasync/download/my_blackberry_app.jad

Javadoc

You can find Javadoc of the Pervasync client interface in <Pervasync Server Home>/android/doc. Open the index.html in a browser.

Advertisements

9 thoughts on “Doing Synchronization Using Pervasync Client for Android and Blackberry

  1. Hi,
    Wanted to know if I can embed the pervasync class in a frame of my own. The problem is I am calling the pervasync initially during application installation to sync DB from server. But I have some more tasks to do after the DB is setup. So I need a handle back to my application once the sync is completed or atleast a button to go back from where it was initiated. How can this be done?

      • I tried the tab approach but a click on any of the pop-ups is making the application to crash. Do you have a fix for the same or any alternate approach?

  2. I’m planning to develop an Android app. It has a central MySQL database on a webserver and clients have SQLite databases created locally. Both have the same table structure and data. What I need is, if I do any changes in the central MySQL DB (insert new record. alter record), when a user starts the app, check with the central DB and if there are any changes in the main DB, update the local SQLite DB with those changes automatically without prompting any sort of message or anything to the user.

    Is it possible to do that with this pervasync?
    If so how would I have to pay for this product? Do I have to buy one license per client or a only one server license?

    Please clarify these for me. Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s