Parse.com provides a set of handy tools to rapidly build mobile applications that needs back-end. One of the main provided features is the push notifications that enables asynchronous and real-time communiation. This post illustrates how to set up the push mechnism in an Android application.
- First, we need to create an Account at Parse.com and register an application to have an application key and client key
- Second, in the application settings wen have to enable push notifications
- Then, download the latestes Parse SDK, i.e. the parse.jar
- Finally, code time
In the manifest, we need to add the following lines to ask permessions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
Then, before the </application> register a broadcast receiver
<receiver android:name=".PushReceiver">
<intent-filter>
<action android:name="com.telethonix.NOTIFICATION"> </action>
</intent-filter>
</receiver>
Then create the
PushReceiver class as follow:
public class PushReceiver extends BroadcastReceiver {
public final static String TAG = PushReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
try {
Bundle extras = intent.getExtras();
String message = extras != null ? extras.getString("com.parse.Data") : "";
Log.i(TAG, "Received message: "+message);
// do something with the received data
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Finnaly in the main activity, we should initiate parse with the application keys, and send a notification
String app_id = "your application key";
String client_key = "your client key";
Parse.initialize(this, app_id, client_key);
// subscribe to be notified
PushService.subscribe(MainActivity.this, "channel", MainActivity.class);
// push a message
ParsePush push = new ParsePush(); push.setChannel("channel");
push.setData(data);
push.sendInBackground(new SendCallback(){
@Override
public void done(ParseException arg0){
Log.i(TAG, "push sent done!");
}
});
More details at
Push Developer Guide.