I have a Service which does regular operations such as Bluetooth discovery and sending emails. Depending on the state, it starts different threads which does Bluetooth socket connection or send emails. I’m using AsyncTask to do email sending and it is working well at the moment.
The question I have is this: does AsyncTask I started from the Service finish when Service is stopped, or is the Service not stopped until AsyncTask completes? Under normal circumstances the Service is never ‘stopped’, but it can be stopped when the memory is low, or when the battery is low, or when the phone turns off. I need to resume the operation after the Service is stopped, and I’m wondering how to tell if AsyncTask has completed when the Service is stopped.
I have included a snapshot of my code.
public class ScheduledService extends Service {
SendEmailAsyncTask emailTask;
boolean emailSuccess;
@Override
public int onStartCommand(Intent intent, int flag, int startId) {
log.v("onStart()");
super.onStartCommand(intent, flag, startId);
// do regular operations
if (state == sendEmail) {
emailTask = new SendEmailAsyncTask();
emailTask.execute();
}
}
class SendEmailAsyncTask extends AsyncTask <Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
// send email
}
@Override
protected void onPostExecute(Boolean result){
if (result) {
createNotification("Email has been sent!");
emailSuccess = true;
} else {
//try again
emailSuccess = false;
}
}
}
}
the task won’t stop if its doing something and in between the service is stopped. Unless you call task’s cancel method in service’s onDestroy’s implementation, it will be ended only once completed