我正在开发一个显示推送通知消息的应用程序。当我尝试使用Toast消息显示消息时,它在任何情况下都能正常工作。但我想使用StatusBarNotifications
来进行这些推送通知。当应用程序运行时,它工作正常。如果我在关闭后重新启动设备,则状态栏通知不会显示。应用程序强制关闭时,情况也是如此。
我该如何解决这个问题?
以下是代码:
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,tickerMessage,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);
}
以前我用过上下文,但它不适用于其他小部件,其他小部件。所以我打算使用context.getApplicationContext()
。
答案 0 :(得分:1)
TL; DR:使用getBaseContext()
代替getApplicationContext()
(半)详细答案:
我找到了问题的答案,因为我今天遇到了同样的问题。
问题是,当您的应用程序强制关闭/重新启动后并且未在任务管理器中时,getApplicationContext()
未正确初始化。在尝试检索通知管理器以生成通知时,使用它将为您提供错误的引用。
传递给handleMessage方法的Context
很可能也由getApplicationContext()
给出。
可以使用getBaseContext()
我建议通过方法尽可能追溯到收到推送通知意图的地方,并更改传递给handleMessage方法的任何Context
,并将其替换为Context context = getBaseContext();
然后您可以在方法中使用context参数。