即使唤醒锁到位,Android 服务也会停止
我一定没有正确实现唤醒锁。我就是这样做的。这是正确的吗?
private static final String LOCK_NAME_STATIC="domination.shredAssistant.locationService";
private static volatile PowerManager.WakeLock lockStatic=null;
synchronized private static PowerManager.WakeLock getLock(Context context) {
if (lockStatic==null) {
PowerManager mgr=(PowerManager)context.getSystemService(Context.POWER_SERVICE);
lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
LOCK_NAME_STATIC);
lockStatic.setReferenceCounted(true);
}
return(lockStatic);
}
和 onStart 方法
//onStart
public void onStart( Intent intent, int startId ) {
super.onStart( intent, startId );
if (running == false) {
Context ctxt=getApplicationContext();
getLock(ctxt).acquire();
running = true;
readResorts();
serviceHandler = new Handler();
serviceHandler.postDelayed( new RunTask(),1000L );
runtest=true;
locupdate(0,0);
}
}
我似乎无法弄清楚为什么服务在一段时间不活动后仍然被终止,即使我使用 getLock(ctxt).acquire();感谢您的帮助! -多姆
I must not have implemented the wakelocks correctly. This is how I did it. Is this correct?
private static final String LOCK_NAME_STATIC="domination.shredAssistant.locationService";
private static volatile PowerManager.WakeLock lockStatic=null;
synchronized private static PowerManager.WakeLock getLock(Context context) {
if (lockStatic==null) {
PowerManager mgr=(PowerManager)context.getSystemService(Context.POWER_SERVICE);
lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
LOCK_NAME_STATIC);
lockStatic.setReferenceCounted(true);
}
return(lockStatic);
}
and the onStart method
//onStart
public void onStart( Intent intent, int startId ) {
super.onStart( intent, startId );
if (running == false) {
Context ctxt=getApplicationContext();
getLock(ctxt).acquire();
running = true;
readResorts();
serviceHandler = new Handler();
serviceHandler.postDelayed( new RunTask(),1000L );
runtest=true;
locupdate(0,0);
}
}
I can't seem to figure out why the service is still killed after a period of inactivity even though I use getLock(ctxt).acquire(); Thanks for your help! -Dom
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果某个服务已经处于非活动状态相当长一段时间,Android 就会终止它。通常开发人员会将服务设置为前台优先级,但这会导致电池寿命缩短。如果您需要保持长期运行的服务,您现在必须在服务类中使用新的 startForeground api 在通知栏中发布图标。
developer.android
我创建了一个类,如果您需要它,它可以向后兼容 Android 1.5 和 1.6.... ServiceForegrounder.java
If a service has been in-active for quite sometime Android will kill it. Normally developers would set services to foregrounded priority but this caused poor battery life. If you need to keep a long running service you'll now have to use the new startForeground api in the service class to post an icon in the notification bar.
developer.android
I created a class that makes this backwards compatible to Android 1.5 and 1.6 if you need it.... ServiceForegrounder.java