且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

每当应用程序被杀死时服务停止

更新时间:2022-12-27 11:13:47

需要在manifest里面的service属性下添加android:process=:any_name".

You need to add "android:process=:any_name" in the manifest under the inside the service attributes.

例如

      <service android:name=".MyService"
        android:process=":MyService"
        android:enabled="true"/>

下面是我的服务类的代码.

Below is the code of my Service class.

public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


@Override
public void onCreate() {
    super.onCreate();
    Log.e("onCreate", "onCreate");
    Toast.makeText(AppController.getInstance(),"Created",Toast.LENGTH_SHORT).show();
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("servicedestroy", "servicedestroy");
    Toast.makeText(AppController.getInstance(),"service destroy",Toast.LENGTH_SHORT).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
                              @Override
                              public void run() {

                                  new Handler(Looper.getMainLooper()).post(new Runnable() {
                                      @Override
                                      public void run() {
                                          Toast.makeText(AppController.getInstance(),"Running",Toast.LENGTH_SHORT).show();
                                      }
                                  });


                              }

                          },
            0,
            5000);

    return START_STICKY;
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
            AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}

}