我有一个扩展BroadcastReceiver的类,只要有新的Wifi扫描结果可用就会被调用(接收器在清单中注册,并将Scan_Results广播作为intent-filter)。
从这个课程中,我希望能够向用户显示通知。目前,我将在广播意图类的onReceive方法中作为参数接收的上下文传递给另一个类的“show notification”方法。
当它到达该行时:
myNotificationManager.notify(notificationId, notification);
失败,出现以下异常:
java.lang.IllegalArgumentException: contentView required: pkg=com.mumfordmedia.trackify id=2131034122 notification=Notification(vibrate=null,sound=null,defaults=0x0,flags=0x0)
知道为什么会这样吗?我能想到的只是因为我从onReceive参数获得的上下文不是......因为没有更好的短语,“适合工作”......
有什么想法吗? 谢谢, 最大
答案 0 :(得分:14)
ContentView是单击通知时所需的视图。下面的代码工作正常,setLatestEventInfo()
是必需的方法。
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
"Hello from service", System.currentTimeMillis());
Intent intent = new Intent(this, MainActivity.class);
notification.setLatestEventInfo(this, "contentTitle", "contentText",
PendingIntent.getActivity(this, 1, intent, 0));
manager.notify(111, notification);
答案 1 :(得分:2)
不确定为什么它之前没有工作,但这里是我使用它的代码:
在任何方法之外声明以下内容:
int YOURAPP_NOTIFICATION_ID = 1234567890;
NotificationManager mNotificationManager;
然后在onReceive方法中调用以下内容:
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
showNotification(context, R.drawable.icon, "short", false);
然后声明以下方法:
private void showNotification(Context context, int statusBarIconID, String string, boolean showIconOnly) {
// This is who should be launched if the user selects our notification.
Intent contentIntent = new Intent();
// choose the ticker text
String tickerText = "ticket text";
Notification n = new Notification(R.drawable.icon, "ticker text", System.currentTimeMillis());
PendingIntent appIntent = PendingIntent.getActivity(context, 0, contentIntent, 0);
n.setLatestEventInfo(context, "1", "2", appIntent);
mNotificationManager.notify(YOURAPP_NOTIFICATION_ID, n);
}
答案 2 :(得分:2)
您必须调用Notification.setLatestEventInfo()。
答案 3 :(得分:1)
将此代码与您的通知一起使用
Intent intent = new Intent(this, MusicDroid.class);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "This is the title",
"This is the text", activity);
notification.number += 1;
nm.notify(NOTIFY_ID, notification);
答案 4 :(得分:0)
据我所知,当您创建通知以传递给通知管理器时,您不会给它显示内容视图。查看实际创建通知的行,以查看您是否实际向通知提供了要显示的视图。
答案 5 :(得分:0)
对于使用NotificationCompat的用户,以下代码将起作用:
NotificationCompat.Builder n = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon).setContentText("Notify Title").setContentText("Sample Text");
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent i = new Intent(this,MainActivity.class);
PendingIntent ac = PendingIntent.getActivity(this, 0, i, 0);
n.setContentIntent(ac);
nm.notify(12222, n.build());