即使使用唤醒锁,Android服务也会停止

时间:2011-05-05 21:11:12

标签: android service wakelock

我一定不能正确实施唤醒锁。这就是我做到的。这是对的吗?

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();服务在一段时间不活动后仍然被杀死。谢谢你的帮助! -dom

1 个答案:

答案 0 :(得分:1)

如果某项服务暂时处于活动状态,Android会将其终止。通常,开发人员会将服务设置为优先级,但这会导致电池寿命缩短。如果你需要保持一个长期运行的服务,你现在必须在服务类中使用新的startForeground api在通知栏中发布一个图标。

developer.android

如果您需要,我创建了一个使其向后兼容Android 1.5和1.6的类.... ServiceForegrounder.java