2011-03-22 60 views
8

繼谷歌使用服務的例子後,我創建了一些像這樣的線程。我無法使用IntentService,因爲我正在做一些涉及等待回調的事情。如何終止HandlerThreads?

不過,我不知道如何終止線程以這種方式啓動。據我所知,當run()方法返回時,線程會自動終止。但是,這種線程沒有運行方法。我的線程正在泄漏 - 他們在stopSelf()後仍然活着。

@Override 
public void onCreate() { 

    HandlerThread thread = new HandlerThread("ServiceStartArguments", 
      android.os.Process.THREAD_PRIORITY_BACKGROUND); 
    thread.start(); 
    HandlerThread thread2 = new HandlerThread("CallbackHandling", 
      android.os.Process.THREAD_PRIORITY_BACKGROUND); 
    thread2.start(); 

    mServiceLooper = thread.getLooper(); 
    mCallbackLooper = thread2.getLooper(); 
    mServiceHandler = new MyHandler(mServiceLooper); 
    mCallbackHandler = new Handler(mCallbackLooper); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); 

    // For each start request, send a message to start a job and deliver the 
    // start ID so we know which request we're stopping when we finish the job 
    Message msg = mServiceHandler.obtainMessage(); 
    msg.arg1 = startId; 
    mServiceHandler.sendMessage(msg); 
    mMainThreadHandler=new Handler(); 
    // If we get killed, after returning from here, restart 
    return START_STICKY; 
} 

private final class MyHandler extends Handler { 
    public MyHandler(Looper looper) { 
     super(looper); 
    } 
    @Override 
    public void handleMessage(Message msg) { 
     cycle(); 


     // Stop the service using the startId, so that we don't stop 
     // the service in the middle of handling another job 
     stopSelf(msg.arg1); 
    } 
} 

protected void cycle() { 
    ... 
    mCallbackHandler.post(new Runnable(){ 
     public void run(){ 
      goAskForSomeCallbacks(); 
     } 
    }); 

    try { 
     Thread.sleep(GIVE_UP_TIME); 
    } catch (InterruptedException e){ 
     //The callback will interrupt this thread to stop it from waiting 
     Log.d(TAG,"Got early callback, stop waiting."); 
    } 
    Thread.interrupted(); //clear the interrupt 
    doStuff(); 

} 
+0

我看不出爲什麼使用回調會阻止您使用IntentService。我希望「等待回調」並不意味着在這裏等待。如果是的話,那麼我會建議重新設計。如果不是,那麼沒有理由將單獨的HandlerThread保持爲預期回調的基礎。即使對回調提供的數據進行了大量的後處理,也許明智的辦法就是排隊等等。所以,理解你心目中的架構會很好。 – 2013-01-15 12:04:14

回答

16

嘗試在相應的Loopers上調用quit方法。

+0

@ TenFour04你會發布最終解決方案嗎? – eros 2011-09-28 00:31:31

-1

強制關閉應用程序做它,但否則他們只是不停自己。

1

您可以在您的處理程序線程上調用quit方法。

例如

thread.quit(); 
thread2.quit();