我创建了一个intent服务,它应该以用户定义的时间间隔向服务器发送数据,但在我的情况下,警报管理器不能正确维护间隔。你可以指导我做错误的地方。我想在设备处于睡眠或空闲模式时运行服务。这是我的代码。
public void sosalarmson() {
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, AlarmReceiver.receivercode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), Integer.parseInt(userdefinedinterval) *60* 1000, pendingIntent);
Toast.makeText(FinalSettings.this, "alarm On", Toast.LENGTH_SHORT).show();
}
理想情况下,如果我将用户输入设为15,那么闹钟应该在15分钟发送意图,而在10分钟发送。
答案 0 :(得分:0)
我正在使用此代码,它运行正常:
定义:
final int SDK_INT = Build.VERSION.SDK_INT;
AlarmManager al;
PendingIntent fintent;
Intent notif;
我使用报警管理器直接启动服务._alarm是您预定义的时间间隔。
long _alarm;
Calendar now = Calendar.getInstance();
Calendar wakeupcall = Calendar.getInstance();
wakeupcall.setTimeInMillis(System.currentTimeMillis());
wakeupcall.set(Calendar.HOUR_OF_DAY, 18);
wakeupcall.set(Calendar.MINUTE, 30);
if (wakeupcall.getTimeInMillis() <= now.getTimeInMillis())
_alarm=wakeupcall.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1);
else
_alarm=wakeupcall.getTimeInMillis();
al = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
notif= new Intent(this,TestNotifyService.class);
fintent = PendingIntent.getService(this,0,notif,0);
if (SDK_INT < Build.VERSION_CODES.KITKAT) {
al.set(AlarmManager.RTC_WAKEUP,_alarm, fintent);
}
else if (Build.VERSION_CODES.KITKAT <= SDK_INT && SDK_INT < Build.VERSION_CODES.M) {
al.setExact(AlarmManager.RTC_WAKEUP,_alarm,fintent);
}
else if (SDK_INT >= Build.VERSION_CODES.M) {
al.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,_alarm,fintent);
}