Skip to content

Commit 189face

Browse files
author
Devendra
committed
gcm changes to demo app
1 parent 269520d commit 189face

3 files changed

Lines changed: 337 additions & 6 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.pubnub.examples.pubnubExample;
2+
import android.app.Activity;
3+
import android.content.ComponentName;
4+
import android.content.Context;
5+
import android.content.Intent;
6+
import android.support.v4.content.WakefulBroadcastReceiver;
7+
8+
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
9+
@Override
10+
public void onReceive(Context context, Intent intent) {
11+
// Explicitly specify that GcmIntentService will handle the intent.
12+
ComponentName comp = new ComponentName(context.getPackageName(),
13+
GcmIntentService.class.getName());
14+
// Start the service, keeping the device awake while it is launching.
15+
startWakefulService(context, (intent.setComponent(comp)));
16+
setResultCode(Activity.RESULT_OK);
17+
}
18+
19+
}
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package com.pubnub.examples.pubnubExample;
2+
3+
import com.google.android.gms.gcm.GoogleCloudMessaging;
4+
5+
import android.app.IntentService;
6+
import android.app.NotificationManager;
7+
import android.app.PendingIntent;
8+
import android.content.Context;
9+
import android.content.Intent;
10+
import android.os.Bundle;
11+
import android.os.SystemClock;
12+
import android.support.v4.app.NotificationCompat;
13+
import android.util.Log;
14+
15+
public class GcmIntentService extends IntentService {
16+
public static final int NOTIFICATION_ID = 1;
17+
private static final String TAG = "PubnubGcm";
18+
private NotificationManager mNotificationManager;
19+
NotificationCompat.Builder builder;
20+
21+
public GcmIntentService() {
22+
super("GcmIntentService");
23+
}
24+
25+
@Override
26+
protected void onHandleIntent(Intent intent) {
27+
Bundle extras = intent.getExtras();
28+
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
29+
// The getMessageType() intent parameter must be the intent you received
30+
// in your BroadcastReceiver.
31+
String messageType = gcm.getMessageType(intent);
32+
33+
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
34+
/*
35+
* Filter messages based on message type. Since it is likely that GCM
36+
* will be extended in the future with new message types, just ignore
37+
* any message types you're not interested in, or that you don't
38+
* recognize.
39+
*/
40+
if (GoogleCloudMessaging.
41+
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
42+
sendNotification("Send error: " + extras.toString());
43+
} else if (GoogleCloudMessaging.
44+
MESSAGE_TYPE_DELETED.equals(messageType)) {
45+
sendNotification("Deleted messages on server: " +
46+
extras.toString());
47+
// If it's a regular GCM message, do some work.
48+
} else if (GoogleCloudMessaging.
49+
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
50+
// This loop represents the service doing some work.
51+
for (int i=0; i<5; i++) {
52+
Log.i(TAG, "Working... " + (i+1)
53+
+ "/5 @ " + SystemClock.elapsedRealtime());
54+
try {
55+
Thread.sleep(5000);
56+
} catch (InterruptedException e) {
57+
}
58+
}
59+
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
60+
// Post notification of received message.
61+
sendNotification("Received: " + extras.toString());
62+
Log.i(TAG, "Received: " + extras.toString());
63+
}
64+
}
65+
// Release the wake lock provided by the WakefulBroadcastReceiver.
66+
GcmBroadcastReceiver.completeWakefulIntent(intent);
67+
}
68+
69+
// Put the message into a notification and post it.
70+
// This is just one simple example of what you might choose to do with
71+
// a GCM message.
72+
private void sendNotification(String msg) {
73+
mNotificationManager = (NotificationManager)
74+
this.getSystemService(Context.NOTIFICATION_SERVICE);
75+
76+
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
77+
new Intent(this, MainActivity.class), 0);
78+
79+
NotificationCompat.Builder mBuilder =
80+
new NotificationCompat.Builder(this)
81+
.setSmallIcon(R.drawable.icon)
82+
.setContentTitle("GCM Notification")
83+
.setStyle(new NotificationCompat.BigTextStyle()
84+
.bigText(msg))
85+
.setContentText(msg);
86+
87+
mBuilder.setContentIntent(contentIntent);
88+
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
89+
}
90+
}

‎android/examples/PubnubExample/src/com/pubnub/examples/pubnubExample/MainActivity.java‎

Lines changed: 228 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
package com.pubnub.examples.pubnubExample;
22

3-
import java.util.Hashtable;
3+
import java.io.IOException;
44

5-
import android.view.View;
6-
import android.widget.LinearLayout;
75
import org.json.JSONArray;
86
import org.json.JSONObject;
97

@@ -14,19 +12,31 @@
1412
import android.content.DialogInterface;
1513
import android.content.Intent;
1614
import android.content.IntentFilter;
15+
import android.content.SharedPreferences;
16+
import android.content.pm.PackageInfo;
17+
import android.content.pm.PackageManager.NameNotFoundException;
1718
import android.net.ConnectivityManager;
19+
import android.os.AsyncTask;
1820
import android.os.Bundle;
1921
import android.text.InputType;
22+
import android.text.TextUtils;
23+
import android.util.Config;
2024
import android.util.Log;
2125
import android.view.Menu;
2226
import android.view.MenuItem;
27+
import android.view.View;
2328
import android.widget.EditText;
29+
import android.widget.LinearLayout;
30+
import android.widget.TextView;
2431
import android.widget.Toast;
25-
import android.view.View.OnClickListener;
2632

2733
import com.pubnub.api.Callback;
2834
import com.pubnub.api.Pubnub;
2935
import com.pubnub.api.PubnubError;
36+
import com.pubnub.api.PubnubException;
37+
import com.pubnub.api.PubnubGcmRegistrationIdMissingException;
38+
39+
import com.google.android.gms.gcm.GoogleCloudMessaging;
3040

3141
public class MainActivity extends Activity {
3242
/*
@@ -37,7 +47,15 @@ public class MainActivity extends Activity {
3747
*/
3848

3949
Pubnub pubnub = new Pubnub("demo", "demo", "", false);
40-
50+
GoogleCloudMessaging gcm;
51+
Context context;
52+
String regId;
53+
public static final String SENDER_ID = "750222044802";
54+
public static final String REG_ID = "regId";
55+
private static final String APP_VERSION = "appVersion";
56+
57+
static final String TAG = "Register Activity";
58+
4159
private void notifyUser(Object message) {
4260
try {
4361
if (message instanceof JSONObject) {
@@ -198,12 +216,216 @@ public boolean onOptionsItemSelected(MenuItem item) {
198216
case R.id.option23:
199217
setHeartbeatInterval();
200218
return true;
219+
case R.id.option24:
220+
gcmRegister();
221+
return true;
222+
case R.id.option25:
223+
gcmUnregister();
224+
return true;
225+
case R.id.option26:
226+
gcmAddChannel();
227+
return true;
228+
case R.id.option27:
229+
gcmRemoveChannel();
230+
return true;
231+
case R.id.option28:
232+
gcmRemoveAllChannels();
233+
return true;
201234
default:
202235
return super.onOptionsItemSelected(item);
203236
}
204237
}
205238

206-
private void setHeartbeatInterval() {
239+
private void gcmRemoveAllChannels() {
240+
pubnub.unregisterAllChannelsForDevice(new Callback() {
241+
@Override
242+
public void successCallback(String channel,
243+
Object message) {
244+
notifyUser("GCM REMOVE ALL : " + message);
245+
}
246+
@Override
247+
public void errorCallback(String channel,
248+
PubnubError error) {
249+
notifyUser("GCM REMOVE ALL : " + error);
250+
}
251+
});
252+
253+
}
254+
255+
private void gcmRemoveChannel() {
256+
AlertDialog.Builder builder = new AlertDialog.Builder(this);
257+
builder.setTitle("Remove Channel from GCM");
258+
builder.setMessage("Enter Channel Name");
259+
final EditText edChannelName = new EditText(this);
260+
edChannelName.setInputType(InputType.TYPE_CLASS_TEXT);
261+
builder.setView(edChannelName);
262+
builder.setPositiveButton("Remove",
263+
new DialogInterface.OnClickListener() {
264+
265+
@Override
266+
public void onClick(DialogInterface dialog, int which) {
267+
String channel = edChannelName.getText().toString();
268+
try {
269+
pubnub.unregisterDeviceFromChannel(channel, new Callback() {
270+
@Override
271+
public void successCallback(String channel,
272+
Object message) {
273+
notifyUser("GCM REMOVE : " + message);
274+
}
275+
@Override
276+
public void errorCallback(String channel,
277+
PubnubError error) {
278+
notifyUser("GCM REMOVE : " + error);
279+
}
280+
});
281+
} catch (PubnubGcmRegistrationIdMissingException e) {
282+
gcmRegister();
283+
}
284+
}
285+
});
286+
AlertDialog alert = builder.create();
287+
alert.show();
288+
289+
}
290+
291+
private void gcmAddChannel() {
292+
AlertDialog.Builder builder = new AlertDialog.Builder(this);
293+
builder.setTitle("Add Channel to GCM");
294+
builder.setMessage("Enter Channel Name");
295+
final EditText edChannelName = new EditText(this);
296+
edChannelName.setInputType(InputType.TYPE_CLASS_TEXT);
297+
builder.setView(edChannelName);
298+
builder.setPositiveButton("Add",
299+
new DialogInterface.OnClickListener() {
300+
301+
@Override
302+
public void onClick(DialogInterface dialog, int which) {
303+
String channel = edChannelName.getText().toString();
304+
try {
305+
pubnub.registerDeviceOnChannel(channel, new Callback() {
306+
@Override
307+
public void successCallback(String channel,
308+
Object message) {
309+
notifyUser("GCM ADD : " + message);
310+
}
311+
@Override
312+
public void errorCallback(String channel,
313+
PubnubError error) {
314+
notifyUser("GCM ADD : " + error);
315+
}
316+
});
317+
} catch (PubnubGcmRegistrationIdMissingException e) {
318+
gcmRegister();
319+
}
320+
}
321+
});
322+
AlertDialog alert = builder.create();
323+
alert.show();
324+
325+
}
326+
327+
private void gcmUnregister() {
328+
pubnub.setGcmRegistrationId("");
329+
}
330+
331+
332+
333+
334+
private String gcmRegister() {
335+
pubnub.setCacheBusting(false);
336+
pubnub.setOrigin("dara11.devbuild");
337+
context = getApplicationContext();
338+
gcm = GoogleCloudMessaging.getInstance(this);
339+
String regId = getRegistrationId(context);
340+
341+
if (TextUtils.isEmpty(regId)) {
342+
343+
registerInBackground();
344+
345+
Log.d("RegisterActivity",
346+
"registerGCM - successfully registered with GCM server - regId: "
347+
+ regId);
348+
} else {
349+
Toast.makeText(getApplicationContext(),
350+
"RegId already available. RegId: " + regId,
351+
Toast.LENGTH_LONG).show();
352+
}
353+
return regId;
354+
}
355+
356+
private String getRegistrationId(Context context) {
357+
final SharedPreferences prefs = getSharedPreferences(
358+
MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
359+
String registrationId = prefs.getString(REG_ID, "");
360+
if (registrationId.length() <= 0) {
361+
Log.i(TAG, "Registration not found.");
362+
return "";
363+
}
364+
int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
365+
int currentVersion = getAppVersion(context);
366+
if (registeredVersion != currentVersion) {
367+
Log.i(TAG, "App version changed.");
368+
return "";
369+
}
370+
return registrationId;
371+
}
372+
373+
private static int getAppVersion(Context context) {
374+
try {
375+
PackageInfo packageInfo = context.getPackageManager()
376+
.getPackageInfo(context.getPackageName(), 0);
377+
return packageInfo.versionCode;
378+
} catch (NameNotFoundException e) {
379+
Log.d("RegisterActivity",
380+
"I never expected this! Going down, going down!" + e);
381+
throw new RuntimeException(e);
382+
}
383+
}
384+
385+
private void registerInBackground() {
386+
new AsyncTask<Void, Void, String>() {
387+
@Override
388+
protected String doInBackground(Void... params) {
389+
String msg = "";
390+
try {
391+
if (gcm == null) {
392+
gcm = GoogleCloudMessaging.getInstance(context);
393+
}
394+
regId = gcm.register(SENDER_ID);
395+
Log.d("RegisterActivity", "registerInBackground - regId: "
396+
+ regId);
397+
msg = "Device registered, registration ID=" + regId;
398+
399+
storeRegistrationId(context, regId);
400+
} catch (IOException ex) {
401+
msg = "Error :" + ex.getMessage();
402+
Log.d("RegisterActivity", "Error: " + msg);
403+
}
404+
Log.d("RegisterActivity", "AsyncTask completed: " + msg);
405+
return msg;
406+
}
407+
408+
@Override
409+
protected void onPostExecute(String msg) {
410+
Toast.makeText(getApplicationContext(),
411+
"Registered with GCM Server." + msg, Toast.LENGTH_LONG)
412+
.show();
413+
}
414+
}.execute(null, null, null);
415+
}
416+
417+
private void storeRegistrationId(Context context, String regId) {
418+
final SharedPreferences prefs = getSharedPreferences(
419+
MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
420+
int appVersion = getAppVersion(context);
421+
Log.i(TAG, "Saving regId on app version " + appVersion);
422+
SharedPreferences.Editor editor = prefs.edit();
423+
editor.putString(REG_ID, regId);
424+
editor.putInt(APP_VERSION, appVersion);
425+
editor.commit();
426+
}
427+
428+
private void setHeartbeatInterval() {
207429
AlertDialog.Builder builder = new AlertDialog.Builder(this);
208430
builder.setTitle("Set Presence Heartbeat Interval");
209431
builder.setMessage("Enter heartbeat value in seconds");

0 commit comments

Comments
 (0)