Android 单击通知时执行操作

Android 单击通知时执行操作,android,Android,我有一个应用程序,它在服务中使用持久通知,并在后台运行。当此服务运行时,我需要能够在单击通知时调用方法/执行某些操作。然而,我不知道如何实现这一点我已经阅读了许多类似的问题/答案,但没有一个得到明确或适合我的目的的回答。因此,问题接近我想要达到的目标,但选择的答案很难理解 我的服务/通知是在BackgroundService类的onCreate()方法中启动的 Notification notification = new Notification(); startForeground(

我有一个应用程序,它在服务中使用持久通知,并在后台运行。当此服务运行时,我需要能够在单击通知时调用方法/执行某些操作。然而,我不知道如何实现这一点我已经阅读了许多类似的问题/答案,但没有一个得到明确或适合我的目的的回答。因此,问题接近我想要达到的目标,但选择的答案很难理解

我的服务/通知是在BackgroundService类的onCreate()方法中启动的

Notification notification = new Notification();
    startForeground(1, notification);
    registerReceiver(receiver, filter);
此服务将从我的主要活动的按钮单击启动:

final Intent service = new Intent(Main.this, BackgroundService.class);

bStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if((counter % 2) == 0){

                bStart.setText("STOP");
                startService(service);

            }else {
                bStart.setText("BEGIN");
                stopService(service);
            }

            counter++;

        }

任何建议都将不胜感激

为此,您必须使用
广播接收器
。看看下面的代码。将其放入您的
服务中

private MyBroadcastReceiver mBroadcastReceiver;
@Override
onCreate() {
    super.onCreate();
    mBroadcastReceiver = new MyBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
    // set the custom action
    intentFilter.addAction("do_something");

    registerReceiver(mBroadcastReceiver, intentFilter);
}



// While making notification
Intent i = new Intent("do_something");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, 0);
notification.contentIntent = pendingIntent;




public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch(action) {
                case "do_something":
                    doSomething();
                    break;
            }
        }
    }

public void doSomething() {
    //Whatever you wanna do on notification click
}

这样,当单击通知时,将调用
doSomething()
方法。

这不起作用。我将日志放在onReceive()方法中,而不是占位符方法(doSomething()),但在单击notification@Steve在这一点上,我会问自己,接收者是否正确注册?notification.contentIntent是否在代码中的正确位置正确设置?所有设置都在正确位置。通知在onCreate()方法中启动,接收方在其中注册为well@Steve您应该将行notification.contentIntent=pendingent;开工前(1,通知);你能把你的服务课发出去吗?我的答案最好能实现。