Mpressiv
Mpressiv

Reputation: 48

Android AlarmManager Inaccurate

Hi I am trying to set an alarm using the AlarmManager in my APK. For some reason, on certain devices the alarm is taking much longer than intended to trigger. Does anyone have any experience for this? The device I am currently testing on is Android Version 4.3. I have the following code in my main 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);
}

My AlarmReceiver class looks like this:

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();
    }
 }

}

And finally my Android manifest file looks like this:

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

Does anyone have any suggestions on how to make the alarm more accurate on all devices? Thanks in advance.

Upvotes: 2

Views: 895

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93728

On 4.4 they changed how alarm manager works. See https://developer.android.com/about/versions/android-4.4.html. Basically they decided the default should be to sacrifice accuracy for power savings, and you need to call a slightly different api to do the other way.

Upvotes: 3

Related Questions