以下は、FireBaseJobDispatcher を使用してジョブを開始するデモ コードです。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job job=createJob(dispatcher);
dispatcher.schedule(job);
}
public static Job createJob(FirebaseJobDispatcher dispatcher){
Job job = dispatcher.newJobBuilder()
// persist the task across boots
.setLifetime(Lifetime.FOREVER)
// Call this service when the criteria are met.
.setService(ScheduledJobService.class)
// unique id of the task
.setTag("LocationJob")
// We are mentioning that the job is not periodic.
.setRecurring(true)
// Run between 30 - 60 seconds from now.
.setTrigger(Trigger.executionWindow(10,20))
//Run this job only when the network is avaiable.
.setConstraints(Constraint.ON_ANY_NETWORK)
.build();
return job;
}
}
以下はデモサービスです
public class ScheduledJobService extends JobService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {
private GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
@Override
public boolean onStartJob(JobParameters job) {
Log.d("token","Start Job Called");
setUpLocationClientIfNeeded();
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30000);
return true;
}
@Override
public boolean onStopJob(JobParameters job) {
Log.d("token","stopped");
return true;
}
@Override
public void onConnected(@Nullable Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
mLocationRequest, this); // This is the changed line.
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private void setUpLocationClientIfNeeded()
{
if(mGoogleApiClient == null)
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
this.mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
this.mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
Log.d("token",location.getLatitude()+""+location.getLongitude());
}
}
受信した新しい場所に基づいて、マップ内の場所を更新しています。ユーザーが目的地に到達したら、ジョブを終了したいので、ユーザーが目的地に到達してリソースを解放したら、このジョブを停止するにはどうすればよいですか。