android - 对通知点击执行操作

标签 android

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

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

Notification notification = new Notification();
    startForeground(1, notification);
    registerReceiver(receiver, filter);

这个服务是从我的主要 Activity 的按钮点击启动的:

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++;

        }

感谢任何建议

最佳答案

您必须为此使用 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
}

这样,当您的 Notification 被点击时,doSomething() 方法将被调用。

关于android - 对通知点击执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32257067/

相关文章:

Android 处理吉他调音器的音频

android - 根据背景图片相对布局换行宽高

Android:搜索 Intent 不起作用

Android:如何安全地将数据发送到网站

android - Kakao Talk 是如何运作的?

Java\jdk1.7.0_06\bin\java.exe'' 以非零退出值 1 android studio 完成

android - Gradle 自定义存储库和依赖解析

android - ParseException 仅适用于 Galaxy Nexus

android - ListView,在 Android 1.6 上不检查可检查项目

android - 发布前缩小图片尺寸