1

我正在开发一个使用服务的应用程序。该服务本身可以工作,但 Android 系统会在退出我的 Activity 后 30 秒内将其杀死,有时甚至早至 6 秒。

我已经查看了很多关于此的不同帖子,并且知道我可以使用带有图标的前台服务。在这个阶段,我不想走这条路。

我使用以下代码明确启动服务。该服务由 SwitchPreference 控制。该服务还返回 START_STICKY 因此它会重新启动。

这是我正在使用的代码(不是这样一起运行的)。

// starting within the activity
Intent intent = new Intent(context, ListenerService.class);
startService(intent);

// stopping within the activity
Intent intent = new Intent(context, ListenerService.class);
stopService(intent);

// Service onStartCommand
return START_STICKY;

当我第一次退出应用程序时,我看到活动被破坏,然后在 30 秒内我看到我的 toast 消息显示,说明服务已重新启动。

我了解 Android 系统完全有权在内存不足时终止我的服务,但我是否应该期望它在我退出应用程序后几乎立即终止?它只是垃圾收集我的活动引用并启动服务“干净”吗?

我正在清理活动的 onStop() 方法中的对象。

另外,当我通过活动返回到我的应用程序时,绑定到服务以获取对服务对象的引用是一种好习惯吗?绑定在activity的onStart()方法中完成,如下:

Intent intent = new Intent(this, ListenerService.class);
bindService(intent, serviceConnection, 0);

在 onStop() 方法中完成解绑

unbindService(serviceConnection);

所以 2 个问题:
1. 我是否应该期望 Android 系统几乎立即终止并重新启动我的服务?
2. 我的绑定方法可以接受吗?

非常感谢

4

1 回答 1

0

据我了解,您通过调用 startService 和 stopService 来控制服务的生命周期。这个对吗?

如果要保持服务运行,为什么要调用 stopService 呢?

关于服务的重启——一切都取决于你的服务配置和你的代码实现。

于 2013-05-01T06:27:52.340 回答