我试图在不必打开应用的情况下解除来自.addAction()
的通知。问题是当按下按钮没有任何反应时,onReceive()
方法不会触发。
以下是MainActivity上的代码:
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>
答案 0 :(得分:2)
您的命名惯例令人困惑。 Android已经有一个名为Notification
的类,所以你可能不应该打电话给你的接收器Notification
: - (
如果MainActivity
扩展Activity
,那么您需要为其创建一个清单条目,如下所示:
<activity android:name=".MainActivity"/>
对于BroadcastReceiver
,您需要一个这样的清单条目:
<receiver android:name=".Notification"
android:exported="true"/>
由于您使用明确的Intent
来启动BroadcastReceiver
,因此您无需为其提供<intent-filter>
。由于BroadcastReceiver
将由NotificationManager
启动,因此您需要确保它是exported
。
然后,您需要创建PendingIntent
,以便它实际启动您的BroadcastReceiver
,因此请更改此内容:
Intent notificationIntent = new Intent(mContext, MainActivity.class);
到此:
Intent notificationIntent = new Intent(mContext, Notification.class);