2014-04-16 92 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