在Asynctask中为onProgressUpdate使用2个不同类的任何示例?

时间:2013-09-25 04:04:34

标签: java android android-asynctask

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

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

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

非常感谢!

2 个答案:

答案 0 :(得分:0)

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

或者,如果您传递一个可以解析的字符串并获得所需的值,该怎么办?如果你拿第一个字符串+ =“:”+ int,那么使用像

这样的东西
String myString = passedString.substring(0, passedString.lastIndexOf(":")))
int i = Integer.parseInt(passedString.substring(passedString.lastIndexOf(":")+1));

答案 1 :(得分: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();
}

此致

沙迪亚