下面列出了怎么用android.app.job.JobParameters的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
@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;
}
@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;
}
@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;
}
@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;
}
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;
}
@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;
}
@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;
}
}
@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;
}
@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;
}
/**
* 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;
}
@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;
}
@Override
public boolean onStopJob(JobParameters params) {
LogUtil.i(TAG, "onStopJob");
UserRepository userRepo = State.userRepo();
if (userRepo.loggedIn()) {
ServiceManager.startToxService();
}
return false;
}
@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;
}
@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;
}
@Override
public boolean onStartJob(JobParameters jobParameters) {
Log.i(getClass().getName(), "onStartJob");
this.jobParameters = jobParameters;
mergeThread = new MergeThread(this);
mergeThread.start();
return false;
}
@Override
public void stopJob(JobParameters jobParams) throws RemoteException {
int jobId = jobParams.getJobId();
synchronized (mJobSessions) {
JobSession session = mJobSessions.get(jobId);
if (session != null) {
session.stopSession();
}
}
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.i(getClass().getName(), "onStopJob");
if ((authenticationThread != null) && (authenticationThread.isAlive())){
authenticationThread.interrupt();
}
return false;
}
@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;
}
@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;
}
@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;
}
@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;
}
@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();
}
}
}
}
@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;
}
@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;
}
@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;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
if (mSynchronizeDatabaseTask != null) {
mSynchronizeDatabaseTask.cancel(true);
mSynchronizeDatabaseTask = null;
}
return true;
}
@Override
public boolean onStartJob(JobParameters jobParameters) {
AddWatchNextContinueInBackground newTask = new AddWatchNextContinueInBackground(
jobParameters);
newTask.execute();
return true;
}
@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;
}
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;
}