2014-05-06 34 views
2

我認爲這可能是重複的,但我找不到任何可以回答我的問題的東西。我知道服務在應用程序的同一線程中工作。我想從一個服務中運行一些任務,但使用不同的線程。 我有幾個要點,我必須連續跟蹤GPS和每次我到這一點之一,我必須做一些其他任務(相當快的)。爲此,我使用BroadcastReceiver。一切都很完美,但現在我想把所有這些放在一個不同的線程中。我怎樣才能做到這一點?我的意思是我嘗試過,但我不斷收到錯誤「不能創建處理程序內部的線程沒有調用Looper.prepare()」。我查找了一些修正,但沒有一個似乎適合或成爲正確的編程方式(很少有人看起來像修復,但以一種非常糟糕的方式)。 我會發布一些代碼,以便您可以將其與您的解決方案集成。預先感謝您的幫助。Android如何在不同的線程中運行服務

public class MyService extends Service { 

    private final IBinder mBinder = new MyBinder(); 

     ... 

    @Override 
    public void onCreate() { 
     ... 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     return mBinder; 
    } 

    public class MyBinder extends Binder { 
     MyService getService() { 
      return MyService.this; 
     } 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     .... 
     (my tasks) 
     .... 
     return(START_REDELIVER_INTENT); 
    } 

     ............ 

     (final method that calls stopSelf() after it's done) 

     ............ 

     @Override 
    public void onDestroy() { 
     Log.i("onDestroy", "Service stop"); 
     super.onDestroy(); 
    } 
} 

回答

2

可以使服務separate process。然後它將運行在它自己的process中。爲此,只需在Android Manifest中添加process attribute即可。

<service 
     android:name="<serviceName>" 
     android:process=":<processName>" /> 

不要忘記processname

+0

這應該是我正在尋找的。謝謝。現在我遇到了一個新問題。我無法使用活頁夾綁定服務。我認爲這是因爲現在在他自己的流程中運行的服務不能像以前那樣訪問。你知道我該怎麼做嗎? – user2294708

+0

我不認爲在單獨的進程上運行服務會使綁定器不能工作。 – SathMK

+0

它確實我想,因爲給定的相同的代碼和添加機器人:過程=「:」它導致errore當我執行被綁定到該服務的方法,包括: \t公共無效removeProximityAlert(查看視圖){\t \t myService.removeProximityAlert(Integer.valueOf(etNumber.getText()。的toString())); \t} – user2294708

2

簡單和最好的方法是使用IntentService和基類相當Service。

public class MyService extends IntentService { 

    public MyService(String name) { 
     super(""); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 

     /* 
     * Do Your task here, service will automatically stop as your task 
     * complete. And your task will run in worker thread rather main thread. 
     * Everything will handled by IntentService. 
     */ 
    } 

} 

你可以找到完整的IntenetService演示Here

+0

謝謝你的答案,但我認爲IntentService有它的侷限性,可能是我的應用程序的問題在這種情況下 – user2294708

0

的IntentService類提供了一個簡單的結構,用於在單個後臺線程中運行的操作之前添加:。這允許它處理長時間運行的操作,而不會影響用戶界面的響應。而且,IntentService不受大多數​​用戶界面生命週期事件,所以它繼續在運行的情況下,將關閉一個的AsyncTask

的IntentService有一些限制:

它不能直接與互動您的用戶界面。要將其結果放入UI中,您必須將它們發送到活動。 工作請求按順序運行。如果某個操作正在IntentService中運行,並且您發送了另一個請求,則請求會等待,直到第一個操作完成。 在IntentService上運行的操作不能被中斷。

有關詳細信息和示例,請參見文檔: https://developer.android.com/training/run-background-service/create-service.html

例SRC代碼:https://developer.android.com/shareables/training/ThreadSample.zip

+0

您的答案確實完整,但正如您所指出的,IntentService幾乎沒有什麼限制,在我的情況下可能會導致衝突。儘管如此,我還是要了解更多關於IntentService的知識 – user2294708

相關問題