2015-12-23 88 views
0

當我試過這段代碼時,一切正常,除非設備重啓後服務沒有啓動。我想自動啓動相同的服務。我正在通過將移動設備與USB連接來測試此示例。我需要改變什麼? [http://javatechig.com/android/repeat-alarm-example-in-android]關機後的鬧鐘管理器

+2

試試這個。 [如果設備重啓,啓動AlarmManager](http://stackoverflow.com/questions/17673746/start-alarmmanager-if-device-is-rebooted) –

+0

你是否啓用了這個廣播接收器「android.intent.action.BOOT_COMPLETED」 –

+0

回答

0

你必須創建一個廣播接收器將偵聽啓動完成事件,當接收到該事件再次開始

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

您的服務創建一個類,像這樣在的onReceive方法中添加代碼

public class Autostart extends BroadcastReceiver 
{ 
    public void onReceive(Context arg0, Intent arg1) 
    { 
     Log.i("Autostart", "**********started************"); 
    } 
} 
1

嘗試這樣

<!-- for reboot event to reset alarms --> 
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 

然後

<receiver 
     android:name="com.yourapp.receiver.RestartAppReceiver" 
     android:enabled="true" 
     android:exported="true"> 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
     </intent-filter> 
    </receiver> 

下次你要創建的BroadcastReceiver類

public class RestartAppReceiver extends BroadcastReceiver { 

    private static final String LOG_TAG = "RestartAppReceiver"; 

    public RestartAppReceiver() { 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     if (intent != null) { 
      String action = intent.getAction(); 

      switch (action) { 
       case Intent.ACTION_BOOT_COMPLETED: 
        Log.i(LOG_TAG, "Start resetting alarms after reboot"); 


        //restart what you need 


        Log.i(LOG_TAG, "Finish resetting alarms after reboot"); 
        break; 
       default: 
        break; 
      } 
     } 
    } 
} 
+0

在那裏我打電話給RestartAppReceiver –

+0

@UsmanAsif沒有必要做一個call.define這樣的清單,然後它會在重啓事件發生時 –