Java Code Examples for android.app.job.JobScheduler#RESULT_SUCCESS

The following examples show how to use android.app.job.JobScheduler#RESULT_SUCCESS . 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: ActivityHelper.java    From ActivityDiary with GNU General Public License v3.0 6 votes vote down vote up
public void scheduleRefresh() {
        int cycleTime;
        long delta = (new Date().getTime() - mCurrentActivityStartTime.getTime() + 500) / 1000;
        if(delta <= 15) {
            cycleTime = 1000 * 10;
        }else if(delta <= 45){
            cycleTime = 1000 * 20;
        }else if(delta <= 95){
            cycleTime = 1000 * 60;
        }else{
            cycleTime = 1000 * 60 * 5; /* 5 min for now. if we want we can make this time configurable in the settings */
        }
        ComponentName componentName = new ComponentName(ActivityDiaryApplication.getAppContext(), RefreshService.class);
        JobInfo.Builder builder = new JobInfo.Builder(ACTIVITY_HELPER_REFRESH_JOB, componentName);
        builder.setMinimumLatency(cycleTime);
        refreshJobInfo = builder.build();

        JobScheduler jobScheduler = (JobScheduler) ActivityDiaryApplication.getAppContext().getSystemService(JOB_SCHEDULER_SERVICE);
        int resultCode = jobScheduler.schedule(refreshJobInfo);
        if (resultCode != JobScheduler.RESULT_SUCCESS) {
            Log.w(TAG, "RefreshJob not scheduled");
        }
// TODO: do we need to keep track on the scheduled jobs, or is a waiting job with the same ID as a new one automatically canceled?
    }
 
Example 2
Source File: MobileMessagingJobService.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
private static void registerForNetworkAvailability(Context context) {
    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
    if (jobScheduler == null) {
        return;
    }

    int scheduleId = getScheduleId(context, ON_NETWORK_AVAILABLE_JOB_ID);

    jobScheduler.cancel(scheduleId);

    int r = jobScheduler.schedule(new JobInfo.Builder(scheduleId, new ComponentName(context, MobileMessagingJobService.class))
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .build());
    if (r == JobScheduler.RESULT_SUCCESS) {
        MobileMessagingLogger.d(TAG, "Registered job for connectivity updates");
    } else {
        MobileMessagingLogger.e(TAG, "Failed to register job for connectivity updates");
    }
}
 
Example 3
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 4
Source File: BackgroundDownloadService.java    From shortyz with GNU General Public License v3.0 6 votes vote down vote up
private static void scheduleJob(Context context) {
    JobScheduler scheduler =
            (JobScheduler)context.getSystemService(Context.JOB_SCHEDULER_SERVICE);

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

    JobInfo info = getJobInfo(
            preferences.getBoolean("backgroundDownloadRequireUnmetered", true),
            preferences.getBoolean("backgroundDownloadAllowRoaming", false),
            preferences.getBoolean("backgroundDownloadRequireCharging", false));


    LOGGER.info("Scheduling background download job: " + info);

    int result = scheduler.schedule(info);

    if (result == JobScheduler.RESULT_SUCCESS) {
        LOGGER.info("Successfully scheduled background downloads");
    } else {
        LOGGER.log(Level.WARNING, "Unable to schedule background downloads");
    }
}
 
Example 5
Source File: BackgroundTaskSchedulerJobService.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public boolean schedule(Context context, TaskInfo taskInfo) {
    ThreadUtils.assertOnUiThread();
    if (!BackgroundTaskScheduler.hasParameterlessPublicConstructor(
                taskInfo.getBackgroundTaskClass())) {
        Log.e(TAG, "BackgroundTask " + taskInfo.getBackgroundTaskClass()
                        + " has no parameterless public constructor.");
        return false;
    }

    JobInfo jobInfo = createJobInfoFromTaskInfo(context, taskInfo);

    JobScheduler jobScheduler =
            (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);

    if (taskInfo.shouldUpdateCurrent()) {
        jobScheduler.cancel(taskInfo.getTaskId());
    }

    int result = jobScheduler.schedule(jobInfo);
    return result == JobScheduler.RESULT_SUCCESS;
}
 
Example 6
Source File: PlatformScheduler.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
  JobInfo jobInfo =
      buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
  int result = jobScheduler.schedule(jobInfo);
  logd("Scheduling job: " + jobId + " result: " + result);
  return result == JobScheduler.RESULT_SUCCESS;
}
 
Example 7
Source File: PlatformScheduler.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
  JobInfo jobInfo =
      buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
  int result = jobScheduler.schedule(jobInfo);
  logd("Scheduling job: " + jobId + " result: " + result);
  return result == JobScheduler.RESULT_SUCCESS;
}
 
Example 8
Source File: PlatformScheduler.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
  JobInfo jobInfo =
      buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
  int result = jobScheduler.schedule(jobInfo);
  logd("Scheduling job: " + jobId + " result: " + result);
  return result == JobScheduler.RESULT_SUCCESS;
}
 
Example 9
Source File: PlatformScheduler.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
  JobInfo jobInfo =
      buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
  int result = jobScheduler.schedule(jobInfo);
  logd("Scheduling job: " + jobId + " result: " + result);
  return result == JobScheduler.RESULT_SUCCESS;
}
 
Example 10
Source File: PlatformScheduler.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean schedule(Requirements requirements, String servicePackage, String serviceAction) {
  JobInfo jobInfo =
      buildJobInfo(jobId, jobServiceComponentName, requirements, serviceAction, servicePackage);
  int result = jobScheduler.schedule(jobInfo);
  logd("Scheduling job: " + jobId + " result: " + result);
  return result == JobScheduler.RESULT_SUCCESS;
}
 
Example 11
Source File: JobSchedulerService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
        int userId, String tag) {
    try {
        if (ActivityManager.getService().isAppStartModeDisabled(uId,
                job.getService().getPackageName())) {
            Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
                    + " -- package not allowed to start");
            return JobScheduler.RESULT_FAILURE;
        }
    } catch (RemoteException e) {
    }

    synchronized (mLock) {
        final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());

        if (work != null && toCancel != null) {
            // Fast path: we are adding work to an existing job, and the JobInfo is not
            // changing.  We can just directly enqueue this work in to the job.
            if (toCancel.getJob().equals(job)) {

                toCancel.enqueueWorkLocked(ActivityManager.getService(), work);

                // If any of work item is enqueued when the source is in the foreground,
                // exempt the entire job.
                toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);

                return JobScheduler.RESULT_SUCCESS;
            }
        }

        JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);

        // Give exemption if the source is in the foreground just now.
        // Note if it's a sync job, this method is called on the handler so it's not exactly
        // the state when requestSync() was called, but that should be fine because of the
        // 1 minute foreground grace period.
        jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);

        if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
        // Jobs on behalf of others don't apply to the per-app job cap
        if (ENFORCE_MAX_JOBS && packageName == null) {
            if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
                Slog.w(TAG, "Too many jobs for uid " + uId);
                throw new IllegalStateException("Apps may not schedule more than "
                            + MAX_JOBS_PER_APP + " distinct jobs");
            }
        }

        // This may throw a SecurityException.
        jobStatus.prepareLocked(ActivityManager.getService());

        if (work != null) {
            // If work has been supplied, enqueue it into the new job.
            jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
        }

        if (toCancel != null) {
            // Implicitly replaces the existing job record with the new instance
            cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
        } else {
            startTrackingJobLocked(jobStatus, null);
        }
        StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
                uId, null, jobStatus.getBatteryName(),
                StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED,
                JobProtoEnums.STOP_REASON_CANCELLED);

        // If the job is immediately ready to run, then we can just immediately
        // put it in the pending list and try to schedule it.  This is especially
        // important for jobs with a 0 deadline constraint, since they will happen a fair
        // amount, we want to handle them as quickly as possible, and semantically we want to
        // make sure we have started holding the wake lock for the job before returning to
        // the caller.
        // If the job is not yet ready to run, there is nothing more to do -- we are
        // now just waiting for one of its controllers to change state and schedule
        // the job appropriately.
        if (isReadyToBeExecutedLocked(jobStatus)) {
            // This is a new job, we can just immediately put it on the pending
            // list and try to run it.
            mJobPackageTracker.notePending(jobStatus);
            addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
            maybeRunPendingJobsLocked();
        }
    }
    return JobScheduler.RESULT_SUCCESS;
}
 
Example 12
Source File: JobSchedulerSchedulerV21.java    From JobSchedulerCompat with MIT License 4 votes vote down vote up
@Override
public int schedule(JobInfo job) {
    int result = jobScheduler.schedule(toPlatformJob(job).build());
    return result == JobScheduler.RESULT_SUCCESS ? RESULT_SUCCESS : RESULT_FAILURE;
}
 
Example 13
Source File: JobProxy21.java    From android-job with Apache License 2.0 4 votes vote down vote up
protected static String scheduleResultToString(int scheduleResult) {
    return scheduleResult == JobScheduler.RESULT_SUCCESS ? "success" : "failure";
}