如何在强制停止应用程序后重新启动服务

时间:2014-01-30 09:15:36

标签: android 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;
      }

强制停止应用(设置 - >应用 - >强制停止应用)后,我的服务无法运行。怎么解决?

2 个答案:

答案 0 :(得分:2)

您确定该服务未重启吗?你投入回报的START_STICKY应该有一段时间。系统重新启动它需要一些时间,你可以把日志等待,以确保它重新启动。

答案 1 :(得分:2)

根据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.

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.

在强制停止应用时,Android只会终止进程ID。没有警告,回调服务/活动。根据Android document,当应用程序被杀死时,它有可能调用onPause()。

当我在我的应用程序中尝试时,即使onPause()也未被调用。 我认为唯一的方法是使用该意图标志并按照Chris的建议从另一个应用程序发送。