Reputation: 83
Below I have a method that cancel my asynctask and ProgressDialog
. The code works well but when you press the back button it stops everything as its suppose too but it will just leave the user staring at a unpopulated listview. So the idea here is that when the user clicks the back button it stops the asynctask and ProgressDialog
and instead of just leaving them looking at a unpopulated listview I want it to also take them back to the main activity as well. Can anybody help me to make this possible?
@Override
public void onBackPressed()
{
/** If user Pressed BackButton While Running Asynctask
this will close the ASynctask.
*/
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onBackPressed();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
/** If Activity is Destroyed While Running Asynctask
this will close the ASynctask. */
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
if (pDialog != null)
{
if(pDialog.isShowing())
{
pDialog.dismiss();
}
super.onPause();
}
}
Upvotes: 1
Views: 1186
Reputation: 3232
use this : getActivity = for fragment, for activity use ActivityName.this
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finishActivity(false);
Upvotes: 0
Reputation: 48871
Simply calling mTask.cancel(true);
won't immediately cancel your AsyncTask
. You need to periodically call isCancelled()
in doInBackground(...)
- if the result is true
you need to return from doInBackground(...)
.
In this case, onPostExecute(...)
will not be called and instead onCancelled()
will be called and you can call finish()
to terminate the Activity
.
Upvotes: 0