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

时间:2016-08-04 07:29:51

标签: android notifications

我收到了一封来自服务的通知。我想在通知点击时再次呼叫该服务。但是通知点击无法进入方法。

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());

我试过以下链接但无法解决我的问题。  How to execute a method by clicking a notification

2 个答案:

答案 0 :(得分:8)

您可以在Broadcast中指定Service,并通过通知中的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
    }
};

您只需使用以下内容在receiver(可能在Service)中注册此onStartCommand()

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

你的Service必须正在运行才能发挥作用。

答案 1 :(得分:0)

更好的选择是尝试How to execute a method by clicking a notification ..但是因为静态类

而要小心