Display Notification when receiving C2DM message causes crash
I want to display a message contained in my C2DM message's payload, but I can't seem to get this to work without crashing.
package com.themenetwork.app;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class C2DMMessageReceiver extends BroadcastReceiver {
public NotificationManager myNotificationManager;
public static final int NOTIFICATION_ID = 1;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w("c2dm", "Message Receiver called");
if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
Log.w("c2dm", "Received message");
final String payload = intent.getStringExtra("payload");
Log.d("c2dm", "dmControl: payload = " + payload);
Notification notification = new Notification(R.drawable.icon, "Hello", 0);
Intent notificationIntent = new Intent(context, RootActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, "Title", "Text", contentIntent);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
myNotificationManager.notify(NOTIFICATION_ID, notification);
}
}
}
The exception is...
Thread [<1> main] (Suspended (exception RuntimeException))
ActivityThread.handleReceiver(ActivityThread$ReceiverData) line: 1881 ActivityThread.access$2400(ActivityThread, ActivityThread$ReceiverData) line: 124 ActivityThread$H.handleMessage(Message) line: 1018 ActivityThread$H(Handler).dispatchMessage(Message) line: 99 Looper.loop() line: 130 ActivityThread.main(String[]) line: 3806 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Metho开发者_JAVA技巧d.invoke(Object, Object...) line: 507 ZygoteInit$MethodAndArgsCaller.run() line: 839 ZygoteInit.main(String[]) line: 597 NativeStart.main(String[]) line: not available [native method]
I'm really new to Java, let alone Android, so I'm completely stumped as to why this isn't working.
Isn't myNotificationManager
null when you try to invoke notify
on it? You need to initialize it to point to a valid instance of a NotificationManager
, maybe like this:
myNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
精彩评论