Android显示来自BroadcastReceiver的通知

Max*_*ord 6 notifications android broadcastreceiver wifi

我有一个扩展BroadcastReceiver的类,只要有新的Wifi扫描结果可用就会被调用(接收器在清单中注册,并将Scan_Results广播作为intent-filter).

从这个课程,我希望能够向用户显示通知.目前,我将在广播意图类的onReceive方法中作为参数接收的上下文传递给另一个类的"show notification"方法.

当它到达该行:

myNotificationManager.notify(notificationId, notification);
Run Code Online (Sandbox Code Playgroud)

它失败,出现以下异常:

java.lang.IllegalArgumentException: contentView required: pkg=com.mumfordmedia.trackify id=2131034122 notification=Notification(vibrate=null,sound=null,defaults=0x0,flags=0x0)
Run Code Online (Sandbox Code Playgroud)

知道为什么会这样吗?我能想到的只是因为我从onReceive参数得到的上下文不是......因为没有更好的短语,"适合工作"......

有任何想法吗?谢谢,马克斯.

SME*_*SME 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);
Run Code Online (Sandbox Code Playgroud)

  • +1:使用 setLatestEventInfo() 会导致错误消失。显示如此简单的通知需要多少行代码,这有点烦人…… (2认同)

Kur*_*aum 0

据我所知,当您创建要传递给通知管理器的通知时,您并没有为其提供要显示的内容视图。检查实际创建通知的行,看看您是否确实为通知提供了要显示的视图。