我正在編寫一個應每10秒收集一些傳感器數據並將它們寫入磁盤的應用程序。定期運行任務,*即使設備處於空閒狀態*
到目前爲止,我有一個啓動服務的Activity。該服務有一個可運行的,它使用一個處理程序通過handler.postDelayed()
定期運行我的任務。請參閱下面的(縮寫)代碼。
到目前爲止,只要設備處於活動狀態,此工作正常。一旦設備進入空閒狀態,它不會運行我的任務,直到它再次喚醒。
所以,我的問題是如何運行我的任務總是。
隨着setExactAndAllowWhileIdle()
的AlarmManager似乎提供正是我需要的,但是......
要減少濫用,也有對這些報警將如何頻繁地去關閉特定應用程序的限制。在正常的系統操作下,它不會在大約每分鐘的時間內發送這些警報(此時每個這樣的待處理警報都會發送)。當處於低功率空閒模式時,這個持續時間可能會明顯更長,例如15分鐘。
電池壽命只是次要的優先事項,雖然沒有被喚醒整個時間都可以。 (不知道機器人可以只是一秒鐘左右醒來)
MyActivity
...
public void onStartService(View view) {
Intent i= new Intent(getBaseContext(), MyAppService.class);
getBaseContext().startService(i);
}
public void onStopService(View view) {
stopService(new Intent(getBaseContext(), MyAppService.class));
}
....
爲MyService
public class MyAppService extends Service {
MyRunnable mr;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mr= new MyRunnable(getApplicationContext());
mr.Start();
return Service.START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
mr.Stop();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
MyRunnable
public class MyRunnable implements Runnable{
// context is needed for sensorListener (?)
private Context myContext;
private Handler handler;
public MyRunnable(Context c){
myContext=c;
handler= new Handler();
}
public void Start(){
run();
}
public void Stop(){
handler.removeCallbacks(this);
// some clean-up
}
@Override
public void run() {
//acquire and write to file some sensor data
handler.postDelayed(this, 10000);
}
}
如果這是關於Marshmellow Doze,您可以閱讀:http://stackoverflow.com/documentation/android/1361/alarmmanager/14777/api23-doze-mode-interferes-with-alarmmanager爲電池創建一個例外優化你的應用程序。我不確定這是否會影響警報的最小間隔,儘管... – devnull69
@ devnull69:但是,我也覺得這並不影響AlarmManager允許的最大速率。 – sweber