2012-10-14 189 views
2

我需要我的應用程序在重新啓動設備後開始運行(在後臺)。下面是我想出現在爲止(後服用大量從這裏幫助...)如何在重新啓動後通過服務啓動活動

這是我BootUpReceiver利用廣播接收器的:

public class BootUpReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent serviceIntent = new Intent(context, RebootService.class); 
     serviceIntent.putExtra("caller", "RebootReceiver"); 
     context.startService(serviceIntent); 
    } 
} 

這是服務類:

public class RebootService extends IntentService{ 

    public RebootService(String name) { 
     super(name); 
     // TODO Auto-generated constructor stub 
} 

protected void onHandleIntent(Intent intent) { 

     Intent i = new Intent(getBaseContext(), MainActivity.class); 
     i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

     String intentType = intent.getExtras().getString("caller"); 
     if(intentType == null) 
      return; 
     if(intentType.equals("RebootReceiver")) 
      getApplication().startActivity(i);    
    } 
} 

這是我的Android清單:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
    <receiver 
     android:name=".BootUpReceiver" 
     android:enabled="true" 
     android:permission="android.permission.RECEIVE_BOOT_COMPLETED" > 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 

      <category android:name="android.intent.category.DEFAULT" /> 
     </intent-filter> 
    </receiver> 

    <service android:name=".RebootService"/> 
</application> 

的問題是,當我安裝這在我的手機上,並重新啓動,該應用程序崩潰:它說,「傳輸已停止工作」。按OK按鈕後,當我檢查應用程序信息時,該應用程序正在運行。

我是新來的android,我不知道發生了什麼。我應該添加更多的權限?

請幫忙。 TIA

回答

0

我認爲你的問題在於你的RebootService構造函數。當系統調用它時,它不提供任何參數,所以它會崩潰。如果您在日誌中查找你可能會看到的東西的影響「無法實例化服務......」

試着用替換你的構造:

public RebootService() { 
    super("Reboot Service"); 
} 
+0

感謝。讓我試試看,並找回你..我找到了構造函數腥 – blueren

+0

更新:它的作品。現在,當我重新啓動時,活動啓動..但我真正想要的是應用程序在後臺啓動:| – blueren

+0

這是您的設計問題,而不是代碼問題。你正在開始一個活動,這將在前臺出現。如果你想在後臺使用它,那麼你必須在你的服務中做任何你正在做的事情,而不是開始一個活動。 – Ralgha