我需要从NLService线程调用延迟方法(runnable)。但是这个方法永远不会被调用。我将不胜感激任何帮助。
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();
}
};
}
答案 0 :(得分:4)
NotificationListenerService
是在框架内发布通知时激活的服务。它通过框架内部的Binder
通知执行此操作,因此从其中一个绑定池线程调用您的onNotificationPosted()
回调,而不是应用程序的常用主线程。实质上,您正在创建的Handler
将自身与永远不会被调用的Looper
相关联,因为该线程由内部绑定器框架管理,而不是您可能创建的常用主线程或其他线程。 / p>
试试这个:在第一次点击你的回调时创建一个HandlerThread(并将其保存)然后启动它。将您的Runnable
翻到您创建的Handler
,该Looper
与HandlerThread
中的{{1}}绑定。
答案 1 :(得分:2)
还有一个更简单的"解。
您可以在Handler
内创建新的onCreate()
。将其保存为类变量,并在需要时再调用它。
示例:
public class NotificationListener extends NotificationListenerService
private mHandler handler;
public void onCreate() {
super.onCreate();
handler = new Handler();
}
@Override
public void onNotificationPosted(StatusBarNotification statusBarNotification) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something special here :)
}
}, 5*1000);
}
....
// Override other importand methods
....
}