Commit 1d660fe9 authored by Bob Easterday's avatar Bob Easterday
Browse files

Add support for background notifications

parent e52c125f
Loading
Loading
Loading
Loading
+2 −1
Changes for Example/server/pushGCM.rb: 2 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -4,5 +4,6 @@ GCM.host = 'https://android.googleapis.com/gcm/send'
GCM.format = :json
GCM.key = "API_KEY_GOES_HERE"
destination = ["REGISTRATION_ID_GOES_HERE"]
data = {:message => "PhoneGap Build rocks!", :msgcnt => "1"}
data = {:message => "PhoneGap Build rocks!", :msgcnt => "1", :soundname => "beep.wav"}

GCM.send_notification( destination, data)
+13 −0
Changes for Example/www/index.html: 13 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -56,6 +56,19 @@
                    break;
                    
                    case 'message':
                    	// if this flag is set, this notification happened while we were in the foreground.
                    	// you might want to play a sound to get the user's attention, throw up a dialog, etc.
                    	if (e.foreground)
                    	{
							$("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');
							
							// if the notification contains a soundname, play it.
							var my_media = new Media("/android_asset/www/"+e.soundname);
							my_media.play();
						}
						else	// otherwise we were launched because the user touched a notification in the notification tray.
							$("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
                    
						$("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.message + '</li>');
						$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.msgcnt + '</li>');
                    break;
+4 −1
Changes for plugin.xml: 4 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -2,7 +2,7 @@
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
    xmlns:android="http://schemas.android.com/apk/res/android"
    id="com.adobe.plugins.PushPlugin"
    version="1.0.1">
    version="1.1.0">
    <name>PushPlugin</name>

	<asset src="www/PushNotification.js" target="PushNotification.js" />
@@ -13,6 +13,7 @@
        </config-file>
    
		<config-file target="AndroidManifest.xml" parent="/manifest">
			<uses-permission android:name="android.permission.GET_TASKS" />
			<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
			<uses-permission android:name="android.permission.GET_ACCOUNTS" />
			<uses-permission android:name="android.permission.WAKE_LOCK" />
@@ -22,6 +23,7 @@
  		</config-file>
  		
     	<config-file target="AndroidManifest.xml" parent="/manifest/application">
			<activity android:name="com.plugin.GCM.PushHandlerActivity"/>
 			<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
 				<intent-filter>
 					<action android:name="com.google.android.c2dm.intent.RECEIVE" />
@@ -38,6 +40,7 @@
 		<source-file src="src/android/com/google/android/gcm/GCMRegistrar.java" target-dir="src/com/google/android/gcm/" />
 		<source-file src="src/android/com/google/android/gcm/GCMIntentService.java" target-dir="src/com/google/android/gcm/" />
 		<source-file src="src/android/com/plugin/GCM/PushPlugin.java" target-dir="src/com/plugin/GCM/" />
 		<source-file src="src/android/com/plugin/GCM/PushHandlerActivity.java" target-dir="src/com/plugin/GCM/" />
		
    </platform>

+84 −7
Changes for src/android/com/google/android/gcm/GCMIntentService.java: 84 added lines, 7 removed lines.
Original line number Diff line number Diff line
package com.google.android.gcm;

import java.io.IOException;
import java.util.List;

import com.plugin.GCM.PushHandlerActivity;
import com.google.android.gcm.*;

import org.apache.cordova.example.R;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import com.plugin.GCM.PushPlugin;


@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {

  public static final String ME="GCMReceiver";
  public static final int notificationID = 237;

  public GCMIntentService() {
    super("GCMIntentService");
@@ -57,39 +78,95 @@ public class GCMIntentService extends GCMBaseIntentService {

    // Extract the payload from the message
	Bundle extras = intent.getExtras();
    if (extras != null) {
    if (extras != null)
    {
    	boolean	foreground = this.isInForeground();
    	extras.putBoolean("foreground", foreground);
    	
    	// we can't call into the JS app if we are in the background
    	if (foreground)
    	{
    		try
    		{
    			JSONObject json;
    			json = new JSONObject().put("event", "message");
            	

    			// My application on my host server sends back to "EXTRAS" variables message and msgcnt
    			// Depending on how you build your server app you can specify what variables you want to send
        //
    			json.put("message", extras.getString("message"));
    			json.put("msgcnt", extras.getString("msgcnt"));
    			json.put("soundname", extras.getString("soundname"));
    			json.put("foreground", foreground);

    			Log.v(ME + ":onMessage ", json.toString());

    			PushPlugin.sendJavascript( json );
        // Send the MESSAGE to the Javascript application
    		}
    		catch( JSONException e)
    		{
    			Log.e(ME + ":onMessage", "JSON exception");
    		}
    	}
    	else
    		this.onReceive(context, extras);
	}
  }
  
	// This is called for all notifications, whether the app is in the foreground or the background.
	// This is so we can update any existing notification in the tray, for our app.
	public void onReceive(Context context, Bundle extras)
	{
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		CharSequence appName = context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
		if (null == appName)
			appName = "";
		
		Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
		notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		notificationIntent.putExtra("pushBundle", extras);
		
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);		

		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
		.setSmallIcon(R.drawable.icon)
		.setWhen(System.currentTimeMillis())
		.setContentTitle(appName)
		.setTicker(appName)
		.setContentText(extras.getString("message"))
		.setNumber(Integer.parseInt(extras.getString("msgcnt")))
		.setContentIntent(contentIntent);
		
		mNotificationManager.notify(notificationID, mBuilder.build());
	
		try
		{
			Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
			Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
			r.play();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public boolean isInForeground()
	{
	    ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
	    List<RunningTaskInfo> services = activityManager
	    		.getRunningTasks(Integer.MAX_VALUE);

	    if (services.get(0).topActivity.getPackageName().toString()
	            .equalsIgnoreCase(getApplicationContext().getPackageName().toString()))
	        return true;
		
		return false;
	}
	

  @Override
  public void onError(Context context, String errorId) {
    Log.e(TAG, "onError - errorId: " + errorId);
  }




}
+66 −0
Changes for src/android/com/plugin/GCM/PushHandlerActivity.java: 66 added lines, 0 removed lines.
Original line number Diff line number Diff line
//
//  PushHandlerActivity.java
//
// Pushwoosh Push Notifications SDK
// www.pushwoosh.com
//
// MIT Licensed

package com.plugin.GCM;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class PushHandlerActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        handlePush();
    }

    private void handlePush()
    {
    	// If we are here, it is because we were launched via a notification. It is up to the author to decide what to do with it.
    	// You may simply ignore it since the notification already fired in the background. Either way, the background flag
    	// will let you know what the state was when the notification fired.
    	Bundle extras = this.getIntent().getExtras();
        if (extras != null)
        {
    		Bundle	originalExtras = extras.getBundle("pushBundle");
    		if (originalExtras != null)
    		{
    			try
    			{
     				JSONObject json;
    				json = new JSONObject().put("event", "message");

    				json.put("message", originalExtras.getString("message"));
    				json.put("msgcnt", originalExtras.getString("msgcnt"));
    				json.put("foreground", originalExtras.getBoolean("foreground"));

    				Log.v("PushHandlerActivity:handlePush", json.toString());

    				PushPlugin.sendJavascript( json );
    			}
    			catch( JSONException e)
    			{
    				Log.e("PushHandlerActivity:handlePush", "JSON exception");
    			}
    		}
	}
        finish();
  }

    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
    }
}