在通知点击后调用服务中的方法

3

我有一个通知在服务中调用。我希望在点击通知时再次调用该服务。但是无法在方法内部获取通知点击事件。

Intent intent = new Intent(this, MyService.class).setAction(ACTION_1);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.food)
                    .setContentTitle("notification")
                    .setContentText("near by you!");
   NotificationManager mNotificationManager =(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);

我想调用的方法是

if (ACTION_1.equals(resultPendingIntent)) {
        getRecommendation();
    } 
        mBuilder.setContentIntent(resultPendingIntent);
    mNotificationManager.notify(id, mBuilder.build());

我尝试了以下链接,但无法解决我的问题。 如何点击通知执行一个方法
2个回答

12

您可以在Service中指定一个Broadcast,并通过PendingIntent在通知中启动它。

Intent stopIntent = new Intent("my.awersome.string.name");
PendingIntent stopPi = PendingIntent.getBroadcast(this, 4, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT);

然后,在您的通知构建器中:

NotificationCompat.Builder builder;
builder = new NotificationCompat.Builder(context)
    ...     
    .setContentIntent(stopPi);

在您的Service中,您可以设置一个BroadcastReceiver,如下所示:

private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Code to run
    }
};

您只需在Service中注册此receiver(可能在onStartCommand()中进行):

registerReceiver(myReceiver, new IntentFilter("my.awersome.string.name"));

你的Service必须在运行才能使此项工作。


1
你真是个救命恩人。这正是我一直在寻找的。运行得非常好。谢谢!! - John Spax
在服务中设置广播的位置 - user10445557
@VipulChauhan 你可以在启动通知时立即设置它,但请确保在使用完毕后(以及在onDestroy()中)立即注销它。 - Shaishav
谢谢您的快速回复,但我已经完成了它,现在我卡在如何为通知设置自定义布局上。 - user10445557
@VipulChauhan 这是完全不同的问题。你可以尝试在SO上找到解决方案,或者在这里创建一个新问题。 - Shaishav

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接