Java 类android.app.job.JobScheduler 实例源码

项目:androidbeginners-Lesson3    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Create JobScheduler
    JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

    //Create a component passing the JobService that we want to use
    ComponentName jobService =  new ComponentName(getPackageName(), MyJobService.class.getName());

    //Create a JobInfo passing a unique JOB_ID and the jobService
    //also set the periodic time to repeat this job
    JobInfo jobInfo =  new JobInfo.Builder(JOB_ID, jobService)
            .setPeriodic(REFRESH_INTERVAL)
            .build();

    jobScheduler.schedule(jobInfo);

}
项目:Udhari    文件:SettingsActivity.java   
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    final String remindersKey = getString(R.string.pref_key_reminders);
    if (key.equals(remindersKey)) {
        boolean enabled = sharedPreferences.getBoolean(remindersKey, false);
        JobScheduler jobScheduler =
                (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

        if (!enabled) {
            jobScheduler.cancel(JOB_ID);
            Log.d(TAG, "cancelling scheduled job");
        } else {
            long interval = AlarmManager.INTERVAL_HOUR;
            JobInfo job = new JobInfo.Builder(JOB_ID,
                    new ComponentName(getPackageName(),
                            ScheduledJobService.class.getName()))
                    .setPersisted(true)
                    .setPeriodic(interval)
                    .build();
            jobScheduler.schedule(job);
            Log.d(TAG, "setting scheduled job for: " + interval);
        }
    }
}
项目:MiPushFramework    文件:PushController.java   
/**
 * Set XMPush sdk enable
 * @param enable enable
 * @param context context param
 */
public static void setServiceEnable (boolean enable, Context context) {
    if (enable && isAppMainProc(context)) {
        MiPushClient.registerPush(wrapContext(context), APP_ID, APP_KEY);
    } else {
        MiPushClient.unregisterPush(wrapContext(context));
        // Force stop and disable services.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
            scheduler.cancelAll();
        }
        context.stopService(new Intent(context, XMPushService.class));
    }
}
项目:nifi-android-s2s    文件:SiteToSiteJobServiceTest.java   
@Test(timeout = 5000)
public void testProcessOnePacket() throws Exception {
    DataPacket dataPacket = new ByteArrayDataPacket(Collections.singletonMap("id", "testId"), "testPayload".getBytes(Charsets.UTF_8));
    queuedSiteToSiteClientConfig.createQueuedClient(context).enqueue(dataPacket);

    mockNiFiS2SServer.enqueueSiteToSitePeers(Collections.singletonList(peer));
    String transactionPath = mockNiFiS2SServer.enqueuCreateTransaction(portIdentifier, transactionIdentifier, 30);
    mockNiFiS2SServer.enqueuDataPackets(transactionPath, Collections.singletonList(dataPacket), queuedSiteToSiteClientConfig);
    mockNiFiS2SServer.enqueueTransactionComplete(transactionPath, 2, ResponseCode.CONFIRM_TRANSACTION, ResponseCode.CONFIRM_TRANSACTION);

    JobInfo.Builder processJobInfoBuilder = SiteToSiteJobService.createProcessJobInfoBuilder(context, 1, queuedSiteToSiteClientConfig, parcelableQueuedOperationResultCallback);
    processJobInfoBuilder.setOverrideDeadline(0);
    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    assertEquals(JobScheduler.RESULT_SUCCESS, jobScheduler.schedule(processJobInfoBuilder.build()));
    assertEquals(1, parcelableQueuedOperationResultCallback.getInvocations().size());
    SiteToSiteDBTestUtil.assertNoQueuedPackets(siteToSiteDB);
    mockNiFiS2SServer.verifyAssertions();
}
项目:androidtv-sample    文件:RichBootReceiver.java   
@Override
public void onReceive(Context context, Intent intent) {
    JobScheduler jobScheduler =
            (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    // If there are not pending jobs. Create a sync job and schedule it.
    List<JobInfo> pendingJobs = jobScheduler.getAllPendingJobs();
    if (pendingJobs.isEmpty()) {
        String inputId = context.getSharedPreferences(SyncJobService.PREFERENCE_EPG_SYNC,
                Context.MODE_PRIVATE).getString(SyncJobService.BUNDLE_KEY_INPUT_ID, null);
        if (inputId != null) {
            // Set up periodic sync only when input has set up.
            SyncUtils.setUpPeriodicSync(context, inputId);
        }
        return;
    }
    // On L/L-MR1, reschedule the pending jobs.
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
        for (JobInfo job : pendingJobs) {
            if (job.isPersisted()) {
                jobScheduler.schedule(job);
            }
        }
    }
}
项目:leanback-homescreen-channels    文件:AddWatchNextService.java   
public static void scheduleAddWatchNextRequest(Context context, ClipData clipData) {
    JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);

    PersistableBundle bundle = new PersistableBundle();
    bundle.putString(ID_KEY, clipData.getClipId());
    bundle.putString(CONTENT_ID_KEY, clipData.getContentId());
    bundle.putLong(DURATION_KEY, clipData.getDuration());
    bundle.putLong(PROGRESS_KEY, clipData.getProgress());
    bundle.putString(TITLE_KEY, clipData.getTitle());
    bundle.putString(DESCRIPTION_KEY, clipData.getDescription());
    bundle.putString(CARD_IMAGE_URL_KEY, clipData.getCardImageUrl());

    scheduler.schedule(new JobInfo.Builder(1,
            new ComponentName(context, AddWatchNextService.class))
            .setMinimumLatency(0)
            .setExtras(bundle)
            .build());
}
项目:QuickPeriodicJobScheduler    文件:InstrumentedTests.java   
@Test
public void testStart() {
    Context context = InstrumentationRegistry.getTargetContext();
    QuickPeriodicJobScheduler qpjs = new QuickPeriodicJobScheduler(context);
    qpjs.start(2, 30000l);

    SystemClock.sleep(1000);

    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    List<JobInfo> jobInfoList = jobScheduler.getAllPendingJobs();
    JobInfo jobInfo = null;
    for(JobInfo job : jobInfoList) {
        if(job.getId() == 2) {
            jobInfo = job;
        }
    }

    Assert.assertEquals(jobInfo.getMaxExecutionDelayMillis(), 30000l);
    Assert.assertEquals(jobInfo.getMinLatencyMillis(), 30000l);
    Assert.assertEquals(jobInfo.getId(), 2);
    Assert.assertEquals(jobInfo.getExtras().getLong("interval"), 30000l);
    Assert.assertNotNull(jobInfo);
}
项目:SimpleRssReader    文件:PeriodicJob.java   
@SuppressWarnings("ConstantConditions")
public static void schedule(final Context context) {
    final JobScheduler scheduler = context.getSystemService(JobScheduler.class);

    for (final JobInfo job : scheduler.getAllPendingJobs()) {
        if (job.getId() == JOB_ID_PERIODIC) {
            return;
        }
    }

    final long interval = MINUTE *
            Integer.valueOf(DefaultSharedPrefUtils.getBackgroundServiceInterval(context));

    final ComponentName name = new ComponentName(context, PeriodicJob.class);

    final int result = scheduler.schedule(new JobInfo.Builder(JOB_ID_PERIODIC, name)
            .setPeriodic(interval)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .build());

    if (result != JobScheduler.RESULT_SUCCESS) {
        Log.e(TAG, "Failed to schedule periodic job");
    }
}
项目:intra42    文件:NotificationsJobService.java   
public static void schedule(Context context) {

        SharedPreferences settings = AppSettings.getSharedPreferences(context);
        int notificationsFrequency = AppSettings.Notifications.getNotificationsFrequency(settings);

        ComponentName component = new ComponentName(context, NotificationsJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, component)
                .setPeriodic(60000 * notificationsFrequency);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NOT_ROAMING);
        else
            builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);

        JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(builder.build());
    }
项目:LatestDiscounts    文件:PollJobService.java   
@TargetApi(21)
public static void startPolling(Context context) {
    JobScheduler scheduler = (JobScheduler)
            context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    final int JOB_ID = 1;

    if (isBeenScheduled(JOB_ID, context)){
        Log.i(TAG, "scheduler.cancel(JOB_ID)");
        scheduler.cancel(JOB_ID);
    } else{
        Log.i(TAG, "scheduler.schedule(jobInfo)");
        int pollInterval = QueryPreferences.getPollInterval(context);
        Log.i(TAG, "the poll interval is: " + pollInterval + " ms");
        JobInfo jobInfo = new JobInfo.Builder(
                JOB_ID, new ComponentName(context, PollJobService.class))
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                .setPeriodic(pollInterval)
                .setPersisted(true)
                .build();
        scheduler.schedule(jobInfo);
    }
}
项目:Asynchronous-Android-Programming    文件:JobListActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.job_list_activity);
    RecyclerView rv = (RecyclerView)findViewById(R.id.jobList);

    // Set the recycler view layout
    LinearLayoutManager llm = new LinearLayoutManager(this);
    rv.setLayoutManager(llm);

    initList();

    Button cancelAllBut = (Button)findViewById(R.id.cancelAllBut);
    cancelAllBut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            JobScheduler jobScheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
            jobScheduler.cancelAll();
            initList();
            Toast.makeText(JobListActivity.this,
                    "Cancelling all the pending jobs",
                    Toast.LENGTH_LONG).show();
        }
    });
}
项目:Asynchronous-Android-Programming    文件:JobListRecyclerAdapter.java   
@Override
public void onBindViewHolder(JobListRecyclerAdapter.JobViewHolder holder, int position) {

    final JobInfo ji= mJobList.get(position);
    holder.jobId.setText(Integer.toString(ji.getId()));
    holder.serviceName.setText(ji.getService().getClassName());
    holder.stopBut.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            JobScheduler jobScheduler = (JobScheduler)mContext.getSystemService(mContext.JOB_SCHEDULER_SERVICE);
            jobScheduler.cancel(ji.getId());
            Log.i("JobList", "Stopping the job "+ji.getId());
            Toast.makeText(mContext,
                    "Canceling the job "+ji.getId(),
                    Toast.LENGTH_LONG).show();
            mContext.initList();
        }
    });
}
项目:stockhawk    文件:QuoteSyncJob.java   
private static void schedulePeriodic(Context context) {
    Timber.d("Scheduling a periodic task");

    JobInfo.Builder builder = new JobInfo.Builder(
            PERIODIC_ID, new ComponentName(context, QuoteJobService.class));


    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .setPeriodic(PERIOD)
            .setBackoffCriteria(INITIAL_BACKOFF, JobInfo.BACKOFF_POLICY_EXPONENTIAL);


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

    int result = scheduler.schedule(builder.build());
    if (result == JobScheduler.RESULT_SUCCESS) {
        Timber.i("Job scheduled successfully!");
    } else {
        Timber.e("Job did not scheduled!");
    }

}
项目:qiscus-sdk-android    文件:QiscusSyncJobService.java   
private void syncJob() {
    QiscusAccount qiscusAccount = Qiscus.getQiscusAccount();

    Random rand = new Random();
    int randomValue = rand.nextInt(50);

    JobInfo jobInfo = new JobInfo.Builder(qiscusAccount.getId() + randomValue, componentName)
            .setPeriodic(TimeUnit.MINUTES.toMillis(15))
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .build();

    JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    if (jobScheduler != null) {
        jobScheduler.schedule(jobInfo);
    }

}
项目:mobile-messaging-sdk-android    文件:MobileMessagingJobService.java   
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");
    }
}
项目:authentication    文件:BootReceiver.java   
@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);
    }
项目:materialistic    文件:ItemSyncJobServiceTest.java   
@Test
public void testScheduledJob() {
    PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application)
            .edit()
            .putBoolean(RuntimeEnvironment.application.getString(R.string.pref_saved_item_sync), true)
            .apply();
    shadowOf((ConnectivityManager) RuntimeEnvironment.application
            .getSystemService(Context.CONNECTIVITY_SERVICE))
            .setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null,
                    ConnectivityManager.TYPE_WIFI, 0, true, true));
    new SyncScheduler().scheduleSync(RuntimeEnvironment.application, "1");
    List<JobInfo> pendingJobs = shadowOf((JobScheduler) RuntimeEnvironment.application
            .getSystemService(Context.JOB_SCHEDULER_SERVICE)).getAllPendingJobs();
    assertThat(pendingJobs).isNotEmpty();
    JobInfo actual = pendingJobs.get(0);
    assertThat(actual.getService().getClassName())
            .isEqualTo(ItemSyncJobService.class.getName());
}
项目:geohashdroid    文件:AlarmService.java   
private void waitForNetwork() {
    // SDK check!  We'll go with JobScheduler if we can.
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // JobScheduler time!  It's fancier!
        JobScheduler js = (JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo job = new JobInfo.Builder(
                ALARM_CONNECTIVITY_JOB,
                new ComponentName(this, AlarmServiceJobService.class))
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .build();
        js.schedule(job);
    } else {
        // Otherwise, just use the ol' package component.
        AndroidUtil.setPackageComponentEnabled(this, NetworkReceiver.class, true);
    }
}
项目:geohashdroid    文件:WikiService.java   
private void showWaitingForConnectionNotification() {
    Notification.Builder builder = getFreshNotificationBuilder()
            .setOngoing(true)
            .setContentTitle(getString(R.string.wiki_notification_waiting_for_connection_title))
            .setContentText(getString(R.string.wiki_notification_waiting_for_connection_content))
            .setSmallIcon(R.drawable.ic_stat_navigation_more_horiz)
            .setContentIntent(getBasicCommandIntent(QueueService.COMMAND_RESUME));

    mNotificationManager.notify(R.id.wiki_waiting_notification, builder.build());

    // If we have JobScheduler (SDK 21 or higher), use that.  Otherwise, go
    // with the old ConnectivityListener style.
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        JobScheduler js = (JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo job = new JobInfo.Builder(
                WIKI_CONNECTIVITY_JOB,
                new ComponentName(this, WikiServiceJobService.class))
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .build();
        js.schedule(job);
    } else {
        // Make sure the connectivity listener's waiting for a connection.
        AndroidUtil.setPackageComponentEnabled(this, WikiServiceConnectivityListener.class, true);
    }
}
项目:klingon-assistant    文件:BaseActivity.java   
@Override
protected void onResume() {
  super.onResume();

  // Change locale to Klingon if Klingon UI option is set.
  updateLocaleConfiguration();

  // Schedule the KWOTD service if it hasn't already been started. It's necessary to do this here
  // because the setting might have changed in Preferences.
  SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
  if (sharedPrefs.getBoolean(Preferences.KEY_KWOTD_CHECKBOX_PREFERENCE, /* default */ true)) {
    runKwotdServiceJob(/* isOneOffJob */ false);
  } else {
    // If the preference is unchecked, cancel the persisted job.
    JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    scheduler.cancel(KWOTD_SERVICE_PERSISTED_JOB_ID);
  }
}
项目:shortyz    文件:BackgroundDownloadService.java   
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");
    }
}
项目:android-job    文件:JobRescheduleTest.java   
@Test
@Config(sdk = Build.VERSION_CODES.LOLLIPOP_MR1)
public void verifyPeriodicJobRescheduled() throws Exception {
    assertThat(manager().getAllJobRequests()).isEmpty();

    ContentValues contentValues = new JobRequest.Builder("tag")
            .setPeriodic(TimeUnit.HOURS.toMillis(1))
            .build()
            .toContentValues();

    manager().getJobStorage().getDatabase()
            .insert(JobStorage.JOB_TABLE_NAME, null, contentValues);

    Set<JobRequest> requests = manager().getAllJobRequests();
    assertThat(requests).isNotEmpty();

    JobScheduler scheduler = (JobScheduler) context().getSystemService(Context.JOB_SCHEDULER_SERVICE);
    assertThat(scheduler.getAllPendingJobs()).isEmpty();

    int rescheduledJobs = new JobRescheduleService().rescheduleJobs(manager());
    assertThat(rescheduledJobs).isEqualTo(1);
}
项目:365browser    文件:BackgroundTaskSchedulerJobService.java   
@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;
}
项目:NasaPic    文件:PeriodicWallpaperChangeService.java   
public static void setupIfNeededPeriodicWallpaperChange(Context context) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        Resources res = context.getResources();
        JobScheduler scheduler = (JobScheduler) context
                .getSystemService(Context.JOB_SCHEDULER_SERVICE);

        if (scheduler.getAllPendingJobs().size() == 0) {
            ComponentName serviceEndpoint = new ComponentName(context,
                    PeriodicWallpaperChangeService.class);
            JobInfo wallpaperChangeJob = new JobInfo.Builder(
                    PeriodicWallpaperChangeService.JOB_ID, serviceEndpoint)
                    .setRequiresCharging(false)
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                    .setPersisted(true)
                    .setRequiresDeviceIdle(true)
                    .setPeriodic(PERIOD_IN_HOURS * 60 * 60 * 1000)
                    .build();

            scheduler.schedule(wallpaperChangeJob);
            String scheduledMessage = res.getString(R.string.periodic_change_scheduled);
            Toast.makeText(context, scheduledMessage, Toast.LENGTH_SHORT).show();
        }
    }
}
项目:androidtv-sample-inputs    文件:RichBootReceiver.java   
@Override
public void onReceive(Context context, Intent intent) {
    JobScheduler jobScheduler =
            (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    // If there are not pending jobs. Create a sync job and schedule it.
    List<JobInfo> pendingJobs = jobScheduler.getAllPendingJobs();
    if (pendingJobs.isEmpty()) {
        String inputId = context.getSharedPreferences(EpgSyncJobService.PREFERENCE_EPG_SYNC,
                Context.MODE_PRIVATE).getString(EpgSyncJobService.BUNDLE_KEY_INPUT_ID, null);
        if (inputId != null) {
            // Set up periodic sync only when input has set up.
            EpgSyncJobService.setUpPeriodicSync(context, inputId,
                    new ComponentName(context, SampleJobService.class));
        }
        return;
    }
    // On L/L-MR1, reschedule the pending jobs.
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
        for (JobInfo job : pendingJobs) {
            if (job.isPersisted()) {
                jobScheduler.schedule(job);
            }
        }
    }
}
项目:muzei    文件:TaskQueueService.java   
private void scheduleRetryArtworkDownload() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(new JobInfo.Builder(LOAD_ARTWORK_JOB_ID,
                new ComponentName(this, DownloadArtworkJobService.class))
                .setRequiredNetworkType(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                        ? JobInfo.NETWORK_TYPE_NOT_ROAMING
                        : JobInfo.NETWORK_TYPE_ANY)
                .build());
    } else {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        int reloadAttempt = sp.getInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, 0);
        sp.edit().putInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, reloadAttempt + 1).apply();
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        long retryTimeMillis = SystemClock.elapsedRealtime() + (1 << reloadAttempt) * 2000;
        am.set(AlarmManager.ELAPSED_REALTIME, retryTimeMillis,
                TaskQueueService.getArtworkDownloadRetryPendingIntent(this));
    }
}
项目:muzei    文件:TaskQueueService.java   
public static Intent maybeRetryDownloadDueToGainedConnectivity(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        List<JobInfo> pendingJobs = jobScheduler.getAllPendingJobs();
        for (JobInfo pendingJob : pendingJobs) {
            if (pendingJob.getId() == LOAD_ARTWORK_JOB_ID) {
                return TaskQueueService.getDownloadCurrentArtworkIntent(context);
            }
        }
        return null;
    }
    return (PreferenceManager.getDefaultSharedPreferences(context)
            .getInt(PREF_ARTWORK_DOWNLOAD_ATTEMPT, 0) > 0)
            ? TaskQueueService.getDownloadCurrentArtworkIntent(context)
            : null;
}
项目:muzei    文件:ArtworkComplicationJobService.java   
static void scheduleComplicationUpdateJob(Context context) {
    JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
    ComponentName componentName = new ComponentName(context, ArtworkComplicationJobService.class);
    int result = jobScheduler.schedule(new JobInfo.Builder(ARTWORK_COMPLICATION_JOB_ID, componentName)
            .addTriggerContentUri(new JobInfo.TriggerContentUri(
                    MuzeiContract.Artwork.CONTENT_URI,
                    JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS))
            .build());
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "Job scheduled with " + (result == JobScheduler.RESULT_SUCCESS ? "success" : "failure"));
    }
    // Enable the BOOT_COMPLETED receiver to reschedule the job on reboot
    ComponentName bootReceivedComponentName = new ComponentName(context,
            ArtworkComplicationBootReceiver.class);
    context.getPackageManager().setComponentEnabledSetting(bootReceivedComponentName,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
项目:codeexamples-android    文件:MainActivity.java   
/**
 * UI onclick listener to schedule a new job. 
 */
public void scheduleJob(View v) {
    JobInfo.Builder builder = new JobInfo.Builder(kJobId++,mServiceComponent);
    String delay = mDelayEditText.getText().toString();
    if (delay != null && !TextUtils.isEmpty(delay)) {
        builder.setMinimumLatency(Long.valueOf(delay) * 1000);
    }
    String deadline = mDeadlineEditText.getText().toString();
    if (deadline != null && !TextUtils.isEmpty(deadline)) {
        builder.setOverrideDeadline(Long.valueOf(deadline) * 1000);
    }
    boolean requiresUnmetered = mWiFiConnectivityRadioButton.isChecked();
    boolean requiresAnyConnectivity = mAnyConnectivityRadioButton
            .isChecked();
    if (requiresUnmetered) {
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
    } else if (requiresAnyConnectivity) {
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
    }
    builder.setRequiresDeviceIdle(mRequiresIdleCheckbox.isChecked());
    builder.setRequiresCharging(mRequiresChargingCheckBox.isChecked());
    JobScheduler jobScheduler =
            (JobScheduler) getApplication().getSystemService(Context.JOB_SCHEDULER_SERVICE);

    jobScheduler.schedule(builder.build());
}
项目:GitHub    文件:WatchDogService.java   
/**
 * 用于在不需要服务运行的时候取消 Job / Alarm / Subscription.
 *
 * 因 WatchDogService 运行在 :watch 子进程, 请勿在主进程中直接调用此方法.
 * 而是向 WakeUpReceiver 发送一个 Action 为 WakeUpReceiver.ACTION_CANCEL_JOB_ALARM_SUB 的广播.
 */
public static void cancelJobAlarmSub() {
    if (!DaemonEnv.sInitialized) return;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        JobScheduler scheduler = (JobScheduler) DaemonEnv.sApp.getSystemService(JOB_SCHEDULER_SERVICE);
        scheduler.cancel(HASH_CODE);
    } else {
        AlarmManager am = (AlarmManager) DaemonEnv.sApp.getSystemService(ALARM_SERVICE);
        if (sPendingIntent != null) am.cancel(sPendingIntent);
    }
    if (sDisposable != null) sDisposable.dispose();
}
项目:JobSchedulerCompat    文件:JobSchedulerSchedulerTest.java   
@Before
public void setup() {
    context = RuntimeEnvironment.application;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        scheduler = new JobSchedulerSchedulerV26(context);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        scheduler = new JobSchedulerSchedulerV24(context);
    } else {
        scheduler = new JobSchedulerSchedulerV21(context);
    }
    jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
}
项目:LaunchEnr    文件:ExtractionUtils.java   
/** Starts the {@link ColorExtractionService} without checking the wallpaper id */
static void startColorExtractionService(Context context) {
    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(
            Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(new JobInfo.Builder(Utilities.COLOR_EXTRACTION_JOB_ID,
            new ComponentName(context, ColorExtractionService.class))
            .setMinimumLatency(0).build());
}
项目:AndroidKeepLivePractice    文件:DaemonService.java   
@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);
}
项目:nifi-android-s2s    文件:MainActivity.java   
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void jobSchedule(View view) {
    JobInfo.Builder processJobInfoBuilder = SiteToSiteJobService.createProcessJobInfoBuilder(getApplicationContext(), 1234, siteToSiteClientConfig, new JobSchedulerCallback());
    processJobInfoBuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
    processJobInfoBuilder.setRequiresCharging(true);
    JobScheduler jobScheduler = (JobScheduler) getApplicationContext().getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(processJobInfoBuilder.build());
}
项目:nifi-android-s2s    文件:SiteToSiteJobServiceTest.java   
@Test(timeout = 5000)
public void testProcessNoPackets() throws PendingIntent.CanceledException, InterruptedException {
    JobInfo.Builder processJobInfoBuilder = SiteToSiteJobService.createProcessJobInfoBuilder(context, 1, queuedSiteToSiteClientConfig, parcelableQueuedOperationResultCallback);
    processJobInfoBuilder.setOverrideDeadline(0);
    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    assertEquals(JobScheduler.RESULT_SUCCESS, jobScheduler.schedule(processJobInfoBuilder.build()));
    assertEquals(1, parcelableQueuedOperationResultCallback.getInvocations().size());
    SiteToSiteDBTestUtil.assertNoQueuedPackets(siteToSiteDB);
}
项目:nifi-android-s2s    文件:SiteToSiteJobServiceTest.java   
@Test(timeout = 25000)
public void testProcessAThousandPackets() throws Exception {
    int numPackets = 1000;
    List<DataPacket> dataPackets = new ArrayList<>(numPackets);
    for (int i = 0; i < numPackets; i++) {
        dataPackets.add(new ByteArrayDataPacket(Collections.singletonMap("id", "testId" + i), ("testPayload" + i).getBytes(Charsets.UTF_8)));
    }
    queuedSiteToSiteClientConfig.createQueuedClient(context).enqueue(dataPackets.iterator());
    SiteToSiteDBTestUtil.assertQueuedPacketCount(siteToSiteDB, numPackets);

    Collections.reverse(dataPackets);
    mockNiFiS2SServer.enqueueSiteToSitePeers(Collections.singletonList(peer));

    for (int i = 0; i < numPackets; i+= 100) {
        String transactionPath = mockNiFiS2SServer.enqueuCreateTransaction(portIdentifier, transactionIdentifier, 30);
        mockNiFiS2SServer.enqueuDataPackets(transactionPath, dataPackets.subList(i, i + 100), queuedSiteToSiteClientConfig);
        mockNiFiS2SServer.enqueueTransactionComplete(transactionPath, 2, ResponseCode.CONFIRM_TRANSACTION, ResponseCode.CONFIRM_TRANSACTION);
    }

    JobInfo.Builder processJobInfoBuilder = SiteToSiteJobService.createProcessJobInfoBuilder(context, 3, queuedSiteToSiteClientConfig, parcelableQueuedOperationResultCallback);
    processJobInfoBuilder.setOverrideDeadline(0);
    JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
    assertEquals(JobScheduler.RESULT_SUCCESS, jobScheduler.schedule(processJobInfoBuilder.build()));
    assertEquals(1, parcelableQueuedOperationResultCallback.getInvocations().size());
    SiteToSiteDBTestUtil.assertNoQueuedPackets(siteToSiteDB);
    mockNiFiS2SServer.verifyAssertions();
}
项目:AndroidRepositoryWithOfflineMode    文件:RepositoryApplication.java   
@Override
public void onCreate() {
    super.onCreate();

    dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
    }

    Realm.init(this);
    RealmConfiguration config = new RealmConfiguration.Builder().build();
    Realm.setDefaultConfiguration(config);
}
项目:FreshMember    文件:MyService.java   
public void startJobSheduler() {
    try {
        JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(getPackageName(), MyService.class.getName()));
        builder.setPeriodic(5);
        builder.setPersisted(true);
        JobScheduler jobScheduler = (JobScheduler) this.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(builder.build());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
项目:mapbox-events-android    文件:JobSchedulerFlusher.java   
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void schedule(long elapsedRealTime) {
  JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
  jobScheduler.schedule(new JobInfo.Builder(SCHEDULER_FLUSHER_JOB_ID,
    new ComponentName(context, SchedulerFlusherJobService.class))
    .setPeriodic(FLUSHING_PERIOD_IN_MILLIS)
    .build());
}
项目:leanback-homescreen-channels    文件:DeleteWatchNextService.java   
public static void scheduleDeleteWatchNextRequest(Context context, String clipId) {
    JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);

    PersistableBundle bundle = new PersistableBundle();
    bundle.putString(ID_KEY, clipId);

    scheduler.schedule(new JobInfo.Builder(1, new ComponentName(context,
            DeleteWatchNextService.class))
            .setMinimumLatency(0)
            .setExtras(bundle)
            .build());
}