Android完成活动后显示下载进度

时间:2015-08-15 10:30:31

标签: multithreading android-activity android-asynctask android-progressbar activity-finish

您好,在我的聊天应用程序中,我一直在从listview下载媒体文件。我曾使用thead进行下载操作。它工作正常,并显示我们保持相同活动时的进度状态。如果我们完成了活动并再来一次,我怎么能显示从上一个位置下载的进度。我可以看到下载发生在后台,但我需要在UI中显示该状态..是否有可能与线程...我需要使用任何其他方法..?

我尝试过正常的线程..是不是Asynchtask可以做必要的..?

1 个答案:

答案 0 :(得分:0)

This is my thread 


@Override
    public void run() {
        try {

            URL url = new URL(task.url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            connection.setReadTimeout(1000);
            if (chunk.end != 0) // support unresumable links
                connection.setRequestProperty("Range", "bytes=" + chunk.begin + "-" + chunk.end);

            connection.connect();
            File cf = new File(FileUtils.address(task.save_address, String.valueOf(chunk.id)));
            InputStream remoteFileIn = connection.getInputStream();
            FileOutputStream chunkFile = new FileOutputStream(cf, true);

            int len = 0;
            // set watchDoger to stop thread after 1sec if no connection lost
            watchDog = new ConnectionWatchDog(5000, this);
            watchDog.start();
            while (!this.isInterrupted() &&  
                    (len = remoteFileIn.read(buffer)) > 0) {

                watchDog.reset();
                chunkFile.write(buffer, 0, len);
                process(len);
            }

            chunkFile.flush();
            chunkFile.close();
            watchDog.interrupt();
            connection.disconnect();

            if (!this.isInterrupted()) {
                observer.rebuild(chunk);
            }


        }catch (SocketTimeoutException e) {
            e.printStackTrace();

            observer.connectionLost(task.id);
            puaseRelatedTask();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return;
    }

process(len) will send progress status to the UI using interface callbacks. 
相关问题