用户或系统杀死它时以编程方式重新启动服务

时间:2018-03-30 06:40:25

标签: android service background-service

我有一个后台服务,即使我的主要活动被杀或处于后台,也会运行很长时间。

问题出在:

  1. 用户从设置手动杀死服务---> app ---> myapp 强制停止
  2. 功耗密集型模式(例如华为的超级模式)处于活动状态
  3. 在这种情况下,我的服务被终止,无法自动重启。

    这是我的服务代码:

    public class MyService extends Service {
    
      protected final String TAG = this.getClass().getName();
    
      @Override
      public void onCreate() {
        super.onCreate();
      }
    
      @Override
      public final int onStartCommand(Intent intent, int flags, int startId) {
    
          Log.i(TAG, "onStarCommand(): Received id " + startId + ": " + intent);
          return START_STICKY;
    
      }
    
      @Override
      public final IBinder onBind(Intent intent) {
        return m_messenger.getBinder();
      }
    
      @Override
      public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "Service Stopped.");
      }    
    
      @Override
      public void onTaskRemoved(Intent rootIntent){
        Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
        restartServiceTask.setPackage(getPackageName());    
        PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        myAlarmService.set(
            AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartPendingIntent);
    
        super.onTaskRemoved(rootIntent);
      }
    }
    

0 个答案:

没有答案