(JobService, IntentService), :
, Handler.Callback, IntentService Messenger, IntentService .Callback . Handler.Callback JobService, finishJob (...).
public class MyJobService extends JobService implements Handler.Callback {
private Handler mHandler = new Handler(this);
public static final String BNDL_MESSENGER = "messenger";
public static final String BNDL_PARAMS = "params";
public static final int FINISH_JOB_MESSAGE = 100;
public static final int NEEDS_RESCHEDULE_TRUE = 0;
public static final int NEEDS_RESCHEDULE_FALSE = 1;
public boolean handleMessage(Message msg) {
int msgType = msg.what;
if (msgType == FINISH_JOB_MESSAGE) {
int jobId = msg.arg1;
JobParameters params = (JobParameters)msg.obj;
boolean needsReschedule = (msg.arg2 == NEEDS_RESCHEDULE_TRUE);
Log.i(TAG, "Finishing Job ID: " + jobId);
jobFinished(params, needsReschedule);
} else {
Log.e(TAG, "Message type not supported: " + msgType);
}
}
@Override
public boolean onStartJob(JobParameters params) {
Intent intent = new Intent(this, MyIntentService.class);
intent.putExtra(BNDL_MESSENGER, new Messenger(mHandler));
intent.putExtra(BNDL_PARAMS, params);
startService(intent);
}
}
IntentService :
public class MyIntentService extends IntentService {
@Override
public void onHandleIntent(Intent intent) {
Messenger messenger = (Messenger)intent.getParcelableExtra(MyJobService.BNDL_MESSENGER);
JobParameters params = (JobParameters)intent.getParcelableExtra(MyJobService.BNDL_PARAMS);
if (messenger != null) {
Message msg = Message.obtain();
msg.what = MyJobService.FINISH_JOB_MESSAGE;
msg.arg1 = params.getJobId();
msg.arg2 = MyJobService.NEEDS_RESCHEDULE_TRUE;
msg.obj = params;
try {
messenger.send(msg);
} catch (RemoteException re) {
Log.e(TAG, "Couldn't send message to finish job!", re);
}
}
}
}