2011-10-21 29 views
0

看到很多關於這個問題,但即時無法解決這個問題。我怎麼能阻止我的RECEIVE_BOOT_COMPLETED服務

我有這樣的代碼

public class myBroadcastReceiver extends BroadcastReceiver { 
private final String TAG = "myBroadcastReceiver"; 
    @Override 
    public void onReceive(Context context, Intent intent) { 
    if(intent.getAction().equals(Consts.ANDROID_INTENT_ACTION_BOOT_COMPLEATE)){ 
    Intent newinIntent = new Intent(context, ServiceBootCompleated.class); 
    context.startService(newinIntent); 
    } 
    } 
} 

它開始Service,我可以用這條線

android.os.Debug.waitForDebugger(); 

我看到return START_NOT_STICKY;執行調試,但仍 服務是作爲一個可見的「運行「服務 設置>程序>運行服務

onDestroy()永遠不會被調用,除非我手動停止它。
我需要做些什麼來阻止它,
從「設置>程序>運行服務」窗口中將其刪除?

回答

3

一旦你完成你想要在後臺調用stopSelf()

要確保你的服務做任何實際工作中的onCreate或onStartCommand作爲後臺線程中完成的,而不是做的工作。

有關服務生命週期的更多詳細信息,請參閱http://developer.android.com/reference/android/app/Service.html#ServiceLifecycle

例子:

public int onStartCommand(final Intent intent, final int flags, final int startId) 
{  
    Thread thread = new Thread(new Runnable() 
    { 
     @Override 
     public void run() 
     { 
        //do work 
       stopSelf(); 
     } 
    },"MyWorkerThread"); 
    thread.start(); 
    return Service.START_NOT_STICKY; 
} 
+0

我叫stopSelf()和工作在onStartCommand運行。代碼只是檢查MySql完整性的幾行。我將把它移動到一個線程。謝謝 – Erik

+0

我應該把stopSelf();在thread.run()之後的onStartCommand中;?或者在run()中像這樣ctx.stopSelf(); – Erik

+1

在onStartCommand(來自主線程)中調用stopSelf可能不一致,因爲服務在onStartCommand返回之前不被視爲已啓動。我通常在完成工作時從另一個線程調用它。 – cistearns

0

對任務的完成,必須停止這種類型的綁定服務做context.stopService()。

問候,
SSuman185

相關問題