使用Handler更新水平ProgressDialog,同时从Web加载图像

时间:2016-11-02 09:52:12

标签: java android progressdialog android-progressbar

是否可以使用Handler(我故意不想使用AsyncTask)更新水平(确定)ProgressDialog,同时从Web加载图像?如果是的话,我该怎么做?

这是try块:

URL url = new URL(link);
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
if(httpCon.getResponseCode()!=200) return;
InputStream inputStream = httpCon.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);

2 个答案:

答案 0 :(得分:0)

是的,这是可能的。您可以通过Message类传递数据并以handleMessage(Message msg) Handler方式获取数据,例如这种方式(msg.arg1 - 已下载字节,msg.arg2 - 总字节数下载):

final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Downloading Image ...");
progressDialog.setMessage("Download in progress ...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
progressDialog.setMax(100);
progressDialog.show();

final Handler downloadProgressHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        progressDialog.setProgress(100 * msg.arg1 / msg.arg2);
        if (progressDialog.getProgress() == progressDialog.getMax()) {
            progressDialog.dismiss();
        }
    }
};

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            URL url = new URL("<your_url>");
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            int totalSize = urlConnection.getContentLength();
            ByteArrayOutputStream receivedBytesStream = new ByteArrayOutputStream();
            int downloadedSize = 0;
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0 ) {
                receivedBytesStream.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                Message msg = new Message();
                msg.arg1 = downloadedSize;
                msg.arg2 = totalSize;
                downloadProgressHandler.sendMessage(msg);
            }
            receivedBytesStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}).start();

或者,如果您不想通过msg.arg1msg.arg2发送数据,您可以创建自定义对象并将其添加到msg.obj = new YourCustomObjectClass() // or any other object之类的消息中。您可以使用handleMessage(Message msg)这样的方法获取它:YourCustomObjectClass obj = (YourCustomObjectClass) msg.obj;

答案 1 :(得分:0)

不是直接将InputStream解码为位图,而是将文件下载到设备中的任何路径。并且从asynchtask的onProgressUpdate方法,您可以更新进度。下载文件后,打开文件并设置为imageview。

例如Asynchtask

WHERE C.FirstName like coalesce(@FirstName + '%' , C.FirstName)
    AND C.LastName like coalesce(@LastName + '%' , C.LastName)
    etc.

你可以用

来调用它
class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream to write file
            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
   }

    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissDialog(progress_bar_type);

        // Displaying downloaded image into image view
        // Reading image path from sdcard
        String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
        // setting downloaded into image view
        my_image.setImageDrawable(Drawable.createFromPath(imagePath));
    }

}