首页 > 解决方案 > 我怎么知道在通知中点击了哪个按钮?

问题描述

每个通知中都有三个按钮(主通知按钮、计时器按钮和禁用按钮)。

有没有办法为所有三个按钮使用一个前台服务?如果是这样,我如何确定在服务中单击了哪个按钮?或者我必须为每个按钮创建三个前台服务?

我的代码

PendingIntent pendingIntentMain = PendingIntent.getService(context, 0, new Intent(context, ForegroundService.class).putExtra("main", "a"), PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntentTimer = PendingIntent.getService(context, 0, new Intent(context, ForegroundService.class).putExtra("timer", "b"), PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntentDisable = PendingIntent.getService(context, 0, new Intent(context, ForegroundService.class).putExtra("disable", "c"), PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, String.valueOf(NOTIFICATION_ID))
    .addAction(R.mipmap.ic_launcher, context.getString(R.string.timer), pendingIntentTimer)
    .addAction(R.mipmap.ic_launcher, context.getString(R.string.disable), pendingIntentDisable)
    .setContentIntent(pendingIntentMain)
    .setOngoing(true)
    .setAutoCancel(false)
    .setShowWhen(false)
    .setSmallIcon(R.mipmap.ic_launcher)
    .setContentTitle(context.getString(R.string.app_name))
    .setContentText(context.getString(R.string.tap_to_enable_service))
    .setPriority(NotificationCompat.PRIORITY_DEFAULT);

前台服务

public class ForegroundService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.w("ABC", "" + intent.getStringExtra("main"));
        Log.w("ABC", "" + intent.getStringExtra("timer"));
        Log.w("ABC", "" + intent.getStringExtra("disable"));
        Log.w("ABC", "" + intent.getExtras());
        return super.onStartCommand(intent, flags, startId);
    }

}

里面什么都Log.w没有onStartCommand

标签: androidandroid-notifications

解决方案


无需创建不同的前台服务,您可以使用 Intent Action 而不是将 Intent 与数据一起传递。喜欢,

Intent intent = new Intent(this , ClipTextObserverService.class);
intent.setAction("specify_name_of_the_action")

PendingIntent.getService(
            this,
            1464,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        );

相应地更改标志。在 addAction() 方法中传递这个 pendingIntent。然后检查 Service.Like 的 onStartCommand() 方法中的操作,

@Override
public int onStartCommand(Intent Intent , Int flags , Int startId) {

switch (intent.getAction()) {
 case "your_action_name":
    // TODO == Perform your action here.
    break;
}

return super.onStartCommand(intent, flags , startId);
}

推荐阅读