Please i have an activity that contains async task method, This async task method continues to execute in background even when the user has moved from that page. Please is there a way to stop async task executions as soon as a user press on the back button or move from that page to another page.
Below is what i have tried but it isnt working
private AsyncTask totalLikesAsync;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
context = this;
totalLikesAsync = new TotalLikes().execute(msgID);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
totalLikesAsync.cancel(true);
this.finish();
break;
case R.id.share:
new ShareImage().execute(msgImage);
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
private class TotalLikes extends AsyncTask<String, String, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... msgIDs) {
UserFunctions userFunction = new UserFunctions();
String msgsID = msgIDs[0];
JSONObject json=null;
if(!isCancelled()){
//This gets all the information unread from the server
json = userFunction.TotalLikes(context, msgsID);
}
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
if (json != null) {
...
} else {
...
}
}
}
UPDATE
After testing all the answers below, they all allow the execution of doinbackground
within the async task even though the back button is pressed. I want a situation where the Background would be cancelled as soon as back button is pressed.
@Override
public void onBackPressed() {
super.onBackPressed();
if (totalLikesAsync != null && totalLikesAsync.getStatus().equals(AsyncTask.Status.RUNNING)) {
totalLikesAsync.cancel(true);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
totalLikesAsync.cancel(true);
}
@Override
public void onBackPressed() {
TotalLikes.cancel(true);
// If you want to finish the activity you can use below code
// finish();
super.onBackPressed();
}
handle yourself the onBackPressed() method:
@Override
public void onBackPressed()
{
if (totalLikesAsync != null)
totalLikesAsync.cancel(true);
super.onBackPressed();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.