Java Code Examples for android.app.job.JobParameters

The following examples show how to use android.app.job.JobParameters. These examples are extracted from open source projects. 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
@Override
public boolean onStartJob(JobParameters params) {
  Log.d(TAG, "onStartJob()");

  if (BackgroundMessageRetriever.shouldIgnoreFetch(this)) {
    Log.i(TAG, "App is foregrounded. No need to run.");
    return false;
  }

  SignalExecutors.UNBOUNDED.execute(() -> {
    Context                    context   = getApplicationContext();
    BackgroundMessageRetriever retriever = ApplicationDependencies.getBackgroundMessageRetriever();
    boolean                    success   = retriever.retrieveMessages(context, new RestStrategy(), new RestStrategy());

    if (success) {
      Log.i(TAG, "Successfully retrieved messages.");
      jobFinished(params, false);
    } else {
      Log.w(TAG, "Failed to retrieve messages. Scheduling a retry.");
      jobFinished(params, true);
    }
  });

  return true;
}
 
Example 2
@Override
public boolean onStartJob(JobParameters jobParameters) {
    Log.i(TAG, "Start params=" + jobParameters);

    Intent intent = new Intent(this, BackgroundService.class);
    int id = jobParameters.getJobId();
    if (id == JOB_UPLOAD_GPX) {
        intent.setAction(BackgroundService.ACTION_UPLOAD_GPX);
        intent.putExtras(Util.getBundle(jobParameters.getExtras()));
    } else if (id == JOB_CONNECTIVITY)
        intent.setAction(BackgroundService.ACTION_CONNECTIVITY);
    else
        Log.w(TAG, "Unknown job id=" + id);

    Log.i(TAG, "Starting intent=" + intent);
    startService(intent);

    return false;
}
 
Example 3
Source Project: xipl   Source File: EpgSyncJobService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onStartJob(JobParameters params) {
    if (DEBUG) {
        Log.d(TAG, "onStartJob(" + params.getJobId() + ")");
    }
    // Broadcast status
    Intent intent = createSyncStartedIntent(params.getExtras().getString(BUNDLE_KEY_INPUT_ID));
    LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

    EpgSyncTask epgSyncTask = new EpgSyncTask(params);
    synchronized (mTaskArray) {
        mTaskArray.put(params.getJobId(), epgSyncTask);
    }
    // Run the task on a single threaded custom executor in order not to block the AsyncTasks
    // running on application side.
    epgSyncTask.executeOnExecutor(SINGLE_THREAD_EXECUTOR);
    return true;
}
 
Example 4
Source Project: android-beacon-library   Source File: ScanJob.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onStopJob(JobParameters params) {
    // See corresponding synchronized block in onStartJob
    synchronized(ScanJob.this) {
        mStopCalled = true;
        if (params.getJobId() == getPeriodicScanJobId(this)) {
            LogManager.i(TAG, "onStopJob called for periodic scan " + this);
        }
        else {
            LogManager.i(TAG, "onStopJob called for immediate scan " + this);
        }
        LogManager.d(TAG, "ScanJob Lifecycle STOP: "+ScanJob.this);
        // Cancel the stop timer.  The OS is stopping prematurely
        mStopHandler.removeCallbacksAndMessages(null);

        stopScanning();
        startPassiveScanIfNeeded();
        if (mScanHelper != null) {
            mScanHelper.terminateThreads();
        }
    }
    return false;
}
 
Example 5
Source Project: androidtv-sample-inputs   Source File: EpgSyncJobService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onStartJob(JobParameters params) {
    if (DEBUG) {
        Log.d(TAG, "onStartJob(" + params.getJobId() + ")");
    }
    // Broadcast status
    Intent intent = createSyncStartedIntent(params.getExtras().getString(BUNDLE_KEY_INPUT_ID));
    LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

    EpgSyncTask epgSyncTask = new EpgSyncTask(params);
    synchronized (mTaskArray) {
        mTaskArray.put(params.getJobId(), epgSyncTask);
    }
    // Run the task on a single threaded custom executor in order not to block the AsyncTasks
    // running on application side.
    epgSyncTask.executeOnExecutor(SINGLE_THREAD_EXECUTOR);
    return true;
}
 
Example 6
Source Project: android_9.0.0_r45   Source File: BackgroundDexOptService.java    License: Apache License 2.0 6 votes vote down vote up
private boolean runIdleOptimization(final JobParameters jobParams,
        final PackageManagerService pm, final ArraySet<String> pkgs) {
    new Thread("BackgroundDexOptService_IdleOptimization") {
        @Override
        public void run() {
            int result = idleOptimization(pm, pkgs, BackgroundDexOptService.this);
            if (result != OPTIMIZE_ABORT_BY_JOB_SCHEDULER) {
                Log.w(TAG, "Idle optimizations aborted because of space constraints.");
                // If we didn't abort we ran to completion (or stopped because of space).
                // Abandon our timeslice and do not reschedule.
                jobFinished(jobParams, /* reschedule */ false);
            }
        }
    }.start();
    return true;
}
 
Example 7
Source Project: 365browser   Source File: BackgroundTaskJobService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onStopJob(JobParameters params) {
    ThreadUtils.assertOnUiThread();
    if (!mCurrentTasks.containsKey(params.getJobId())) {
        Log.w(TAG, "Failed to stop job, because job with job id " + params.getJobId()
                        + " does not exist.");
        return false;
    }

    BackgroundTask backgroundTask = mCurrentTasks.get(params.getJobId());

    TaskParameters taskParams =
            BackgroundTaskSchedulerJobService.getTaskParametersFromJobParameters(params);
    boolean taskNeedsReschedule =
            backgroundTask.onStopTask(getApplicationContext(), taskParams);
    mCurrentTasks.remove(params.getJobId());
    return taskNeedsReschedule;
}
 
Example 8
Source Project: android_9.0.0_r45   Source File: BackgroundDexOptService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onStopJob(JobParameters params) {
    if (DEBUG_DEXOPT) {
        Log.i(TAG, "onStopJob");
    }

    if (params.getJobId() == JOB_POST_BOOT_UPDATE) {
        mAbortPostBootUpdate.set(true);

        // Do not reschedule.
        // TODO: We should reschedule if we didn't process all apps, yet.
        return false;
    } else {
        mAbortIdleOptimization.set(true);

        // Reschedule the run.
        // TODO: Should this be dependent on the stop reason?
        return true;
    }
}
 
Example 9
@Override
    public boolean onStartJob(JobParameters params) {
        Log.i(getClass().getName(), "onStartJob");

        // Start processing work
        boolean isWifiEnabled = ConnectivityHelper.isWifiEnabled(getApplicationContext());
        Log.i(getClass().getName(), "isWifiEnabled: " + isWifiEnabled);
        boolean isWifiConnected = ConnectivityHelper.isWifiConnected(getApplicationContext());
        Log.i(getClass().getName(), "isWifiConnected: " + isWifiConnected);
        if (!isWifiEnabled) {
//            Toast.makeText(getApplicationContext(), getString(R.string.wifi_needs_to_be_enabled), Toast.LENGTH_SHORT).show();
            Log.i(getClass().getName(), getString(R.string.wifi_needs_to_be_enabled));
        } else if (!isWifiConnected) {
//            Toast.makeText(getApplicationContext(), getString(R.string.wifi_needs_to_be_connected), Toast.LENGTH_SHORT).show();
            Log.i(getClass().getName(), getString(R.string.wifi_needs_to_be_connected));
        } else {
            new ReadDeviceAsyncTask(getApplicationContext()).execute();
        }

        boolean isWorkProcessingPending = false;
        return isWorkProcessingPending;
    }
 
Example 10
Source Project: service   Source File: myJobService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean onStartJob(final JobParameters params) {
    // The work that this service "does" is simply wait for a certain duration and finish
    // the job (on another thread).

    int max = params.getExtras().getInt("max", 6);  //something low so I know it didn't work.
    Log.wtf(TAG, "max is " + max);

    // Process work here...  we'll pretend by sleeping for 3 seconds.
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
    }

    Toast.makeText(getApplicationContext(), "Job: number is " + mGenerator.nextInt(max), Toast.LENGTH_SHORT).show();
    Log.i(TAG, "Job: I'm working on something...");

    //since there seems to be threshold on recurring.  say 10 to 30 minutes, based on simple tests.
    //you could just reschedule the job here.  Then the time frame can be much shorter.
    //scheduleJob(getApplicationContext(),max, true);

    // Return true as there's more work to be done with this job.
    return true;
}
 
Example 11
Source Project: neverEndingProcessAndroid7-   Source File: JobService.java    License: MIT License 6 votes vote down vote up
/**
 * called if Android kills the job service
 * @param jobParameters
 * @return
 */
@Override
public boolean onStopJob(JobParameters jobParameters) {
    Log.i(TAG, "Stopping job");
    Intent broadcastIntent = new Intent(Globals.RESTART_INTENT);
    sendBroadcast(broadcastIntent);
    // give the time to run
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            unregisterReceiver(restartSensorServiceReceiver);
        }
    }, 1000);

    return false;
}
 
Example 12
@Override
public boolean onStartJob(JobParameters params) {
    this.params = params;
    connectedServicesCounter = 0;
    appendLog(this, TAG, "starting cells only location lookup");
    if (locationUpdateService == null) {
        try {
            Intent intent = new Intent(getApplicationContext(), LocationUpdateService.class);
            getApplicationContext().bindService(intent, locationUpdateServiceConnection, Context.BIND_AUTO_CREATE);
        } catch (Exception ie) {
            appendLog(getBaseContext(), TAG, "currentWeatherServiceIsNotBound interrupted:", ie);
        }
    } else {
        locationUpdateService.updateNetworkLocation(
            params.getExtras().getBoolean("byLastLocationOnly"),
            null,
            params.getExtras().getInt("attempts"));
        jobFinished(params, false);
    }
    return true;
}
 
Example 13
@Override
public boolean onStopJob(JobParameters params) {
    LogUtil.i(TAG, "onStopJob");
    UserRepository userRepo = State.userRepo();
    if (userRepo.loggedIn()) {
        ServiceManager.startToxService();
    }
    return false;
}
 
Example 14
Source Project: titan-hotfix   Source File: JobIntentService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onStartJob(JobParameters params) {
    if (DEBUG) {
        Log.d(TAG, "onStartJob: " + params);
    }
    mParams = params;
    // We can now start dequeuing work!
    mService.ensureProcessorRunningLocked(false);
    return true;
}
 
Example 15
Source Project: titan-hotfix   Source File: JobIntentService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onStopJob(JobParameters params) {
    if (DEBUG) {
        Log.d(TAG, "onStartJob: " + params);
    }
    boolean result = mService.doStopCurrentWork();
    synchronized (mLock) {
        // Once we return, the job is stopped, so its JobParameters are no
        // longer valid and we should not be doing anything with them.
        mParams = null;
    }
    return result;
}
 
Example 16
@Override
public boolean onStartJob(JobParameters jobParameters) {
    Log.i(getClass().getName(), "onStartJob");
    this.jobParameters = jobParameters;
    mergeThread = new MergeThread(this);
    mergeThread.start();
    return false;
}
 
Example 17
Source Project: container   Source File: StubJob.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void stopJob(JobParameters jobParams) throws RemoteException {
    int jobId = jobParams.getJobId();
    synchronized (mJobSessions) {
        JobSession session = mJobSessions.get(jobId);
        if (session != null) {
            session.stopSession();
        }
    }
}
 
Example 18
@Override
public boolean onStopJob(JobParameters jobParameters) {
    Log.i(getClass().getName(), "onStopJob");
    if ((authenticationThread != null) && (authenticationThread.isAlive())){
        authenticationThread.interrupt();
    }
    return false;
}
 
Example 19
Source Project: qiscus-sdk-android   Source File: QiscusSyncJobService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onStartJob(JobParameters params) {
    QiscusLogger.print(TAG, "Job started...");

    if (QiscusCore.hasSetupUser()) {
        if (!QiscusPusherApi.getInstance().isConnected()) {
            QiscusAndroidUtil.runOnUIThread(() -> QiscusPusherApi.getInstance().restartConnection());
        }
        scheduleSync();
        syncJob(this);
    }

    return true;
}
 
Example 20
Source Project: android-job   Source File: SafeJobServiceEngineImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onStopJob(JobParameters params) {
    if (DEBUG) Log.d(TAG, "onStopJob: " + params);
    boolean result = mService.doStopCurrentWork();
    synchronized (mLock) {
        // Once we return, the job is stopped, so its JobParameters are no
        // longer valid and we should not be doing anything with them.
        mParams = null;
    }
    return result;
}
 
Example 21
Source Project: android_9.0.0_r45   Source File: JobServiceContext.java    License: Apache License 2.0 5 votes vote down vote up
@GuardedBy("mLock")
boolean timeoutIfExecutingLocked(String pkgName, int userId, boolean matchJobId, int jobId,
        String reason) {
    final JobStatus executing = getRunningJobLocked();
    if (executing != null && (userId == UserHandle.USER_ALL || userId == executing.getUserId())
            && (pkgName == null || pkgName.equals(executing.getSourcePackageName()))
            && (!matchJobId || jobId == executing.getJobId())) {
        if (mVerb == VERB_EXECUTING) {
            mParams.setStopReason(JobParameters.REASON_TIMEOUT, reason);
            sendStopMessageLocked("force timeout from shell");
            return true;
        }
    }
    return false;
}
 
Example 22
@Override
public boolean onStartJob(JobParameters jobParameters) {
    Log.i(getClass().getName(), "onStartJob");
    if (StartPrefsHelper.activateAuthentication()) {
        this.jobParameters = jobParameters;
        trainingThread = new TrainingThread(this);
        trainingThread.start();
    }
    return false;
}
 
Example 23
Source Project: android_9.0.0_r45   Source File: JobSchedulerService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onDeviceIdleStateChanged(boolean deviceIdle) {
    synchronized (mLock) {
        if (deviceIdle) {
            // When becoming idle, make sure no jobs are actively running,
            // except those using the idle exemption flag.
            for (int i=0; i<mActiveServices.size(); i++) {
                JobServiceContext jsc = mActiveServices.get(i);
                final JobStatus executing = jsc.getRunningJobLocked();
                if (executing != null
                        && (executing.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0) {
                    jsc.cancelExecutingJobLocked(JobParameters.REASON_DEVICE_IDLE,
                            "cancelled due to doze");
                }
            }
        } else {
            // When coming out of idle, allow thing to start back up.
            if (mReadyToRock) {
                if (mLocalDeviceIdleController != null) {
                    if (!mReportedActive) {
                        mReportedActive = true;
                        mLocalDeviceIdleController.setJobsActive(true);
                    }
                }
                mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
            }
        }
    }
}
 
Example 24
Source Project: timecat   Source File: JobService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onStopJob(JobParameters params) {
    LogUtil.d(TAG, "onStopJob");
    startService(new Intent(JobService.this, TimeCatMonitorService.class));
    startService(new Intent(JobService.this, ListenClipboardService.class));
    return false;
}
 
Example 25
Source Project: batteryhub   Source File: DataEstimator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onStartJob(JobParameters params) {
    final int jobID = params.getJobId();

    Intent service = new Intent(mContext, DataEstimatorService.class);
    service.putExtra("OriginalAction", mAction);
    service.fillIn(mIntent, 0);

    startService(service);
    jobFinished(params, false);

    return true;
}
 
Example 26
Source Project: android_9.0.0_r45   Source File: MountServiceIdler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onStopJob(JobParameters params) {
    // Once we kick off the fstrim we aren't actually interruptible; just note
    // that we don't need to call jobFinished(), and let everything happen in
    // the callback from the mount service.
    StorageManagerService ms = StorageManagerService.sSelf;
    if (ms != null) {
        ms.abortIdleMaint(mFinishCallback);
        synchronized (mFinishCallback) {
            mStarted = false;
        }
    }
    return false;
}
 
Example 27
@Override
public boolean onStopJob(JobParameters jobParameters) {
    if (mSynchronizeDatabaseTask != null) {
        mSynchronizeDatabaseTask.cancel(true);
        mSynchronizeDatabaseTask = null;
    }
    return true;
}
 
Example 28
@Override
public boolean onStartJob(JobParameters jobParameters) {
    AddWatchNextContinueInBackground newTask = new AddWatchNextContinueInBackground(
            jobParameters);
    newTask.execute();
    return true;
}
 
Example 29
@Override
public boolean onStartJob(JobParameters params) {
    int connectivityScheduleId = getScheduleId(this, ON_NETWORK_AVAILABLE_JOB_ID);
    if (params.getJobId() == connectivityScheduleId) {
        if (TextUtils.isEmpty(mobileMessagingCore().getApplicationCode())) {
            return false;
        }
        MobileMessagingLogger.d(TAG, "Network available");
        mobileMessagingCore().retrySyncOnNetworkAvailable();
        return false;
    }

    return false;
}
 
Example 30
Source Project: android_9.0.0_r45   Source File: BackgroundDexOptService.java    License: Apache License 2.0 5 votes vote down vote up
private boolean runPostBootUpdate(final JobParameters jobParams,
        final PackageManagerService pm, final ArraySet<String> pkgs) {
    if (mExitPostBootUpdate.get()) {
        // This job has already been superseded. Do not start it.
        return false;
    }
    new Thread("BackgroundDexOptService_PostBootUpdate") {
        @Override
        public void run() {
            postBootUpdate(jobParams, pm, pkgs);
        }

    }.start();
    return true;
}