问题
how to stop asynctask on android backpress i want to stop this activity so that when it goes back to previous activity this activity is completely closed
this activity does its work in background , as it is supposed to do, my problem is when we click the android back button this activity should completely stop and go back to first activity i did somne search and came to know the asynctask should be stopped on back press i tried that but ii doesnot seem to work how can this be done in the below code
package com.Blog.blogname;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import com.Blog.blogname.parser.DOMParser;
import com.Blog.blogname.parser.RSSFeed;
public class SplashActivity extends Activity {
//String RSSFEEDURL = "http://feeds.blogname.com/blogname?format=xml";
//String RSSFEEDURL = "http://blogname.blogname.com/feeds/posts/default?alt=rss";
//int position = i.getExtras().getInt("position");
//String[] country = i.getStringArrayExtra("country");
//Toast.makeText(this, i.getStringArrayExtra("country") + "was selected" , Toast.LENGTH_LONG).show();
//String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss";
//String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/country[position]?alt=rss";
RSSFeed feed;
String fileName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
// //public String RSSFEEDURL = "http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss";
Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity!",
Toast.LENGTH_LONG);
toast.show();
//feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
//feed = myParser.parseXml(RSSFEEDURL);
//feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/Awards?alt=rss");
feed = myParser.parseXml("http://blogname.blogspot.com//feeds/posts/default/-/" + country[position] + "?alt=rss");
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
// private RSSFeed ReadFeed(String fName) {
//
// FileInputStream fIn = null;
// ObjectInputStream isr = null;
//
// RSSFeed _feed = null;
// File feedFile = getBaseContext().getFileStreamPath(fileName);
// if (!feedFile.exists())
// return null;
//
// try {
// fIn = openFileInput(fName);
// isr = new ObjectInputStream(fIn);
//
// _feed = (RSSFeed) isr.readObject();
// }
//
// catch (Exception e) {
// e.printStackTrace();
// }
//
// finally {
// try {
// fIn.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// return _feed;
//
// }
// @Override
// public void onBackPressed()
// {
// finish();
// }
// @Override
// public void onBackPressed(){
// if(condition){
// super.onBackPressed(); //Normal behaviour
// } else {
// startLisActivity(feed);
// }
// }
//private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.
//private long mBackPressed;
//@Override
// public void onBackPressed()
// {
// if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
// {
// super.onBackPressed();
// return;
// }
// else if(mBackPressed + TIME_INTERVAL < System.currentTimeMillis()){ Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }
// else {
// //startLisActivity(feed);
// @Override
// protected void onPostExecute(Void result) {
// super.onPostExecute(result);
//
// startLisActivity(feed);
// }
//}
// mBackPressed = System.currentTimeMillis();
//}
@Override
// public void onBackPressed() {
// //DOMParser().cancel(true);
// AsyncLoadXMLFeed.cancel(true);
// // If you want to finish the activity you can use below code
// finish();
// }
// public void onBackPressed()
// {
//
// .cancel(true);
// }
//public void onBackPressed(){
//
//
// if (AsyncLoadXMLFeed != null) if (AsyncLoadXMLFeed.getStatus() == Status.RUNNING) AsyncLoadXMLFeed.cancel(true);
// finish();
// //overridePendingTransition(R.anim.zoom_enter,R.anim.zoom_exit);
// }
}
回答1:
Simply call cancel in activities onDestroy()
public SplashActivity extends Activity {
private AsyncLoadXMLFeed loader;
@Override
public void onCreate(Bundle b){
super.onCreate(b);
...
// Connected - Start parsing
loader = new AsyncLoadXMLFeed();
loader.execute();
}
@Override
public void onDestroy(){
super.onDestroy();
// Cancel the task
loader.cancel(true);
}
}
The official android documentation says:
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
回答2:
You need to keep a reference to your running AsyncTask
object and when back is pressed (or the Activity
is paused) you need to call the cancel()
method of the instance object. Your commented out code is trying to call it as a static method, which it is not.
回答3:
The ProgressDialog has a convenient method that gets called when the user press back.
taskParseKmlDownload = new TaskParseKmlDownload(kmlSummary,
new WeakReference<Context>(this),
this, mMap);
taskParseKmlDownload.execute();
taskParseKmlDownloadProgress = new ProgressDialog(this);
taskParseKmlDownloadProgress.setMessage("Parsing KML File");
taskParseKmlDownloadProgress.show();
taskParseKmlDownloadProgress
.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
taskParseKmlDownload.cancel(false);
}
});
Then in the task you have to check .isCanceled()
Below I'm simply returning -1 if the user cancels the task.
// check for cancel before next download
if (isCancelled()) {
return RESULT_ABORTED;
}
来源:https://stackoverflow.com/questions/27783320/how-to-end-asynctask-onbackpress