2012-06-23 76 views
5

我需要一直使用後臺服務來同步我的Android應用程序和服務器。我知道如何通過我的應用程序啓動它,但是當Android關閉時,後臺服務將會消失。當Android打開時啓動後臺服務

我該如何保持後臺服務始終運行? (即使設備關閉,然後打開...)

我需要添加到Android的啓動程序我的後臺服務。任何提示?

回答

15

使用<action android:name="android.intent.action.BOOT_COMPLETED" />爲設備打開時開始爲您服務。

AndroidManifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"> 
</uses-permission> 

在代碼的一部分BootBroadcastReceiver

public class BootBroadcastReceiver extends BroadcastReceiver {  
    static final String ACTION = "android.intent.action.BOOT_COMPLETED"; 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     // BOOT_COMPLETED」 start Service  
     if (intent.getAction().equals(ACTION)) { 
      //Service  
      Intent serviceIntent = new Intent(context, StartOnBootService.class);  
      context.startService(serviceIntent); 
     } 
    }  
} 

編輯:,如果你談論的是設備在AndroidManifest.xml作爲

<receiver android:name=".BootBroadcastReceiver" > 
      <intent-filter> 
       <action android:name="android.intent.action.BOOT_COMPLETED" /> 
      </intent-filter> 
     </receiver> 

添加權限屏幕開/關,那麼您需要註冊<action android:name="android.intent.action.USER_PRESENT" /><action android:name="android.intent.action.SCREEN_ON" />以在用戶存在或屏幕開啓時開始您的服務。

+0

當我打開手機時出現錯誤...「應用程序被迫...」。它不工作。 – Frion3L

+0

哪個錯誤你越來越可以編輯你的文章與錯誤? –