Android AlarmManager不准确

时间:2014-04-16 17:48:10

标签: android apk alarmmanager

您好我正在尝试使用我的APK中的AlarmManager设置闹钟。出于某种原因,在某些设备上,警报所需的时间比触发时间长得多。有没有人有这方面的经验?我目前正在测试的设备是Android版本4.3。我的主要活动中有以下代码:

@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清单文件如下所示:

<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>

有没有人对如何在所有设备上使报警更准确有任何建议?提前谢谢。

1 个答案:

答案 0 :(得分:3)

在4.4上,他们改变了警报管理器的工作方式。见https://developer.android.com/about/versions/android-4.4.html。基本上他们认为默认应该是牺牲功率节省的准确性,你需要调用稍微不同的api来做其他方式。