Android:如何在另一个包的 Activity 中显示异步任务的进度对话框?

Android: How to show ProgressDailog from Async Task in Activity from another Pack?

我仍在尝试制作我的第一个应用程序。所以,它长大了……我试着把它分成几个包。 我的第一个包与文件一起使用,它将包含 classes,它们可以:下载文件、从文件中读取数据和 et.c.

所以我尝试先从我的主 activity 中移出 class,但是 ProgressDialog 有问题,它不起作用。所以我有几个问题:

1) 将下载百分比发送到“我的应用程序”的 activity 的最佳方式是什么? 2) 如果用户在下载过程中改变电流 Activity 会发生什么?

package com.domen.myapplication.Files;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.widget.Toast;


import com.domen.myapplication.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by DL  on 01.08.2016.
 */
public class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;
    private PowerManager.WakeLock mWakeLock;
    public int progress=0;
    public int progressShow=0;
    public ProgressDialog mProgressDialog;




    public DownloadTask(Context context) {
        this.context = context;

        mProgressDialog = new ProgressDialog(this.context);
        mProgressDialog.setMessage(this.context.getResources().getString(R.string.loading_empty));
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);


    }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            //output = new FileOutputStream("/sdcard/file_name.extension");


            File cacheFile = new File(this.context.getCacheDir(), "FIRMWARE");

            output = new FileOutputStream(cacheFile);

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }


    //метод выше (doInBackground) запускается отдельным поток все сотальное ниже в главном потоке
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                getClass().getName());
        mWakeLock.acquire();
        progressShow=1;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
        this.progress=progress[0];
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        progressShow=1;
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
    }


}

如果您只想下载 activity 中的文件,请将 AsyncTask 设为 activity 中的内部 class 并使用它。

但是如果你想下载文件而不考虑Activity,创建一个服务并在服务中实现下载逻辑并显示来自服务的文件下载进度通知并用下载百分比更新它,就像玩商店应用下载进度。

你的第二个问题如果用户在下载过程中改变电流Activity会发生什么?

是的,Async Task 将 运行 即使在 activity 被销毁后,直到它完成它的工作。查看此 link 了解更多信息