Search code examples
androidwakelockandroid-jobscheduler

Explicit Wakelocks with JobScheduler/JobInfo


I am refactoring this code:

https://github.com/r3gis3r/CSipSimple/blob/master/src/com/csipsimple/utils/TimerWrapper.java

which uses AlarmManager to schedule timers. I am refactoring the code to use JobScheduler following the recommendations from Google:

/**
 * @param entryId
 * @param latencyMs
 * @brief Handler for schedule
 */
private synchronized int handleSchedule(int entryId, int latencyMs) {
    // clamp to minimum latencyMs
    latencyMs = (latencyMs < TIMER_MIN_LATENCY_MS) ? TIMER_MIN_LATENCY_MS : latencyMs;

    // Cancel previous registrations for the entryId
    mJobScheduler.cancel(entryId);
    int existingReg = mScheduleEntries.indexOf(entryId);
    if (existingReg != -1) {
        mScheduleEntries.remove(existingReg);
        mScheduleTimes.remove(existingReg);
    }

    long fireTimeMs = SystemClock.elapsedRealtime() + latencyMs;

    Log.v(TAG, "Schedule timer " + entryId + " in " + latencyMs + "ms @ " + fireTimeMs);

    ComponentName componentName = new ComponentName(mContext, PTAPITimerJobService.class);

    PersistableBundle persistableBundle = new PersistableBundle();
    persistableBundle.putInt(EXTRA_TIMER_ENTRY, entryId);
    persistableBundle.putLong(EXTRA_TIMER_EXPIRATION, fireTimeMs);

    final JobInfo.Builder jobInfoBuilder = new JobInfo.Builder(entryId, componentName).setExtras(persistableBundle);
    jobInfoBuilder.setMinimumLatency(latencyMs);

    // TODO - set wakelock criteria
    JobInfo jobInfo = jobInfoBuilder.build();
    mJobScheduler.schedule(jobInfo);

    mScheduleEntries.add(entryId);
    mScheduleTimes.add(fireTimeMs);
    return 1;
}

The above method is equivalent of doSchedule in the pasted link from CSipSimple. From the documentation of JobInfo, there are methods like: setRequiredNetworkType, setRequiresDeviceIdle for setting various conditions.

Question: Is it sufficient to mention these criteria in JobInfo or we need to manage an explicit WakeLock (as shown in the AlarmManager case)?

WakeLock types for the Timer:

public class WakeLockTypes {
    public static final int     LOCK_TYPE_NONE              = 0x0;
    public static final int     LOCK_TYPE_WIFI              = 0x1;  // Keep the Wi-Fi radio awake
    public static final int     LOCK_TYPE_WIFI_MULTICAST    = 0x2;  // Allow receiving of Wifi Multicast packets
    public static final int     LOCK_TYPE_POWER_WAKE        = 0x4;  // Keeps the device CPU on
    public static final int     LOCK_TYPE_SCREEN_DIM_WAKE   = 0x8;  // Keeps the screen on (dim)

    public static final int     LOCK_TYPE_DEFAULT   = (LOCK_TYPE_SCREEN_DIM_WAKE|LOCK_TYPE_WIFI); 

}

Solution

  • JobScheduler will keep your device awake while your job is running, so you do not need your own WakeLock.