0
I’m studying the services in Android Background and managed to create a service in Background that already works well in the background even after restarting the android or close the App. The problem is when I want to close Jobservice by a button in Activity.
I tried with: jobScheduler.cancel(id)
and jobScheduler.cancelAll()
. But neither of them had any effect.
My code is as follows currently:
Broadcastreceiver.java
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ComponentName comp = new ComponentName(context.getPackageName(), ServiceLocationJob.class.getName());
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo jobInfo = new JobInfo.Builder(11, comp)
// only add if network access is required
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setMinimumLatency(1)
.setOverrideDeadline(1)
.build();
jobScheduler.schedule(jobInfo);
Log.d(Tag, "Iniciado servicoJob as: " + c.getTime().toString());
}
Servicelocationjob.java
private Thread locationThread;
@Override
public boolean onStartJob(JobParameters jobParameters) {
locationThread = new Thread(new Runnable() {
@Override
public void run() {
Log.d(Tag, "Serviço (API<21) iniciado pelo Broadcast com sucesso!");
new Timer().scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
Calendar c = Calendar.getInstance();
Log.i(Tag, "Serviço funcionando a cada 10 segundos mesmo após reiniciar: " + c.getTime());
}
},0,10000);
}
});
locationThread.start();
return true;
}
And finally Mainactivity.java
public void desligarServico() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
JobScheduler jobScheduler = (JobScheduler)this.getSystemService(Context.JOB_SCHEDULER_SERVICE );
jobScheduler.cancelAll();
Log.d(Tag, "Serviço parado (API>=21) com sucesso");
}
}
I don’t know if it’s the Thread who lives even after cancelling the Jobscheduler. So much so that I ended up trying to put locationThread.Interrupt(); within the facility onStopJob(), but still unsuccessful.
I’ve tried putting it in the way onStopJob class Jobservice the method jobFinished(jobParameters, false);
. But still I could not stop the service completely using the button.
I would like a suggestion on how to resolve this.