0

我一直在寻找这个地方,我唯一的答案是“使用配对”,但我也无法让它工作。

这是我需要做的: 在 Asynctask 中,我需要更新进度条和文本。因此,我的 Asynctask 泛型不能只是 Integer 而不仅仅是 String,而是两者兼而有之。这样我就可以在“onProgressUpdate”方法中同时拥有这两个类。

有人可以给我一些示例或链接,说明如何在“doInBackground”中添加字符串并增加整数,以及如何在“onProgressUpdate”中实现这一点?

非常感谢你!

4

2 回答 2

0

你能创建自己的简单类来保存变量然后传递它吗?

或者,如果您传递一个可以解析并获取所需值的字符串怎么办?如果您使用第一个字符串 += ":" + int,则使用类似

String myString = passedString.substring(0, passedString.lastIndexOf(":")))
int i = Integer.parseInt(passedString.substring(passedString.lastIndexOf(":")+1));
于 2013-09-25T04:09:40.310 回答
0

据我了解您的问题;您主要想做两件事:

1) 在 doIneBackground() 中处理 UI 线程。2) 实现onProgressUpdate()。

基本上我们不应该在后台进程运行时尝试访问 UI 线程。原因很清楚...@ OS 级别会有很多线程在运行。在这种情况下,如果我们可以从后台线程更新 UI,屏幕上会很混乱。

对于第二个,我想建议你看看这个例子:

ProgressDialog mProgressDialog;
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
    @Override
    public void onCancel(DialogInterface dialog) {
        downloadTask.cancel(true);
    }
});

在 AsynTask 中:

private class DownloadTask extends AsyncTask<String, Integer, String> {

private Context context;

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

@Override
protected String doInBackground(String... sUrl) {
    // 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);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
         getClass().getName());
    wl.acquire();

    try {
        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");

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled())
                    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();
        }
    } finally {
        wl.release();
    }
    return null;
}}

上面的方法(doInBackground)总是在后台线程上运行。你不应该在那里做任何 UI 任务。另一方面,onProgressUpdate 和 onPreExecute 在 UI 线程上运行,因此您可以更改进度条:

 @Override
protected void onPreExecute() {
    super.onPreExecute();
    mProgressDialog.show();
}

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

@Override
protected void onPostExecute(String result) {
    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();
}

问候

沙迪亚

于 2013-09-25T04:57:37.663 回答