Android 当按下.addAction()时,BroadcastReceiver未接收
我正在尝试在不打开应用程序的情况下取消来自Android 当按下.addAction()时,BroadcastReceiver未接收,android,android-intent,broadcastreceiver,android-notifications,android-pendingintent,Android,Android Intent,Broadcastreceiver,Android Notifications,Android Pendingintent,我正在尝试在不打开应用程序的情况下取消来自.addAction()的通知。问题是当按下按钮时,什么都没有发生,onReceive()方法不会触发 以下是主活动的代码: Intent notificationIntent = new Intent(mContext, MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TO
.addAction()
的通知。问题是当按下按钮时,什么都没有发生,onReceive()
方法不会触发
以下是主活动的代码:
Intent notificationIntent = new Intent(mContext, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("id", SOMENUMBER);
PendingIntent pIntent = PendingIntent.getBroadcast(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext);
notification.setContentTitle("");
notification.setContentText(t);
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setOngoing(true);
notification.addAction(R.mipmap.ic_launcher, "Dismiss", pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(SOMENUMBER, notification.build());
在另一节课上,我有一个接受器:
public class Notification extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(intent.getIntExtra("id", 0));
}
}
以及AndroidManifest.xml文件上的接收器:
<receiver android:name=".MainActivity">
<intent-filter>
<action android:name="io.github.seik.Notification" />
</intent-filter>
</receiver>
您的命名约定令人困惑。Android已经有了一个名为
Notification
的类,所以您可能不应该调用接收方Notification
:-(
如果MainActivity
扩展了Activity
,则需要为其设置一个清单条目,如下所示:
<activity android:name=".MainActivity"/>
<receiver android:name=".Notification"
android:exported="true"/>
由于您正在使用明确的意图
启动广播接收器
,因此不需要为其提供
。由于广播接收器
将由通知管理器
启动,因此您需要确保它已导出
然后,您需要创建pendingent
,以便它实际启动您的BroadcastReceiver
,因此更改此项:
Intent notificationIntent = new Intent(mContext, MainActivity.class);
为此:
Intent notificationIntent = new Intent(mContext, Notification.class);
MainActivity
是否扩展Activity
或BroadcastReceiver
?您的命名约定令人困惑:-(@davidwaser否,只有通知类扩展BroadcastReceiver。