使用Android 4.4 Kitkat设置闹钟

12
Android 4.4 APIs页面中,我读到:

当你将应用程序的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);
}
2个回答

7

是的,这是正确的。谷歌未能提供更多详细信息:

  1. 对于targetSDKVersion<19,在运行KitKat或早期版本的设备上,“set”将是精确的。
  2. 对于targetSDKVersion>=19,在运行小于KitKat的设备上,“set”将是精确的。但对于运行KitKat的设备,它将是不精确的。

0

我从ADT下载了4.1.2并卸载了4.4。 我将“Build Target”设置为4.1.2,清理并重新构建了我的应用程序,并重新安装了apk到手机。

然而,行为仍然不精确。

我在下面粘贴了adb shell dumpsys alarm的输出:

RTC_WAKEUP #0: Alarm{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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接