Android Service stops after the app is killed

孤者浪人 提交于 2019-11-30 15:59:10

问题


I want to create a service that runs even when the app is closed from the Task manager. I have created a service and then Logged a message to check if it's running and I noticed that it works only if if the app is running or in foreground.

Service class:

public class CallService extends Service {

    private final LocalBinder mBinder = new LocalBinder();
    protected Handler handler;

    public class LocalBinder extends Binder {
        public CallService getService() {
            return CallService .this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TESTINGSERVICE", "Service is running");
    }
}

Starting the service from my MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
   ...
   startService(new Intent(this, CallService.class));

Manifest

<application>
   ...
   <service
      android:name=".activities.services.CallService">
   </service>
</application>

What changes do I have to make? Thanks, folks


回答1:


In your service, add the following code.

@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);
 }



回答2:


Best solution is add stopSelf() and add timeout between 70 to 100 millis sec in your service, if kelebro63's solution will not work.

@Override
   public void onTaskRemoved(Intent rootIntent) {
       stopSelf();
       Log.e("stopservice","stopServices");
       try {
           Thread.sleep(100);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       super.onTaskRemoved(rootIntent);
   }


来源:https://stackoverflow.com/questions/43310855/android-service-stops-after-the-app-is-killed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!