Most visited

Recently visited

Added in API level 21

JobInfo.Builder

public static final class JobInfo.Builder
extends Object

java.lang.Object
   ↳ android.app.job.JobInfo.Builder


用于构建 JobInfo对象的构建器类。

Summary

Public constructors

JobInfo.Builder(int jobId, ComponentName jobService)

初始化一个新的Builder来构建一个 JobInfo

Public methods

JobInfo.Builder addTriggerContentUri(JobInfo.TriggerContentUri uri)

添加一个新的内容:将使用 ContentObserver进行监控的 ContentObserver ,并且如果更改,将导致作业执行。

JobInfo build()
JobInfo.Builder setBackoffCriteria(long initialBackoffMillis, int backoffPolicy)

设置退避/重试策略。

JobInfo.Builder setExtras(PersistableBundle extras)

设置可选附加功能。

JobInfo.Builder setMinimumLatency(long minLatencyMillis)

指定该作业应该延迟所提供的时间量。

JobInfo.Builder setOverrideDeadline(long maxExecutionDelayMillis)

设置最大调度延迟的最后期限。

JobInfo.Builder setPeriodic(long intervalMillis)

指定该作业应该按照提供的时间间隔重复执行,每个时间段不得超过一次。

JobInfo.Builder setPeriodic(long intervalMillis, long flexMillis)

指定该作业应该按照提供的时间间隔和弹性进行重复。

JobInfo.Builder setPersisted(boolean isPersisted)

设置是否跨设备重新启动保留此作业。

JobInfo.Builder setRequiredNetworkType(int networkType)

设置你的工作需要的网络类型的一些描述。

JobInfo.Builder setRequiresCharging(boolean requiresCharging)

指定要运行此作业的设备需要插入。

JobInfo.Builder setRequiresDeviceIdle(boolean requiresDeviceIdle)

指定要运行的作业需要设备处于空闲模式。

JobInfo.Builder setTriggerContentMaxDelay(long durationMs)

设置从第一次检测到内容更改到计划作业时允许的最大总延迟(以毫秒为单位)。

JobInfo.Builder setTriggerContentUpdateDelay(long durationMs)

设置从检测到内容更改到计划作业的延迟(以毫秒为单位)。

Inherited methods

From class java.lang.Object

Public constructors

JobInfo.Builder

Added in API level 21
JobInfo.Builder (int jobId, 
                ComponentName jobService)

初始化一个新的Builder来构建一个 JobInfo

Parameters
jobId int: Application-provided id for this job. Subsequent calls to cancel, or jobs created with the same jobId, will update the pre-existing job with the same id. This ID must be unique across all clients of the same uid (not just the same package). You will want to make sure this is a stable id across app updates, so probably not based on a resource ID.
jobService ComponentName: The endpoint that you implement that will receive the callback from the JobScheduler.

Public methods

addTriggerContentUri

Added in API level 24
JobInfo.Builder addTriggerContentUri (JobInfo.TriggerContentUri uri)

添加一个新的内容:将用ContentObserver监视的ContentObserver ,并且如果更改,将导致作业执行。 如果您有与任务关联的任何触发器内容URI,那么它将不会执行,直到有一个或多个更改报告为止。

请注意,触发URI不能与setPeriodic(long)setPersisted(boolean)组合使用。 要持续监视内容更改,需要在完成JobService处理最近的更改之前安排新的JobInfo观察相同的URI。

因为由于设置该属性是不兼容的周期性或坚持工作,这样做会引发 IllegalArgumentExceptionbuild()被调用。

以下示例显示了此功能如何用于监视设备上照片的更改。

import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Example stub job to monitor when there is a change to photos in the media provider.
 */
public class PhotosContentJob extends JobService {
    // The root URI of the media provider, to monitor for generic changes to its content.
    static final Uri MEDIA_URI = Uri.parse("content://" + MediaStore.AUTHORITY + "/");

    // Path segments for image-specific URIs in the provider.
    static final List<String> EXTERNAL_PATH_SEGMENTS
            = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPathSegments();

    // The columns we want to retrieve about a particular image.
    static final String[] PROJECTION = new String[] {
            MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA
    };
    static final int PROJECTION_ID = 0;
    static final int PROJECTION_DATA = 1;

    // This is the external storage directory where cameras place pictures.
    static final String DCIM_DIR = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DCIM).getPath();

    // A pre-built JobInfo we use for scheduling our job.
    static final JobInfo JOB_INFO;

    static {
        JobInfo.Builder builder = new JobInfo.Builder(JobIds.PHOTOS_CONTENT_JOB,
                new ComponentName("com.example.android.apis", PhotosContentJob.class.getName()));
        // Look for specific changes to images in the provider.
        builder.addTriggerContentUri(new JobInfo.TriggerContentUri(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
        // Also look for general reports of changes in the overall provider.
        builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MEDIA_URI, 0));
        JOB_INFO = builder.build();
    }

    // Fake job work.  A real implementation would do some work on a separate thread.
    final Handler mHandler = new Handler();
    final Runnable mWorker = new Runnable() {
        @Override public void run() {
            scheduleJob(PhotosContentJob.this);
            jobFinished(mRunningParams, false);
        }
    };

    JobParameters mRunningParams;

    // Schedule this job, replace any existing one.
    public static void scheduleJob(Context context) {
        JobScheduler js = context.getSystemService(JobScheduler.class);
        js.schedule(JOB_INFO);
        Log.i("PhotosContentJob", "JOB SCHEDULED!");
    }

    // Check whether this job is currently scheduled.
    public static boolean isScheduled(Context context) {
        JobScheduler js = context.getSystemService(JobScheduler.class);
        List<JobInfo> jobs = js.getAllPendingJobs();
        if (jobs == null) {
            return false;
        }
        for (int i=0; i<jobs.size(); i++) {
            if (jobs.get(i).getId() == JobIds.PHOTOS_CONTENT_JOB) {
                return true;
            }
        }
        return false;
    }

    // Cancel this job, if currently scheduled.
    public static void cancelJob(Context context) {
        JobScheduler js = context.getSystemService(JobScheduler.class);
        js.cancel(JobIds.PHOTOS_CONTENT_JOB);
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.i("PhotosContentJob", "JOB STARTED!");
        mRunningParams = params;

        // Instead of real work, we are going to build a string to show to the user.
        StringBuilder sb = new StringBuilder();

        // Did we trigger due to a content change?
        if (params.getTriggeredContentAuthorities() != null) {
            boolean rescanNeeded = false;

            if (params.getTriggeredContentUris() != null) {
                // If we have details about which URIs changed, then iterate through them
                // and collect either the ids that were impacted or note that a generic
                // change has happened.
                ArrayList<String> ids = new ArrayList<>();
                for (Uri uri : params.getTriggeredContentUris()) {
                    List<String> path = uri.getPathSegments();
                    if (path != null && path.size() == EXTERNAL_PATH_SEGMENTS.size()+1) {
                        // This is a specific file.
                        ids.add(path.get(path.size()-1));
                    } else {
                        // Oops, there is some general change!
                        rescanNeeded = true;
                    }
                }

                if (ids.size() > 0) {
                    // If we found some ids that changed, we want to determine what they are.
                    // First, we do a query with content provider to ask about all of them.
                    StringBuilder selection = new StringBuilder();
                    for (int i=0; i<ids.size(); i++) {
                        if (selection.length() > 0) {
                            selection.append(" OR ");
                        }
                        selection.append(MediaStore.Images.ImageColumns._ID);
                        selection.append("='");
                        selection.append(ids.get(i));
                        selection.append("'");
                    }

                    // Now we iterate through the query, looking at the filenames of
                    // the items to determine if they are ones we are interested in.
                    Cursor cursor = null;
                    boolean haveFiles = false;
                    try {
                        cursor = getContentResolver().query(
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                PROJECTION, selection.toString(), null, null);
                        while (cursor.moveToNext()) {
                            // We only care about files in the DCIM directory.
                            String dir = cursor.getString(PROJECTION_DATA);
                            if (dir.startsWith(DCIM_DIR)) {
                                if (!haveFiles) {
                                    haveFiles = true;
                                    sb.append("New photos:\n");
                                }
                                sb.append(cursor.getInt(PROJECTION_ID));
                                sb.append(": ");
                                sb.append(dir);
                                sb.append("\n");
                            }
                        }
                    } catch (SecurityException e) {
                        sb.append("Error: no access to media!");
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }

            } else {
                // We don't have any details about URIs (because too many changed at once),
                // so just note that we need to do a full rescan.
                rescanNeeded = true;
            }

            if (rescanNeeded) {
                sb.append("Photos rescan needed!");
            }
        } else {
            sb.append("(No photos content)");
        }
        Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();

        // We will emulate taking some time to do this work, so we can see batching happen.
        mHandler.postDelayed(mWorker, 10*1000);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        mHandler.removeCallbacks(mWorker);
        return false;
    }
}

Parameters
uri JobInfo.TriggerContentUri: The content: URI to monitor.
Returns
JobInfo.Builder

build

Added in API level 21
JobInfo build ()

Returns
JobInfo The job object to hand to the JobScheduler. This object is immutable.

setBackoffCriteria

Added in API level 21
JobInfo.Builder setBackoffCriteria (long initialBackoffMillis, 
                int backoffPolicy)

设置退避/重试策略。 这默认值为一些值得尊敬的值:{30秒,Exponential}。 我们在5小时后退休。 请注意,尝试为setRequiresDeviceIdle(boolean)作业设置退避条件将在您调用build()时引发异常。 这是因为退款通常对这些类型的工作没有意义。 请参阅jobFinished(android.app.job.JobParameters, boolean)以获取有关在空闲模式下执行的作业的情况的返回值的更多说明。

Parameters
initialBackoffMillis long: Millisecond time interval to wait initially when job has failed.
backoffPolicy int: is one of BACKOFF_POLICY_LINEAR or BACKOFF_POLICY_EXPONENTIAL
Returns
JobInfo.Builder

setExtras

Added in API level 21
JobInfo.Builder setExtras (PersistableBundle extras)

设置可选附加功能。 这是持久的,所以我们只允许原始类型。

Parameters
extras PersistableBundle: Bundle containing extras you want the scheduler to hold on to for you.
Returns
JobInfo.Builder

setMinimumLatency

Added in API level 21
JobInfo.Builder setMinimumLatency (long minLatencyMillis)

指定该作业应该延迟所提供的时间量。 因为它没有任何意义上的周期性的作业设置该属性,这样做会引发IllegalArgumentExceptionbuild()被调用。

Parameters
minLatencyMillis long: Milliseconds before which this job will not be considered for execution.
Returns
JobInfo.Builder

setOverrideDeadline

Added in API level 21
JobInfo.Builder setOverrideDeadline (long maxExecutionDelayMillis)

设置最大调度延迟的最后期限。 即使未满足其他要求,工作也将在截止日期前完成。 因为它没有任何意义上的周期性的作业设置该属性,这样做会引发IllegalArgumentExceptionbuild()被调用。

Parameters
maxExecutionDelayMillis long
Returns
JobInfo.Builder

setPeriodic

Added in API level 21
JobInfo.Builder setPeriodic (long intervalMillis)

指定该作业应该按照提供的时间间隔重复执行,每个时间段不得超过一次。 您无法控制在此间隔内何时执行该作业,只能保证在此间隔内最多执行一次。 在构建器上使用setMinimumLatency(long)setOverrideDeadline(long)设置此功能将导致错误。

Parameters
intervalMillis long: Millisecond interval for which this job will repeat.
Returns
JobInfo.Builder

setPeriodic

Added in API level 24
JobInfo.Builder setPeriodic (long intervalMillis, 
                long flexMillis)

指定该作业应该按照提供的时间间隔和弹性进行重复。 该作业可以在任何时间在期末的弹性窗口中执行。

Parameters
intervalMillis long: Millisecond interval for which this job will repeat. A minimum value of getMinPeriodMillis() is enforced.
flexMillis long: Millisecond flex for this job. Flex is clamped to be at least getMinFlexMillis() or 5 percent of the period, whichever is higher.
Returns
JobInfo.Builder

setPersisted

Added in API level 21
JobInfo.Builder setPersisted (boolean isPersisted)

设置是否跨设备重新启动保留此作业。 如果您的应用程序拥有权限RECEIVE_BOOT_COMPLETED这只会RECEIVE_BOOT_COMPLETED 否则会抛出异常。

Parameters
isPersisted boolean: True to indicate that the job will be written to disk and loaded at boot.
Returns
JobInfo.Builder

setRequiredNetworkType

Added in API level 21
JobInfo.Builder setRequiredNetworkType (int networkType)

设置你的工作需要的网络类型的一些描述。 不调用此功能意味着网络不是必需的,因为默认值为NETWORK_TYPE_NONE 请记住,调用此函数将网络定义为您工作的严格要求。 如果请求的网络不可用,您的工作永远不会运行。 请参阅setOverrideDeadline(long)来更改此行为。

Parameters
networkType int
Returns
JobInfo.Builder

setRequiresCharging

Added in API level 21
JobInfo.Builder setRequiresCharging (boolean requiresCharging)

指定要运行此作业,需要插入该设备。默认设置为false。

Parameters
requiresCharging boolean: Whether or not the device is plugged in.
Returns
JobInfo.Builder

setRequiresDeviceIdle

Added in API level 21
JobInfo.Builder setRequiresDeviceIdle (boolean requiresDeviceIdle)

指定要运行的作业需要设备处于空闲模式。 这默认为false。

空闲模式是由系统提供的松散定义,这意味着设备未被使用,并且一段时间未被使用。 因此,现在是执行资源繁重工作的好时机。 请记住,电池使用量仍将归因于您的应用程序,并在电池状态中显示给用户。

Parameters
requiresDeviceIdle boolean: Whether or not the device need be within an idle maintenance window.
Returns
JobInfo.Builder

setTriggerContentMaxDelay

Added in API level 24
JobInfo.Builder setTriggerContentMaxDelay (long durationMs)

设置从第一次检测到内容更改到计划作业时允许的最大总延迟(以毫秒为单位)。

Parameters
durationMs long: Delay after initial content change, in milliseconds.
Returns
JobInfo.Builder

setTriggerContentUpdateDelay

Added in API level 24
JobInfo.Builder setTriggerContentUpdateDelay (long durationMs)

设置从检测到内容更改到计划作业的延迟(以毫秒为单位)。 如果在此期间有更多更改,延迟将被重置为在最近一次更改时开始。

Parameters
durationMs long: Delay after most recent content change, in milliseconds.
Returns
JobInfo.Builder

Hooray!