Android - 从工作线程(NotificationListenerService 线程)运行延迟任务

标签 android multithreading

我需要从 NLService 线程调用延迟方法(可运行)。但是,该方法永远不会被调用。如果有任何帮助,我将不胜感激。

public class NLService extends NotificationListenerService {

@Override
public void onNotificationPosted(StatusBarNotification sbn) {

    if(sbn.getPackageName().contains("mv.purple.aa")){

       AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
       amanager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);

       //This is the code I am having issues with.
       //I used this code to call the method. However it is not working.
       private Handler handler = new Handler();
       handler.postDelayed(runnable, 100);

    }


}

//I want to call the following method
private Runnable runnable = new Runnable() {
  @Override
  public void run() {
    foobar();
 }
};

}

最佳答案

NotificationListenerService 是一种在框架内发布通知时激活的服务。它通过框架内部的 Binder 通知执行此操作,因此您的 onNotificationPosted() 回调是从 Binder 池线程之一调用的,而不是通常的主线程应用程序。本质上,您正在创建的 Handler 将自身与 Looper 相关联,它永远不会被调用,因为线程由内部 Binder 框架而不是通常的主线程或其他线程管理您可以创建线程。

试试这个:在您的回调第一次被命中时创建一个 HandlerThread(并保存它)并启动它。将您的 Runnable 交给您创建的 Handler,它绑定(bind)到 HandlerThread 中的 Looper

关于Android - 从工作线程(NotificationListenerService 线程)运行延迟任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22387318/

相关文章:

java - 使用线程删除位置更新

java - Java UDP Server 增加内存

android - 编译应用程序时,R8 程序类型已存在错误

Android AlertDialog BUTTON_POSITIVE/BUTTON_NEGATIVE顺序

java - volatile 写入 = volatile 读取

java - 无法创建新的 native 线程错误 - 但使用的线程很少

php - 如何将android中的后置参数声明为php

java - 在 Android 中检查文件是否存在不起作用

android - 创建新的 Intent 错误

c - 如何在多线程中使用 printf()