2011-08-20 72 views
1

我一直試圖弄清楚這一段時間了,並不知道爲什麼會發生這種情況。這看起來很簡單,但我無法解決這個問題。Android啓動服務onStart和另一個問題

這是我想什麼發生

當我啓動應用程序,
1.如果後臺服務(長期運行的單獨服務)未運行,在開始活動之前啓動它。
2.啓動 「主頁」 活動

更新8/20
這裏是正在發生的事情:

1.我啓動應用程序和服務沒有運行
2.我啓動了意圖(通過context.startService)
    - context.start服務被稱爲
3.活動運行完成
4. onStartCommand運行

我怎樣才能獲得onStartCommand活動開始運行之前運行?


對此的任何建議將減輕很多挫折感。我在問這個問題之前搜索了論壇,但找不到與我的問題相符的任何內容
非常感謝!


更新
感謝您的快速反應。
我應該提到我已經從應用程序的擴展(在onCreate方法中啓動服務)中運行此應用程序。
在我當前的實現中(下面),這是按順序執行應用程序時發生的情況。我認爲這會導致服務在活動之前運行,但活動運行並且服務運行。這是我混亂的主要觀點。
1.應用程序的onCreate被稱爲
2. startService方法被運行
3.啓動活動運行
4.服務的onCreate被稱爲
- 服務在onStart沒有被調用(我會盡力這一建議亞歷山大)

public class MyApp extends Application { 

@Override 
public final void onCreate() 
{ 

     if(!MyService.isRunning()) // this is a static method with thread lock 
     { 
      Intent i = new Intent(context, MyService.class); 
      i.setAction(MyConstants.INTENT_START_SERVICE); 
      context.startService(i); 
     } 
    } 
} 

回答

0

感謝Alexander O的評論,指出我正確的方向是讓onStart命令運行。儘管如此,我仍然無法讓onStartCommand在運行之前運行。有什麼建議麼?

我的問題是我的服務中有onStartCommand和onStart函數。
顯然,我不明白onStartCommand的功能,並認爲它只是應該定義服務類型(STICKY,NOT_STICKY)。
一旦我刪除onStart並將onStart代碼移動到onStartCommand,應用程序開始工作。
對於那些想知道的,這裏基本上是我所擁有的。

public class MyService extends Service 
{ 
... 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) 
    { 
      // this was being executed but didn't really do anything 
      return Service.START_STICKY; 
    } 
    ... 
    @Override 
    public void onStart(Intent intent, int startId) 
    { 
     // logic that was never executed 
     // problem fixed when I removed onStart and moved the code to onStartCommand 
    } 
} 
+0

看起來好像沒有辦法強制onStartCommand在Activity之前順序運行。 如果有人找到了解決辦法,請告訴我。 – Summit

2

您可以創建一個擴展Application類的新類的感謝 - 的onStartCommand不是作爲我不是針對老年平臺。此類將在主要活動被調用之前運行,並且僅在應用程序首次啓動時運行。在您打開主頁活動之前,您可以在此啓動服務。

+2

+1。除非您也針對較舊的平臺,否則使用onStartCommand並不推薦onStart是一個好主意。 – EvilDuck

+0

現在正在調用onStartCommand,但我無法在應用程序運行之前使onStartCommand運行。有沒有辦法讓這個工作?你可以在活動之前設定運行意圖嗎? – Summit