Tuesday 8 July 2014

Push notification Demo

1) GCMIntentService

import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

public static final String GCM_SENDER_ID = "378946919077";

public GCMIntentService() {
super(GCM_SENDER_ID);
}

@SuppressWarnings("deprecation")
@Override
protected void onMessage(Context context, Intent intent) {
try {
final Bundle bundle = intent.getExtras();

String message = bundle.getString("message");

Log.i(TAG, "message: " + message);

// MainActivity mainActivity = MainActivity.getMainActivity();
// if (mainActivity != null) {
// mainActivity.onPushMessage(message);
// clearPushMessage();
// } else
//Intent notificationIntent = new Intent(this, MyClass.class);
//PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);


Intent mIntent = new Intent(context, PopUpNotification.class);
mIntent.putExtra("pushmessage", message);
mIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

final PendingIntent contentIntent = PendingIntent.getActivity(
context, (int) System.currentTimeMillis(), mIntent, 0);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
setPushMessage(message);
final Notification notification = new Notification();
final Object systemService = context
.getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationManager notificationMgr = (NotificationManager) systemService;

notification.flags |= Notification.FLAG_AUTO_CANCEL;
// notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults = Notification.DEFAULT_LIGHTS
| Notification.DEFAULT_VIBRATE;

notification.vibrate = new long[] { 0, 100, 200, 300 };
notification.contentIntent = contentIntent;
notification.icon = R.drawable.icon;

notification.tickerText = context.getString(R.string.app_name);
String appName = context.getResources().getString(
R.string.app_name);
notification.setLatestEventInfo(this, appName, message,
contentIntent);
//notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
int ss = (int) System.currentTimeMillis();

notificationMgr.notify(ss, notification);
} else {

NotificationManager m_notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Builder m_builder = new Notification.Builder(this);
m_builder
.setContentTitle(context.getString(R.string.app_name))
.setContentText(message)
.setSmallIcon(R.drawable.icon)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setVibrate(new long[] { 0, 100, 200, 300 })
.setDefaults(
Notification.DEFAULT_LIGHTS
| Notification.DEFAULT_VIBRATE);
String appName = context.getResources().getString(
R.string.app_name);
Notification m_notification = new Notification.BigTextStyle(
m_builder).bigText(message).build();
m_notification.setLatestEventInfo(this, appName, message, contentIntent);
int ss = (int) System.currentTimeMillis();
m_notificationManager.notify(ss, m_notification);
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void setPushMessage(String message) {
final SharedPreferences mSharedPreferences = getSharedPreferences(
"PushNotification", 0);
final SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putString("message", message);
mEditor.commit();
}

public void clearPushMessage() {
final SharedPreferences mSharedPreferences = getSharedPreferences(
"PushNotification", 0);
final SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putString("message", null);
mEditor.commit();
}

private static final String TAG = "GCMIntentService";

@Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
MainActivity instance = MainActivity.getInstance();
if (instance != null)
instance.onDeiceToken(registrationId);
}

@Override
protected void onUnregistered(Context arg0, String arg1) {
Log.i(TAG, "unregistered = " + arg1);
}

@Override
protected void onError(Context arg0, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}

@Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}

}

2) MainActivity.java
==============
public class MainActivity extends DroidGap {

public static MainActivity mainActivity;
private String regId;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mainActivity = this;

super.loadUrl("file:///android_asset/www/html/index.html", 3000);
super.setIntegerProperty("loadUrlTimeoutValue", 80000);
super.setIntegerProperty("splashscreen", R.drawable.splash_screen);
appView.loadUrl("javascript:android.selection.longTouch();");

GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
regId = GCMRegistrar.getRegistrationId(this);

if (TextUtils.isEmpty(regId)) {
GCMRegistrar.register(this, GCMIntentService.GCM_SENDER_ID);
} else {
appView.setWebChromeClient(new MyChromeClient(this, regId));
}

Intent mIntent = getIntent();
if (mIntent != null) {
Bundle mBundle = mIntent.getExtras();
if (mBundle != null) {
if (mBundle.containsKey("bundle")) {
mBundle = mBundle.getBundle("bundle");
String cal_envet_id = mBundle
.getString(AlarmReceiver.NOTIFICATION_ID);
String title = mBundle.getString(AlarmReceiver.TITLE);

String nServerEventID = mBundle
.getString(AlarmReceiver.SERVEREVENTID);
onEventArise(cal_envet_id, title, nServerEventID);
}
}
}
}

public class MyChromeClient extends CordovaChromeClient {

private String registerToken = "";

public MyChromeClient(CordovaInterface cordova, String regId) {
super(cordova);
registerToken = regId;
}

@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress == 100) {
onDeiceToken(registerToken);
Bundle data = getIntent().getExtras();
if (data.containsKey("pushmessage")) {
onPushMessage(data.getString("pushmessage"));
}
}
}
}

public static MainActivity getInstance() {
return mainActivity;
}

@Override
protected void onResume() {
mainActivity = this;
super.onResume();
}

@Override
public void onDestroy() {
mainActivity = null;
super.onDestroy();
}

public void onDeiceToken(final String deviceToken) {
runOnUiThread(new Runnable() {
@Override
public void run() {
appView.loadUrl("javascript:onDeviceToken('" + deviceToken
+ "')");
}
});
}

public void onEventArise(String id, String message, String nServerEventID) {
appView.loadUrl("javascript:onCalanderEvent('" + id + "','" + message
+ "'" + nServerEventID + "')");

}

public void onPushMessage(final String mMessage) {
appView.loadUrl("javascript:onPushMessage('" + mMessage + "')");
}

}
3) in mani fest add
<!-- GCM code Begin -->
    <permission
        android:name="com.rightway.amour.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.rightway.amour.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- GCM code End -->



    <!-- GCM Code Begin -->
        <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" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.rightway.amour" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" />
        <!-- GCM code End -->