2014-04-16 45 views
1

嗨我试图使用我的APK中的AlarmManager设置闹钟。出于某种原因,在某些设备上,警报所花费的时间比预期的要长得多。有没有人有这方面的经验?我目前正在测试的设备是Android版本4.3。我有下面的代码在我的主要活动:Android AlarmManager不准确

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

有没有人有任何建议如何使警报更准确的所有设备ES?提前致谢。

回答

2

4.4上它们改变了警报管理器的工作方式。见https://developer.android.com/about/versions/android-4.4.html。基本上他们认为默认设置应该是牺牲精度来节省功耗,而你需要调用一个稍微不同的API来做另一种方式。

+0

我的targetSdkVersion设置为18,如果检测到KK设备,我也有代码可以使用新的API。在我的MainActivity中,我选择在if语句中使用哪个API – Mpressiv