Android:如何以正确的方式进行用户服务?

时间:2014-12-10 13:23:45

标签: android service

我有一项服务,当活动开始时我会用以下方式绑定到服务:

bindService(new Intent(BaseActivity.this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
这样正确吗?

我需要服务将在应用程序启动时启动并始终以后台模式运行。 如果用户在设置中手动停止应用程序,那么当应用程序再次启动时,服务也需要启动。

如果服务已经存在(已经在后台模式下运行),我就不需要创建服务。有正确的方式绑定到现有服务吗?

任何人都知道如何以正确的方式做到这一点?

提前致谢!

1 个答案:

答案 0 :(得分:2)

1.只需启动无限制服务,例如

startService(new Intent(BaseActivity.this, MyService.class));

2.以及在被OS杀死时自动重启服务

onStartCommand()返回START_STICKY

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

3.对于设置按钮停止

onDestroy()服务中再次启动服务

    @Override
public void onDestroy() {
        // starting the service when the service is destroyed.
        Intent intent = new Intent(this, YourService.class);
        startService(intent);
        super.onDestroy();

};

注意:如果您在“设置”中 FORCE_STOP您的应用,服务将停止