我正在尝试从.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>

最佳答案

您的命名约定令人困惑。 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);

08-05 08:00
查看更多