1

i am making an android widget which is active only when the screen is on, to prolong battery life. so i have one service which run all the time and reacts to ACTION_SCREEN_ON and ACTION_SCREEN_OFF. when the screen turns off i unregister other broadcast receivers and when the screen turns on i register them again.

my question is, what is the best practice, regarding battery life, to do when the screen turns off. is it better also to delete the broadcast receiver variables (i.e. m_Receiver = null;) or is unregistering enough? deleting means more free memory for the system, but causes garbage collection and extra memory operations (when the screen turns on i have to create a new receiver) which are expensive...

4

1 回答 1

0

我正在制作一个仅在屏幕打开时才处于活动状态的 android 小部件,以延长电池寿命。

首先,我假设“小部件”是指“应用小部件”。

其次,应用小部件永远不会“活跃”。

所以我有一项服务一直在运行并对 ACTION_SCREEN_ON 和 ACTION_SCREEN_OFF 做出反应。

这不是一个好主意。首先,保留进程会浪费数兆字节的 RAM。其次,它不会工作,因为Android不会让服务“一直运行”——它最终会关闭你的服务。第三,用户对像您这样一直在运行服务的开发人员感到恼火,因此他们会使用任务杀手(Android 2.1 及以下版本)或设置应用程序中的管理服务屏幕(Android 2.0 及更高版本)来终止您的服务)。

当屏幕关闭时,我取消注册其他广播接收器,当屏幕打开时,我再次注册它们。

我不知道“其他广播接收器”是什么。他们可能不应该首先注册。

我的问题是,当屏幕关闭时,关于电池寿命的最佳做法是什么。还是删除广播接收器变量(即 m_Receiver = null;)更好还是取消注册就足够了?删除意味着系统有更多的可用内存,但会导致垃圾收集和额外的内存操作(当屏幕打开时我必须创建一个新的接收器),这些操作很昂贵......

考虑到您在服务上占用了多少内存,担心这一点是没有意义的。专注于摆脱永恒的服务。

例如,假设此应用小部件正在显示电池电量。没有一个永恒的服务正在观看ACTION_BATTERY_CHANGED。相反,让用户选择一个轮询周期(例如,每五分钟一次)并用于AlarmManager定期检查电池电量。

于 2011-03-27T10:54:02.333 回答