简体   繁体   English

强制停止应用后如何重启服务

[英]How to restart Service after Force Stop of app

Here is my Service 这是我的服务

public class SService extends Service {

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

        someTask();
      }

      public int onStartCommand(Intent intent, int flags, int startId) {

        someTask();

        return START_STICKY;
      }


      public IBinder onBind(Intent intent) {

        return null;
      }

After force stop of app (Settings->Application->Force Stop App) my Service doesn't run. 强制停止应用程序后(设置->应用程序->强制停止应用程序),我的服务无法运行。 How to solve it? 怎么解决呢?

Are you sure that the service isn't restarting? 您确定服务没有重新启动吗? The START_STICKY you put in the return should do the trick some time. 您在回程表中输入的START_STICKY应该可以解决问题。 It takes some time till the system restart it, you can put a log and wait to make sure it's getting restarted. 直到系统重新启动它需要一些时间,您可以放置​​一个日志并等待以确保它重新启动。

As per the Android document 根据Android 文档

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.

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 stoppped 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. 在应用程序强制停止时,Android会杀死进程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(). 根据Android 文档 ,当应用被杀死时,它有可能调用onPause()。

When I tried in my app, even onPause() was not called. 当我在应用程序中尝试时,甚至没有调用onPause()。 I think the only way is use to that intent flag and send it from another app as suggested by Chris. 我认为唯一的方法就是使用该意图标志,并按照克里斯的建议从另一个应用程序发送它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM