在Android 4.4 APIs page中,我读到了:
当您将应用的targetSdkVersion设置为“19”或更高时,会发出警报 使用set()或setRepeating()创建的将是不准确的。
[CUT]
这种不精确的批处理行为仅适用于更新的应用程序。如果你的话 将targetSdkVersion设置为“18”或更低,您的警报将继续 在Android 4.4上运行时,它们的行为与先前版本相同。
在我的应用程序中,我需要准确的时间警报,并将targetSdkVersion更新为“19”。以下代码是否正确?另外,如果我在手机中使用之前的版本将targetSdkVersion设置为“19”,那么“旧”方法AlarmManager.set是否会以相同的方式继续工作?
private void setAlarm (long ms){
final AlarmManager am = (AlarmManager) mCtx.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, BroadcastReceiverAlarm.class);
PendingIntent pi = PendingIntent.getBroadcast(this, ALARM_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT) {
am.set(AlarmManager.RTC, ms, pi);
} else {
setAlarmFromKitkat(am, ms, pi);
}
}
@TargetApi(19)
private void setAlarmFromKitkat(AlarmManager am, long ms, PendingIntent pi){
am.setExact(AlarmManager.RTC, ms, pi);
}
答案 0 :(得分:7)
是的,这是正确的。谷歌未能详细描述:
答案 1 :(得分:0)
我从ADT下载了4.1.2并卸载了4.4。 我将“Build Target”设置为4.1.2并清理并重建了我的应用程序并重新安装了apk到手机。
但是,这种行为仍然不准确。
我粘贴下面adb shell dumpsys alarm
的输出:
RTC_WAKEUP#0:闹钟{426941b0 type 0 net.coolbie.alarmclock}
type=0 when=+4m46s480ms repeatInterval=0 count=0
operation=PendingIntent{42553668: PendingIntentRecord{42a6cc38 net.coolbie.alarmclock broadcastIntent}}
你可以看到“when”在那里+ 4m,但是triggerTime只有8秒。
long triggerTime = calendar.getTimeInMillis();
long currentTime = System.currentTimeMillis();
Toast.makeText(mContext, "gap is:"+(triggerTime-currentTime)/1000,Toast.LENGTH_LONG).show();
Intent intent = new Intent(mContext.getApplicationContext(), AlarmReceiver.class);
PendingIntent pendIntent = PendingIntent.getBroadcast(mContext.getApplicationContext(),
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendIntent);