我读了这篇很棒的博客文章 Android Architecture Tutorial: Developing an App with a Background Service (using IPC)
作者展示了一个在固定时间间隔内在单独进程中运行的推文检索服务。
该服务将无限运行。我意识到要停止进程,转到管理应用并明确停止服务是唯一的方法。
请注意,这不是一种非常省电的方式。甚至作者也声称自己。
Yes, there is a dark side to Android background services too – too many services doing too much stuff in the background will slow down the phone and suck the battery. However it’s not quite what I wanted to bring up in this post, so maybe we’ll come back to resource management etiquette in yet another post.
但是,作者不再更新他的博客。
我尝试通过 TweetViewActivity
停止服务。
@Override
protected void onDestroy() {
super.onDestroy();
try {
api.removeListener(collectorListener);
unbindService(serviceConnection);
} catch (Throwable t) {
// catch any issues, typical for destroy routines
// even if we failed to destroy something, we need to continue destroying
Log.w(TAG, "Failed to unbind from the service", t);
}
// New code added by Cheok. Not working. Not sure why.
this.stopService(intent);
Log.i(TAG, "Activity destroyed");
}
但这行不通。我可以看到该服务仍在运行。我可以知道,一旦我退出 Activity
,停止 IPC 服务的正确方法是什么?对于上述示例,什么是好的电池节省策略?
最佳答案
它仍在运行的原因是系统从未调用过 onDestroy。
如果您查看此链接:http://developer.android.com/reference/android/app/Activity.html从图中可以看出,仅当系统即将从内存中清除您的应用程序时才会调用 onDestroy,并且根据内存限制,它可能根本不会被调用。
唯一保证被调用的回调是 onPause()
,您应该依靠它来停止服务。
关于android - 长时间运行的 IPC 服务的电池节省策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14052915/