【问题标题】:how to cancel the downloaded file in android using Dialog button?如何使用对话框按钮取消在android中下载的文件?
【发布时间】:2012-07-02 08:18:15
【问题描述】:
public class ExampleActivity extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }

    private void startDownload() {
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        new DownloadFileAsync().execute(url);
    }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);
            mProgressDialog.setButton("Cancel", new CancelOnClickListener());

            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }

    }
    private final class CancelOnClickListener implements DialogInterface.OnClickListener {
        public void onClick(DialogInterface dialog, int which) {
        ExampleActivity.this.finish();
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        new DownloadFileAsync().cancel(true);
    }

    }

class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {
        int count;

    try 
    {
    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();

    int lenghtOfFile = conexion.getContentLength();
    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

    byte data[] = new byte[1024];

    long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    }
    catch (Exception e) {

    }
    return null;

    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }


 }
}

如果我点击开始按钮,它将自动下载文件。但我想取消下载(如果我不喜欢),所以我输入mProgressDialog.setButton("Cancel", new CancelOnClickListener());this 退出应用程序。但文件正在下载.如何改变doInBackground()里面的函数

【问题讨论】:

    标签: android dialog android-asynctask


    【解决方案1】:

    您在startDownload() 和CancelOnClickListener 中使用了DownloadFileAsync 的两个不同实例。试试下面的代码:

    public class ExampleActivity extends Activity {
    
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
    
    DownloadFileAsync dfa = new DownloadFileAsync();
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }
    
    private void startDownload() {
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        dfa.execute(url);
    }
    
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);
            mProgressDialog.setButton("Cancel", new CancelOnClickListener());
    
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    
    }
    private final class CancelOnClickListener implements DialogInterface.OnClickListener {
        public void onClick(DialogInterface dialog, int which) {
        ExampleActivity.this.finish();
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        dfa.cancel(true);
    }
    
    }
    
    class DownloadFileAsync extends AsyncTask<String, String, String> {
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
    
    @Override
    protected String doInBackground(String... aurl) {
        int count;
    
    try 
    {
    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();
    
    int lenghtOfFile = conexion.getContentLength();
    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
    
    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");
    
    byte data[] = new byte[1024];
    
    long total = 0;
    if(!isCancelled()){
        while (!isCancelled() && (count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }
    
        output.flush();
        output.close();
        input.close();
    }
    }
    catch (Exception e) {
    
    }
    return null;
    
    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }
    
    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }
    
    
    }
    }
    

    【讨论】:

    • 即使我点击 AsynTask 中的取消按钮,下载的文件仍然保存在 SD 卡中
    • 当您在 Asynctask 的实例上调用 cancel() 时,它会尝试取消任务。该api建议我们定期检查isCancelled()方法以确保任务没有被取消。检查此链接:developer.android.com/reference/android/os/…。我已经更新了代码,你可能想看看它。
    • 只是我添加了这一行 if(isCancelled()) { File file = new File("/sdcard/some_photo_from_gdansk_poland.jpg");文件.删除(); }
    • 谢谢,flush() 和 close() 调用应该放在 finally 子句中,因为这里的异常可能会导致内存泄漏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多