2017-03-31 38 views
0

我想在Android中創建永無止境的後臺服務。要做到這一點,我使用AlarmManager與簡單ServiceAlarmmanger在一段時間後發送廣播,在廣播接收機我正在檢查服務正在運行,如果運行,然後什麼也不做,再次啓動它。當從最近的任務列表中殺死應用程序時,Android後臺服務永遠不會啓動

我的服務代碼是

public class MyService extends Service { 
    public MyService() { 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
      return null; 
    } 
    @Override 
    public void onCreate() { 
     super.onCreate (); 
     Log.e ("My service ", "oncreate"); 
    } 

    @Override 
    public void onTaskRemoved(Intent rootIntent) { 
     scheduleAlarm(); 
     super.onTaskRemoved (rootIntent); 
    } 
    // Setup a recurring alarm every half hour 
    public void scheduleAlarm() { 
     // Construct an intent that will execute the ServiceAlarmReceiver 
     Intent intent = new Intent("com.hmkcode.android.USER_ACTION"); 
     // Create a PendingIntent to be triggered when the alarm goes off 
     final PendingIntent pIntent = PendingIntent.getBroadcast(this, ServiceReceiver.REQUEST_CODE, 
       intent, PendingIntent.FLAG_UPDATE_CURRENT); 
     // Setup periodic alarm every 5 seconds 
     long firstMillis = System.currentTimeMillis()+5000; // alarm is set right away 
     AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); 
     // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTCWAKEUP 
     // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY 
     alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 
       6000, pIntent); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 

     Log.e ("My Service:", " on Start Command"); 
      return START_STICKY; 
    } 
} 

廣播接收機

public class ServiceReceiver extends WakefulBroadcastReceiver { 

    public static final int REQUEST_CODE=12355; 
    public ServiceReceiver() { 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO: This method is called when the BroadcastReceiver is receiving 
     // an Intent broadcast. 
     // check service is running or not 
     if (isMyServiceRunning (MessageService.class,context)){ 
      // don nothing 

     } 
     else { 
      // launch the service 
      if (isConnectedToInternet (context)) { 
       Intent serviceIntent = new Intent (context, MyService.class); 
       context.startService (serviceIntent); 
      } 
     } 


     Log.e ("hello","wer are in Receiver"); 
     // throw new UnsupportedOperationException ("Not yet implemented"); 
    } 
} 

我的清單:

<receiver 
      android:name=".Services.ServiceReceiver" 
      android:enabled="true" 
      android:exported="true" 
      android:process=":remote"> 

      <intent-filter> 
       <action android:name="com.hmkcode.android.USER_ACTION" /> 
      </intent-filter> 
     </receiver> 

     <service 
      android:name=".Services.MyService" 
      android:enabled="true" 
      android:stopWithTask="false" 
      android:process=":remote" 

     > 
     </service> 

它工作得很好,當應用程序在前臺或後臺,但問題是當我從Android中的最近任務列表中掃出應用程序時,a pp因爲服務而死亡,我的廣播接收機無法再次啓動它?我在onTaskRemoved方法中重新計劃了我的Alarmmanger方法,但服務仍然沒有重新開始。

同樣返回START_STICKYonStartCommand()正如人們所說的那樣,系統將重新啓動服務,即使必須停止資源限制。

也使用"stopWithTask"=false<service>清單文件的標記。它也沒有影響。

回答

0

我已經成功通過報警管理器創建一個PendingIntent並通過代碼而不是通過聲明來實例化它。

public class HeartbeatReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     try{ 
      Log.i(MainService.TAG, "** Heartbeat onReceive **"); 
      if (!Utility.isMyServiceRunning(context)){ 
       Log.i(MainService.TAG, "Service is dead. Restarting..."); 
       context.startService(new Intent(context, MainService.class)); 
       return; 
      } 
     } 
    } 

    public void StartHeartbeat(Context context, int interval) { 
     this.CancelHeartbeat(context); 
     AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
     Intent i = new Intent(context, HeartbeatReceiver.class); 
     PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); 
     am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pi); 
    } 

    public void CancelHeartbeat(Context context) { 
     Intent intent = new Intent(context, HeartbeatReceiver.class); 
     PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); 
     AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
     alarmManager.cancel(sender); 
    } 
} 

我在應用程序類中以編程方式初始化接收器。當意圖在清單中創建時似乎沒有工作。

public class MainApp extends Application { 
    @Override 
    public void onCreate(){ 
     super.onCreate(); 
     MainService.baseContext = getBaseContext(); 
     HeartbeatReceiver heartBeat = new HeartbeatReceiver(); 
     heartBeat.StartHeartbeat(MainService.baseContext, 60 * 1000 * 5); 

    } 
} 

然後,只需在清單中接收並無意

<receiver android:name="HeartbeatReceiver"/> 

這是嘗試,所以我也不清楚爲什麼它的工作原理,但如果我殺程序的時候,回來成功的結果當下一次報警運行時。希望有所幫助。

相關問題