我正在使用异步任务来访问Web服务url并从服务器检索结果但是在onPreExecute()方法中有一段时间如果发生解析异常我在catch()方法上处理它,现在我想暂停处理下一步意味着执行不去OnpostExecute()方法,所以如何停止执行进程将其转到OnPostExecute() 我的代码在下面
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainMenu.this);
dialog.setMessage("Processing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing())
{
dialog.dismiss();
}
Intent i = new Intent(MainMenu.this, filterpagetabs.class);
startActivity(i);
}
@Override
protected Boolean doInBackground(final String... args) {
try{
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL(
"http://www.mobi/iphonejh/output.php?estado=1");
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
答案 0 :(得分:3)
http://developer.android.com/reference/android/os/AsyncTask.html
“可以通过调用cancel(boolean)随时取消任务。调用此方法将导致后续调用isCancelled()返回true。调用此方法后,onCancelled(Object),而不是onPostExecute(Object)将在doInBackground(Object [])返回后调用。为确保尽快取消任务,应始终定期从doInBackground(Object [])检查isCancelled()的返回值(如果可能)(在循环内)例如。)“
虽然,由于您的大部分工作已经完成,即网络I / O,最好只返回成功布尔值并检查onPostExecute
答案 1 :(得分:1)
将parsingSuccessful布尔变量放在顶部,值为true。在catch的异常集中设置false。在postExecute中,使用if语句检查解析是否已成功完成,并将onPostExecute行放在此if语句中。
像这样:
private boolean parsingSuccessful = true;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainMenu.this);
dialog.setMessage("Processing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
@Override
protected void onPostExecute(final Boolean success) {
if (parsingSuccessful == true){
if (dialog.isShowing()){
dialog.dismiss();
}
Intent i = new Intent(MainMenu.this, filterpagetabs.class);
startActivity(i);
}
}
@Override
protected Boolean doInBackground(final String... args) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceUrl = new URL(
"http://www.mobi/iphonejh/output.php?estado=1");
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
parsingSuccessful = false;
}