Android:Sticky Service无法重启

时间:2015-04-24 22:03:03

标签: android service restart sticky

我的应用将服务用于后台任务。我希望服务在用户杀死应用程序时继续运行(轻扫它)。用户可以通过两种方式杀死应用程序:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent test = new Intent(this, TestService.class);
        startService(test);
    }
}

public class TestService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Service", "Service is restarted!");//In Scenario 2, it takes more than 5 minutes to print this. 
        return Service.START_STICKY;
    }

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

场景1完全按预期工作。应用程序在几秒钟内被刷掉后服务重新启动。

方案2无法按预期工作。该服务确实重新启动,但超过5分钟后。

我不明白为什么在方案2中重启服务需要这么长时间。是否有一个已知的解决方案?

getUrl()

1 个答案:

答案 0 :(得分:0)

当您按下后退按钮时,您实际上是在销毁活动,这意味着在您onDestroy() stop()的位置调出STICKY_SERVICE。因此,STICKY_SERVICE会立即再次启动。

当您按下主页按钮时,您将暂停活动(onPause()),基本上将其置于后台。仅当操作系统决定对其进行GC时,才会销毁该活动。只有在那个时间点,onDestroy()才会调用stop()服务,STICKY_SERVICE再次启动。

希望这有帮助。

相关问题