如何结束异步任务onBackPressed()

时间:2015-01-05 16:07:19

标签: android android-asynctask onbackpressed

如何在Android backpress上停止asynctask我想停止此活动,以便当它返回到上一个活动时此活动完全关闭

这个活动在后台工作,正如它应该做的那样,我的问题是当我们点击android后退按钮这个活动应该完全停止并回到第一个活动我做了somne​​搜索并且开始知道asynctask应该在背压上停下来 我试过,但似乎没有工作如何在下面的代码中完成

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

3 个答案:

答案 0 :(得分:2)

只需在活动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文档说:

  

可以通过调用cancel(boolean)随时取消任务。   调用此方法将导致后续调用isCancelled()   返回true。在调用此方法之后,改为onCancelled(Object)   之后将调用onPostExecute(Object)   doInBackground(Object [])返回。确保取消任务   你应该尽快检查返回值   如果可能的话,定期从doInBackground(Object [])获取isCancelled()   (例如在循环内部。)

答案 1 :(得分:0)

您需要保持对正在运行的AsyncTask对象的引用,并且当按下后退(或Activity暂停时)时,您需要调用实例对象的cancel()方法。您注释掉的代码试图将其称为静态方法,而不是。

答案 2 :(得分:-1)

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