我正在寻找实施定期记录gps或其他传感器值的服务的最佳实践(每10-60秒)。当手机入睡时,该服务应处理待机模式。
非常感谢任何帮助(伪代码或教程)!
答案 0 :(得分:3)
即使设备可能已经入睡,看起来也不可能让方向传感器持续工作数小时(参考http://code.google.com/p/android/issues/detail?id=3708#makechanges
一旦显示屏熄灭,传感器就会一样...... :(
我现在实施了一个唤醒锁(需要许可)
<uses-permission android:name="android.permission.WAKE_LOCK" />
与计时器和广播记录器配合使用,可以重新打开显示屏。这当然是电池寿命的疯狂,但到目前为止我找不到其他方法。
这是我在服务中的onCreate方法:
@Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
CONTEXT = this;
PowerManager pm = (PowerManager) CONTEXT.getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "my tag");
mWakeLock.acquire();
Log.d(TAG, "Wakelock acquired");
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
这个服务的onStart方法:
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onStart");
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.d(TAG, "Screen is on");
} else {
Log.d(TAG, "Screen is off");
Timer timer = new Timer("DigitalClock");
timer.schedule(new TimerTask() {
@Override
public void run() {
Log.d(TAG,"Waiting 1 sec for switching the screen back on again...");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
"my tag");
mWakeLock.acquire();
}
}, 1000);
mWakeLock.acquire();
}
}
这是BroadcastReceiver类:
public class ScreenReceiver extends BroadcastReceiver { private boolean screenOff; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { screenOff = true; } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { screenOff = false; } Intent i = new Intent(context, MyService.class); i.putExtra("screen_state", screenOff); context.startService(i); }
}
这种解决方法也适用于通过USB从调试器插入UN的设备(我首先遇到此问题)。
如果您有更好的解决方案,或者2.3中有解决方法,请告诉我。感谢名单!
答案 1 :(得分:1)