我需要从 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/