I am developing an application that will show the push notification messages. When I am trying to display the messages using Toast message, then it is working properly at any situations. But I want to use StatusBarNotifications
for these push notifications. It is working fine, when the app is running. If I restarted the device after shutting down, the statusbar notification is not showing. This is the same case when the app is force closed.
How can I solve this issue?
The following are the code :
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE"))
{
handleMessage(context, intent);
}
}
private void handleMessage(Context context, Intent intent)
{
String message= intent.getStringExtra("msg");
Toast.makeText(context.getApplicationContext(),"\n message : "+message,1).show();
NotificationManager objNotfManager=(NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.logo;
CharSequence tickerMessage = message;
long when= System.currentTimeMillis();
Notification objNotf = new Notification(icon,tickerMes开发者_如何学运维sage,when);
CharSequence title = "New message from "+message;
CharSequence mesage = "You have "+number+" unread messages";
Intent NotifIntent = new Intent( context.getApplicationContext(),TabContainer.class);
NotifIntent.putExtra("message",message);
PendingIntent contentIntent = PendingIntent.getActivity( context.getApplicationContext(), 0, NotifIntent, 0);
objNotf.setLatestEventInfo( context.getApplicationContext(), title, mesage, contentIntent);
objNotfManager.notify(1,objNotf);
}
Previously I used with context, but it was not working for other widgets, other the Toast. so I planned to use context.getApplicationContext()
.
TL;DR: use getBaseContext()
instead of getApplicationContext()
(Semi) Detailed Answer:
I figured out an answer to your problem as i had the same problem today.
the problem is that when your app is force-closed/after restart and isn't sitting in the task manager, getApplicationContext()
isn't properly initialized. Using it will give you bad references when trying to retrieve the notification manager to generate a notification.
There is a good chance that the Context
that is passed to your handleMessage method is given by getApplicationContext()
too.
The context that is available to you when your application is not alive can be retrieved with getBaseContext()
What i would suggest is to trace back as far as possible through the methods to the place where the push notification intent gets received, and change whatever Context
that gets passed down to the handleMessage method, and replace it with Context context = getBaseContext();
and then you can use the context parameter within the method.
精彩评论