对通知执行操作点击

时间:2015-08-27 18:38:03

标签: android

我有一个应用程序,它在服务中使用持久性通知并在后台运行。当此服务正在运行时,我需要能够在单击通知时调用方法/执行某些操作。但是,我不确定如何实现这一点。 我已阅读了许多类似的问题/答案,但没有一个人能够清楚地或适当地回答我的目的。 This所以问题接近我想要实现的目标,但所选答案是很难理解。

我的服务/通知是在我的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++;

        }

任何建议表示赞赏

1 个答案:

答案 0 :(得分:1)

你必须使用BroadcastReceiver。看看下面的代码。把它放在Service

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()时,系统会调用Notification方法。