0

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

这个活动在后台完成它应该做的工作,我的问题是当我们点击android后退按钮时,这个活动应该完全停止并返回到第一个活动我做了somne​​搜索并知道应该停止异步任务后按我试过了,但 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);
//  }
}
4

3 回答 3

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。调用此方法后,将在 doInBackground(Object[]) 返回后调用 onCancelled(Object),而不是 onPostExecute(Object)。为了确保尽快取消任务,如果可能(例如在循环内),您应该始终从 doInBackground(Object[]) 定期检查 isCancelled() 的返回值。

于 2015-01-05T17:10:17.413 回答
0

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

于 2015-01-05T16:13:19.897 回答
-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;
        }
于 2015-01-05T17:05:07.640 回答