问题
I'm developing an Android & iOS App with cordova. Current Version there is 2.2.0. I've got the following Java code to show the Push Notification:
private void putNotification(String title, String message){
try{
Log.w("Push", "putNotification");
MainActivity context = MainActivity.getAppContext();
Log.w("Push", "context is set");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Log.w("Push", "notificationManager is set");
Notification note = new Notification(R.drawable.icon, title, System.currentTimeMillis());
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
note.setLatestEventInfo(context, title, message, pendingIntent);
note.defaults |= Notification.DEFAULT_SOUND;
note.defaults |= Notification.DEFAULT_VIBRATE;
note.defaults |= Notification.DEFAULT_LIGHTS;
note.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, note);
} catch(Exception e){
Log.w("Push failed", e);
}
}
When the app is running in the background the code works perfectly fine. But If the app is fully closed, I'm getting the following LogCat Errors, and no push is shown:
09-23 16:30:24.725: W/Push(3276): putNotification
09-23 16:30:24.725: W/Push(3276): context is set
09-23 16:30:24.725: W/Push failed(3276): java.lang.NullPointerException
09-23 16:30:24.725: W/Push failed(3276): at ch.seika.lakers.GCMIntentService.putNotification(GCMIntentService.java:105)
09-23 16:30:24.725: W/Push failed(3276): at ch.seika.lakers.GCMIntentService.onMessage(GCMIntentService.java:46)
09-23 16:30:24.725: W/Push failed(3276): at com.google.android.gcm.GCMBaseIntentService.onHandleIntent(GCMBaseIntentService.java:223)
09-23 16:30:24.725: W/Push failed(3276): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
09-23 16:30:24.725: W/Push failed(3276): at android.os.Handler.dispatchMessage(Handler.java:99)
09-23 16:30:24.725: W/Push failed(3276): at android.os.Looper.loop(Looper.java:137)
09-23 16:30:24.725: W/Push failed(3276): at android.os.HandlerThread.run(HandlerThread.java:61)
Line 105 is the following:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
I really can't say where the Null Pointer Exception is coming from, so any hint will be highly appreciated.
回答1:
in your code java.lang.NullPointerException exception occurs due to null context..
so,use context which is passed in onMessage method
protected void onMessage(final Context context, Intent intent)
use this context in your GCMIntentService class
来源:https://stackoverflow.com/questions/18962138/android-app-crashes-when-push-is-received-and-app-is-closed