Java Code Examples for android.app.job.JobInfo#Builder

The following examples show how to use android.app.job.JobInfo#Builder . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CumulusJobService.java    From CumulusTV with MIT License 8 votes vote down vote up
@Deprecated
public static void requestImmediateSync1(Context context, String inputId, long syncDuration,
        ComponentName jobServiceComponent) {
    if (jobServiceComponent.getClass().isAssignableFrom(EpgSyncJobService.class)) {
        throw new IllegalArgumentException("This class does not extend EpgSyncJobService");
    }
    PersistableBundle persistableBundle = new PersistableBundle();
    if (Build.VERSION.SDK_INT >= 22) {
        persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        persistableBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    }
    persistableBundle.putString(EpgSyncJobService.BUNDLE_KEY_INPUT_ID, inputId);
    persistableBundle.putLong("bundle_key_sync_period", syncDuration);
    JobInfo.Builder builder = new JobInfo.Builder(1, jobServiceComponent);
    JobInfo jobInfo = builder
            .setExtras(persistableBundle)
            .setOverrideDeadline(1000)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .build();
    scheduleJob(context, jobInfo);
    Log.d(TAG, "Single job scheduled");
}
 
Example 2
Source File: YourLocalWeather.java    From your-local-weather with GNU General Public License v3.0 8 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    appendLog(this, TAG,"Default locale:", Resources.getSystem().getConfiguration().locale.getLanguage());
    PreferenceManager.getDefaultSharedPreferences(this)
            .edit()
            .putString(Constants.PREF_OS_LANGUAGE, Resources.getSystem().getConfiguration().locale.getLanguage())
            .apply();
    LanguageUtil.setLanguage(this, PreferenceUtil.getLanguage(this));

    sTheme = PreferenceUtil.getTheme(this);

    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
        JobScheduler jobScheduler = getSystemService(JobScheduler.class);
        appendLog(this, TAG, "scheduleStart at YourLocalWeather");
        AppPreference.setLastSensorServicesCheckTimeInMs(this, 0);
        jobScheduler.cancelAll();
        ComponentName serviceComponent = new ComponentName(this, StartAutoLocationJob.class);
        JobInfo.Builder builder = new JobInfo.Builder(StartAutoLocationJob.JOB_ID, serviceComponent);
        builder.setMinimumLatency(1 * 1000); // wait at least
        builder.setOverrideDeadline(3 * 1000); // maximum delay
        jobScheduler.schedule(builder.build());
    }
}
 
Example 3
Source File: BootReceiver.java    From ml-authentication with Apache License 2.0 6 votes vote down vote up
@Override
    public void onReceive(Context context, Intent intent) {
        Log.d(getClass().getName(), "onReceive");

//        // Automatically open application
//        Intent bootIntent = new Intent(context, MainActivity.class);
//        bootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(bootIntent);

        // Initiate background job for synchronizing with server content
        ComponentName componentName = new ComponentName(context, ContentSynchronizationJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(LiteracyApplication.CONTENT_SYNCRHONIZATION_JOB_ID, componentName);
        builder.setPeriodic(1000 * 60 * 30); // Every 30 minutes
        JobInfo jobInfo = builder.build();
        JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(jobInfo);

        /*if (StartPrefsHelper.scheduleAfterBoot(context)){
            scheduleAuthenticationJobs(context);
        } else {
            Log.i(getClass().getName(), "Authentication jobs won't be scheduled because the 7 days after first start-up haven't passed yet.");
        }*/

        scheduleAuthenticationJobs(context);
    }
 
Example 4
Source File: UpdateWeatherService.java    From your-local-weather with GNU General Public License v3.0 6 votes vote down vote up
private void resendTheIntentInSeveralSeconds(int seconds) {
    appendLog(getBaseContext(), TAG, "resendTheIntentInSeveralSeconds:SDK:", Build.VERSION.SDK_INT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        ComponentName serviceComponent = new ComponentName(this, UpdateWeatherResendJob.class);
        JobInfo.Builder builder = new JobInfo.Builder(UpdateWeatherResendJob.JOB_ID, serviceComponent);

        builder.setMinimumLatency(seconds * 1000); // wait at least
        builder.setOverrideDeadline((3 + seconds) * 1000); // maximum delay
        JobScheduler jobScheduler = getSystemService(JobScheduler.class);
        jobScheduler.schedule(builder.build());
        appendLog(getBaseContext(), TAG, "resendTheIntentInSeveralSeconds: sent");
    } else {
        AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),
                0,
                new Intent(getBaseContext(), UpdateWeatherService.class),
                PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + (1000 * seconds), pendingIntent);
    }
}
 
Example 5
Source File: BackgroundTaskSchedulerJobService.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static JobInfo createJobInfoFromTaskInfo(Context context, TaskInfo taskInfo) {
    PersistableBundle jobExtras = new PersistableBundle();
    jobExtras.putString(BACKGROUND_TASK_CLASS_KEY, taskInfo.getBackgroundTaskClass().getName());

    PersistableBundle persistableBundle = getTaskExtrasAsPersistableBundle(taskInfo);
    jobExtras.putPersistableBundle(BACKGROUND_TASK_EXTRAS_KEY, persistableBundle);

    JobInfo.Builder builder =
            new JobInfo
                    .Builder(taskInfo.getTaskId(),
                            new ComponentName(context, BackgroundTaskJobService.class))
                    .setExtras(jobExtras)
                    .setPersisted(taskInfo.isPersisted())
                    .setRequiresCharging(taskInfo.requiresCharging())
                    .setRequiredNetworkType(getJobInfoNetworkTypeFromTaskNetworkType(
                            taskInfo.getRequiredNetworkType()));

    if (taskInfo.isPeriodic()) {
        builder = getPeriodicJobInfo(builder, taskInfo);
    } else {
        builder = getOneOffJobInfo(builder, taskInfo);
    }

    return builder.build();
}
 
Example 6
Source File: PlatformScheduler.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("MissingPermission")
private static JobInfo buildJobInfo(
    int jobId,
    ComponentName jobServiceComponentName,
    Requirements requirements,
    String serviceAction,
    String servicePackage) {
  JobInfo.Builder builder = new JobInfo.Builder(jobId, jobServiceComponentName);

  if (requirements.isUnmeteredNetworkRequired()) {
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
  } else if (requirements.isNetworkRequired()) {
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
  }
  builder.setRequiresDeviceIdle(requirements.isIdleRequired());
  builder.setRequiresCharging(requirements.isChargingRequired());
  builder.setPersisted(true);

  PersistableBundle extras = new PersistableBundle();
  extras.putString(KEY_SERVICE_ACTION, serviceAction);
  extras.putString(KEY_SERVICE_PACKAGE, servicePackage);
  extras.putInt(KEY_REQUIREMENTS, requirements.getRequirements());
  builder.setExtras(extras);

  return builder.build();
}
 
Example 7
Source File: BackgroundDownloadService.java    From shortyz with GNU General Public License v3.0 6 votes vote down vote up
private static JobInfo getJobInfo(boolean requireUnmetered, boolean allowRoaming,
                                  boolean requireCharging) {
    JobInfo.Builder builder = new JobInfo.Builder(
            JobSchedulerId.BACKGROUND_DOWNLOAD.id(),
            new ComponentName("com.totsp.crossword.shortyz",
                    BackgroundDownloadService.class.getName()));

    builder.setPeriodic(TimeUnit.HOURS.toMillis(1))
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
            .setRequiresCharging(requireCharging)
            .setPersisted(true);

    if (!requireUnmetered) {
        if (allowRoaming) {
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        } else {
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NOT_ROAMING);
        }
    }

    return builder.build();
}
 
Example 8
Source File: GcmJobService.java    From ti.goosh with MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.O)
static void scheduleJob(Context context, Bundle extras) {
	ComponentName jobComponentName = new ComponentName(context.getPackageName(), GcmJobService.class.getName());
	JobScheduler mJobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
	JobInfo existingInfo = mJobScheduler.getPendingJob(JOB_ID);
	if (existingInfo != null) {
		mJobScheduler.cancel(JOB_ID);
	}

	JobInfo.Builder jobBuilder = new JobInfo.Builder(JOB_ID, jobComponentName)
			.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setTransientExtras(extras);
	int result = mJobScheduler.schedule(jobBuilder.build());
	if (result != JobScheduler.RESULT_SUCCESS) {
		Log.e(LCAT, "Could not start job, error code: " + result);
	}
}
 
Example 9
Source File: JobIntentService.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
JobWorkEnqueuer(Context context, ComponentName cn, int jobId) {
    super(cn);
    ensureJobId(jobId);
    JobInfo.Builder b = new JobInfo.Builder(jobId, mComponentName);
    mJobInfo = b.setOverrideDeadline(0).build();
    mJobScheduler = (JobScheduler) context.getApplicationContext().getSystemService(
            Context.JOB_SCHEDULER_SERVICE);
}
 
Example 10
Source File: FloatJobService.java    From RelaxFinger with GNU General Public License v2.0 5 votes vote down vote up
public static void scheduleService(Context context) {
    JobScheduler js = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, new ComponentName(context.getPackageName(), FloatJobService.class.getName()));
    builder.setPersisted(true);
    builder.setPeriodic(3 * 1000);
    js.cancel(JOB_ID);
    js.schedule(builder.build());
}
 
Example 11
Source File: VideosContentJob.java    From proofmode with GNU General Public License v3.0 5 votes vote down vote up
public static void scheduleJob(Context context) {
    JobScheduler js =
            (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    JobInfo.Builder builder = new JobInfo.Builder(
            VIDEO_JOB_ID,
            new ComponentName(context, VideosContentJob.class));
    builder.addTriggerContentUri(
            new JobInfo.TriggerContentUri(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
    js.schedule(builder.build());
}
 
Example 12
Source File: MinidumpUploadJobService.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Schedules uploading of all pending minidumps.
 * @param jobInfoBuilder A job info builder that has been initialized with any embedder-specific
 *     requriements. This builder will be extended to include shared requirements, and then used
 *     to build an upload job for scheduling.
 */
public static void scheduleUpload(JobInfo.Builder jobInfoBuilder) {
    Log.i(TAG, "Scheduling upload of all pending minidumps.");
    JobScheduler scheduler =
            (JobScheduler) ContextUtils.getApplicationContext().getSystemService(
                    Context.JOB_SCHEDULER_SERVICE);
    JobInfo uploadJob =
            jobInfoBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                    .setBackoffCriteria(JOB_INITIAL_BACKOFF_TIME_IN_MS, JOB_BACKOFF_POLICY)
                    .build();
    int result = scheduler.schedule(uploadJob);
    assert result == JobScheduler.RESULT_SUCCESS;
}
 
Example 13
Source File: JobProxy21.java    From android-job with Apache License 2.0 5 votes vote down vote up
protected JobInfo.Builder createBaseBuilder(JobRequest request, boolean allowPersisting) {
    JobInfo.Builder builder = new JobInfo.Builder(request.getJobId(), new ComponentName(mContext, PlatformJobService.class))
            .setRequiresCharging(request.requiresCharging())
            .setRequiresDeviceIdle(request.requiresDeviceIdle())
            .setRequiredNetworkType(convertNetworkType(request.requiredNetworkType()))
            .setPersisted(allowPersisting && !request.isTransient() && JobUtil.hasBootPermission(mContext));

    return setTransientBundle(request, builder);
}
 
Example 14
Source File: DaemonService.java    From AndroidKeepLivePractice with Apache License 2.0 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand(): intent = [" + intent.toUri(0) + "], flags = [" + flags + "], startId = [" + startId + "]");

    try {
        // 定时检查 WorkService 是否在运行,如果不在运行就把它拉起来
        // Android 5.0+ 使用 JobScheduler,效果比 AlarmManager 好
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Log.i(TAG, "开启 JobService 定时");
            JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
            jobScheduler.cancelAll();
            JobInfo.Builder builder = new JobInfo.Builder(1024, new ComponentName(getPackageName(), ScheduleService.class.getName()));
            builder.setPeriodic(WAKE_INTERVAL);
            builder.setPersisted(true);
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
            int schedule = jobScheduler.schedule(builder.build());
            if (schedule <= 0) {
                Log.w(TAG, "schedule error!");
            }
        } else {
            // Android 4.4- 使用 AlarmManager
            Log.i(TAG, "开启 AlarmManager 定时");
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            Intent alarmIntent = new Intent(getApplication(), DaemonService.class);
            PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1024, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            am.cancel(pendingIntent);
            am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + WAKE_INTERVAL, WAKE_INTERVAL, pendingIntent);
        }
    } catch (Exception e) {
        Log.e(TAG, "e:", e);
    }
    // 简单守护开机广播
    getPackageManager().setComponentEnabledSetting(
            new ComponentName(getPackageName(), DaemonService.class.getName()),
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    return super.onStartCommand(intent, flags, startId);
}
 
Example 15
Source File: BootReceiver.java    From ml-authentication with Apache License 2.0 5 votes vote down vote up
public static void scheduleFaceRecognitionTranining(Context context){
    ComponentName componentNameFaceRecognitionTranining = new ComponentName(context, FaceRecognitionTrainingJobService.class);
    JobInfo.Builder builderFaceRecognitionTranining = new JobInfo.Builder(LiteracyApplication.FACE_RECOGNITION_TRAINING_JOB_ID, componentNameFaceRecognitionTranining);
    int faceRecognitionTrainingPeriodic = MINUTES_BETWEEN_FACE_RECOGNITION_TRAININGS * 60 * 1000;
    builderFaceRecognitionTranining.setPeriodic(faceRecognitionTrainingPeriodic); // Every 15 minutes
    JobInfo faceRecognitionTrainingJobInfo = builderFaceRecognitionTranining.build();
    JobScheduler jobSchedulerFaceRecognitionTranining = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobSchedulerFaceRecognitionTranining.schedule(faceRecognitionTrainingJobInfo);
    Log.i(context.getClass().getName(), "FACE_RECOGNITION_TRAINING_JOB with ID " + LiteracyApplication.FACE_RECOGNITION_TRAINING_JOB_ID + " has been scheduled with periodic time = " + faceRecognitionTrainingPeriodic);
}
 
Example 16
Source File: NotificationScheduler.java    From Google-AAD-CheatSheet with MIT License 4 votes vote down vote up
public void scheduleJob(View v){
    RadioGroup networkOptions = findViewById(R.id.networkOptions);
    int selectedNetworkID=networkOptions.getCheckedRadioButtonId();
    int selectedNetworkOption=JobInfo.NETWORK_TYPE_NONE;
    switch(selectedNetworkID){
        case R.id.noNetwork:
            selectedNetworkOption = JobInfo.NETWORK_TYPE_NONE;
            break;
        case R.id.anyNetwork:
            selectedNetworkOption = JobInfo.NETWORK_TYPE_ANY;
            break;
        case R.id.wifiNetwork:
            selectedNetworkOption = JobInfo.NETWORK_TYPE_UNMETERED;
            break;
    }

    mScheduler=(JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);




    ComponentName serviceName = new ComponentName(getPackageName(),
            NotificationJobService.class.getName());
    JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, serviceName);
    builder.setRequiredNetworkType(selectedNetworkOption);
    builder.setRequiresDeviceIdle(mDeviceIdleSwitch.isChecked());
    builder.setRequiresCharging(mDeviceChargingSwitch.isChecked());
    int seekBarInteger = mSeekBar.getProgress();
    boolean seekBarSet = seekBarInteger > 0;
    if (seekBarSet) {
        builder.setOverrideDeadline(seekBarInteger * 1000);//过了ddl就不run你的job了
    }
    boolean constraintSet = (selectedNetworkOption != JobInfo.NETWORK_TYPE_NONE)
            || mDeviceChargingSwitch.isChecked() || mDeviceIdleSwitch.isChecked()|| seekBarSet;
    if(constraintSet) {
        //Schedule the job and notify the user
        JobInfo myJobInfo = builder.build();
        mScheduler.schedule(myJobInfo);
        Toast.makeText(this, "Job Scheduled, job will run when " +
                "the constraints are met.", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(this, "Please set at least one constraint",
                Toast.LENGTH_SHORT).show();
    }
}
 
Example 17
Source File: WebsocketDrainedConstraint.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
@RequiresApi(26)
@Override
public void applyToJobInfo(@NonNull JobInfo.Builder jobInfoBuilder) {
}
 
Example 18
Source File: NetworkConstraint.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
@RequiresApi(26)
@Override
public void applyToJobInfo(@NonNull JobInfo.Builder jobInfoBuilder) {
  jobInfoBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
}
 
Example 19
Source File: Constraint.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
@RequiresApi(26)
void applyToJobInfo(@NonNull JobInfo.Builder jobInfoBuilder);
 
Example 20
Source File: BGTask.java    From transistor-background-fetch with MIT License 4 votes vote down vote up
static void schedule(Context context, BackgroundFetchConfig config) {
    Log.d(BackgroundFetch.TAG, config.toString());

    long interval = (config.isFetchTask()) ? (TimeUnit.MINUTES.toMillis(config.getMinimumFetchInterval())) : config.getDelay();

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !config.getForceAlarmManager()) {
        // API 21+ uses new JobScheduler API

        JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo.Builder builder = new JobInfo.Builder(config.getJobId(), new ComponentName(context, FetchJobService.class))
                .setRequiredNetworkType(config.getRequiredNetworkType())
                .setRequiresDeviceIdle(config.getRequiresDeviceIdle())
                .setRequiresCharging(config.getRequiresCharging())
                .setPersisted(config.getStartOnBoot() && !config.getStopOnTerminate());

        if (config.getPeriodic()) {
            if (android.os.Build.VERSION.SDK_INT >= 24) {
                builder.setPeriodic(interval, interval);
            } else {
                builder.setPeriodic(interval);
            }
        } else {
            builder.setMinimumLatency(interval);
        }
        PersistableBundle extras = new PersistableBundle();
        extras.putString(BackgroundFetchConfig.FIELD_TASK_ID, config.getTaskId());
        builder.setExtras(extras);

        if (android.os.Build.VERSION.SDK_INT >= 26) {
            builder.setRequiresStorageNotLow(config.getRequiresStorageNotLow());
            builder.setRequiresBatteryNotLow(config.getRequiresBatteryNotLow());
        }
        if (jobScheduler != null) {
            jobScheduler.schedule(builder.build());
        }
    } else {
        // Everyone else get AlarmManager
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if (alarmManager != null) {
            PendingIntent pi = getAlarmPI(context, config.getTaskId());
            long delay = System.currentTimeMillis() + interval;
            if (config.getPeriodic()) {
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, delay, interval, pi);
            } else {
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, delay, pi);
                } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    alarmManager.setExact(AlarmManager.RTC_WAKEUP, delay, pi);
                } else {
                    alarmManager.set(AlarmManager.RTC_WAKEUP, delay, pi);
                }
            }
        }
    }
}