代替 pendingIntent,在 Notification.addAction() 中执行函数。可能吗?

Instead of pendingIntent, execute function in Notification.addAction() . Is it possible?

我希望在我按下通知按钮时执行一个方法。为此,我在通知中添加了带有 PendingIntent 的操作:

Intent intent = new Intent(context, AlertActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

Notification notification = new Notification.Builder(MainActivity.this)
                    .setContentTitle("New Notification")
                    .setContentText("Click Here")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .addAction(R.mipmap.ic_launcher, "Test2", pendingIntent)
                    .build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, notification);

可以,但是我不想在用户调用操作时启动 Activity。我只是需要做一些工作。

为此,我实现了一个 Service,它应该由 PendingIntent 作为目标:

public class MyServices extends IntentService {
    public MyServices() {
        super("MyServices");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        clearNotification();
    }

    public void clearNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel(0);
        Intent intent = new Intent(MyServices.this, MainActivity.class); 
//Starting new activity just to check
        startActivity(intent);
    }
}

我这样创建 PendingIntent

final Intent intent = new Intent(context, MyServices.class);
final PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

然而,当我在我的通知上调用操作时,没有任何反应。我做错了什么?

通知不是您申请的一部分。它由 OS 管理。碰巧有一些 API 可以用于 show/cancel/etc 通知。

待定意图允许外部代码(例如通知)启动您的 app/activity/service/broadcastreceiver。如果没有待定意图,则无法完成此操作。

What my task is to execute some piece of code when a specific action button is clicked, and clear notification; without starting any activity

您不必开始 activity。您可以在没有 UI 的广播接收器中执行此操作。或者,按照 CommonsWare 的建议,使用 IntentService,具体取决于您在 "piece of code" 中所做的事情。 IntentServices 在单独的线程中处理工作。