How to automatically restart a service even if user force close it?

后端 未结 10 833
感情败类
感情败类 2020-11-27 11:19

I want a service to run all the time in my application. So I want to restart it even if it is force closed by user. There is definitely a way to do it as apps like facebook

10条回答
  •  没有蜡笔的小新
    2020-11-27 11:37

    As per the Android document

    Starting from Android 3.1, the system's package manager keeps track of applications 
    that are in a stopped state and provides a means of controlling their launch from 
    background processes and other applications.
    
    Note that an application's stopped state is not the same as an Activity's stopped
    state. The system manages those two stopped states separately.
    FLAG_INCLUDE_STOPPED_PACKAGES — Include intent filters of stopped applications in the
    list of potential targets to resolve against.
    
    FLAG_EXCLUDE_STOPPED_PACKAGES — Exclude intent filters of stopped applications from the
    list of potential targets.
    
    When neither or both of these flags is defined in an intent, the default behavior is to
    include filters of stopped applications in the list of potential targets. 
    
    Note that the system adds FLAG_EXCLUDE_STOPPED_PACKAGES to all broadcast intents.
    It does this to prevent broadcasts from background services from inadvertently or
    unnecessarily launching components of stopped applications. A background service 
    or application can override this behavior by adding the FLAG_INCLUDE_STOPPED_PACKAGES
    flag to broadcast intents that should be allowed to activate stopped applications.
    

    On Force stop of app, Android just kill the process ID. No warnings, callbacks are given to service/activities. As per the Android document, When the app is killed there are chances that it calls onPause().

    When I tried in my app, even onPause() was not called. I think the only way is use to FLAG_INCLUDE_STOPPED_PACKAGES intent flag and send it from another app

提交回复
热议问题