Restart the service even if app is force-stopped and Keep running service in background even after closing the app How?

前端 未结 8 588
陌清茗
陌清茗 2020-11-30 02:24

I am trying to run a service in the background. What my app does is when user checks checkbox then service starts and when it is unchecked service is stopped. Which is worki

8条回答
  •  无人及你
    2020-11-30 02:39

    You cannot prevent your service from being killed under all circumstances. However, you can ask the system to restart it. There are two cases: (1) the process dies for some abnormal reason (2) the phone reboots. In the former, START_STICKY or START_REDELIVER_INTENT are used to restart the service. In the latter, you'll need to add a BroadcastReceiver for android.intent.action.BOOT_COMPLETED.

    Your code is returning START_STICKY from onStartCommand, so you've chosen one of the service restart paths: "if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service..."

    "This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback."

    You can also use START_REDELIVER_INTENT.

    Note that if your service is doing any significant work, it needs to run in a background thread.

    http://developer.android.com/reference/android/app/Service.html#START_STICKY

提交回复
热议问题