2014-03-13 62 views
1

我需要从NLService线程调用延迟方法(runnable)。但是这个方法永远不会被调用。我将不胜感激任何帮助。Android - 从Worker线程(NotificationListenerService线程)运行延迟任务

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

是 'onNotificationPosted(...)' 叫什么名字?你的包名是否正确? –

+0

请更具体:哪个不叫?方法,if块等 – cbrulak

+0

是@PhilippJahoda,'onNotificationPosted(...)'被调用。 – Shaamil

回答

4

NotificationListenerService是在通知范围内发布其被激活的服务。它通过框架内部的Binder通知来完成此操作,因此您的onNotificationPosted()回调函数将从一个活页夹池线程调用,而不是您应用程序的常用主线程。实质上,您创建的Handler将自己与Looper关联,因为该线程由内部联编程序框架管理,而不是通常的主线程或您可能创建的其他线程,因此永远不会调用Looper

试试这个:创建一个HandlerThread,当你的回调被第一次击中(并保存)并启动它。将Runnable转换为您创建的Handler,并将其绑定到HandlerThread中的Looper

2

还有一个“更简单”的解决方案。 您可以在onCreate()内部创建新的Handler。将它保存为类变量,并在再次需要时调用它。

例子:

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 
    .... 
}