您好,我正在尝试使用 APK 中的 AlarmManager 设置闹钟。由于某种原因,在某些设备上,警报的触发时间比预期要长得多。有人有这方面的经验吗?我目前测试的设备是Android 4.3版本。我的主要 Activity 中有以下代码:
@SuppressLint("NewApi")
public void delay(long waitTime) {
//Toast.makeText(this, "Waiting For: " + waitTime + "ms", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
if (sdkVersion < 19)
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + waitTime, sender);
else
am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + waitTime, sender);
}
我的 AlarmReceiver 类如下所示:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
Log.d(MainActivity.TAG, "Alarm received at: " + System.currentTimeMillis());
Intent newIntent = new Intent(context, MainActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
newIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
context.startActivity(newIntent);
} catch (Exception e) {
Toast.makeText(context, "There was an error somewhere, but we still received an alarm " + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
最后我的 Android list 文件如下所示:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoDisplay" >
<receiver android:process=":remote" android:name="com.package.name.AlarmReceiver"></receiver>
<activity
android:name="com.package.name.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
有人对如何使所有设备上的警报更加准确有任何建议吗?提前致谢。
最佳答案
在 4.4 中,他们改变了警报管理器的工作方式。请参阅https://developer.android.com/about/versions/android-4.4.html 。基本上,他们认为默认值应该是牺牲准确性以节省电量,并且您需要调用稍微不同的 api 来执行其他操作。
关于Android AlarmManager 不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23116573/