如何结束 AsyncTask onBackPress()

How to end AsyncTask onBackPress()

如何在 android backpress 上停止 asynctask 我想停止这个 activity 这样当它回到之前的 activity 这个 activity 就完全关闭了

这个 activity 在后台工作,正如它应该做的那样,我的问题是当我们点击 android 后退按钮时,这个 activity 应该完全停止并返回首先 activity 我做了一些搜索,然后知道 asynctask 应该在后退时停止 我试过了,但 ii 似乎不起作用如何在下面的代码中完成

 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);
//  }
}

您需要保留对 运行 AsyncTask 对象的引用,并且当按下后退(或 Activity 暂停)时,您需要调用 cancel()实例对象的方法。您注释掉的代码试图将其作为静态方法调用,但事实并非如此。

ProgressDialog 有一个方便的方法,当用户按下返回键时调用。

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);
                    }
                });

然后在任务中你必须检查.isCanceled() 如果用户取消任务,下面我只是返回 -1。

 // check for cancel before next download
        if (isCancelled()) {
            return RESULT_ABORTED;
        }

只需在活动中调用取消即可 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);
   }    
}

官方 android 文档说:

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.)