我想創建應用程序,我需要每1,5,10分鐘發送一次位置更新等等。報警管理器沒有按時觸發
當應用程序正在運行,它準確地工作,但是當它進入背景/睡眠模式它不能準確地工作。
我嘗試了兩種方法setRepeating/setInExactRepeating
,但沒有一個在後臺模式下工作。
public static void startSensorAlaram(Context ctx, long minutes) {
AlarmManager alarmManager = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
// Alarm_Receiver is a broadcast receiver.
Intent intent = new Intent(ctx, Alaram_Receiver.class);
intent.setAction(Utility.SENSOR_ACTION);
PendingIntent pi = PendingIntent.getBroadcast(ctx, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),minutes,pi);
// alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), minutes, pi);
}
public static void stopAlaramSensor(Context ctx) {
Intent intent = new Intent(ctx, Alaram_Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 1,
intent, 0);
AlarmManager alarmManager = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
Alarm Receiver - Broadcast receiver
public class Alaram_Receiver extends WakefulBroadcastReceiver {
private SharedPreferences sp;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
sp = context.getSharedPreferences(Utility.SHARED_PREFS, 0);
if (intent.getAction().equalsIgnoreCase(Utility.SENSOR_ACTION)) {
if (sp.getBoolean("logged_in", false)) {
// context.startService(new Intent(context,SensorService.class));
startWakefulService(context,new Intent(context,SensorService.class));
} else
Utility.stopAlaramSensor(context);
}
}
}
Note:-
敏API版本15和編譯的版本是23
哪個版本? – nuuneoi
這是Android 5.1和6.0 @nuuneoi – moDev
請查閱['AlarmManager']的文檔(http://developer.android.com/reference/android/app/AlarmManager.html)。從KitKat開始,如果你的'targetSdkVersion'> = 19,'setRepeating()'是不精確的。您需要使用'setExact()',並在每次觸發時再次將鬧鐘設置爲所需的時間間隔。 –