Android:从类访问线程

时间:2015-03-14 09:05:06

标签: android multithreading

我从网站

创建文件下载

此代码有效,但在我转到主页后,如何访问线程和此监听器?

filedownloader.java

public class FileDownloader {

    public static void download(final String downloadPath, final String filepath, final OnProgressDownloadListener listener) {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    URL url = new URL(downloadPath);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    //connection.setDoOutput(true);
                    connection.connect();

                    int fileSize = connection.getContentLength();

                    File file = new File(filepath);
                    if (file.exists()) {
                        file.delete();
                    }

                    FileOutputStream outputStream = new FileOutputStream(filepath);
                    InputStream inputStream = connection.getInputStream();
                    byte[] buffer = new byte[G.DOWNLOAD_BUFFER_SIZE];
                    int len = 0;
                    int downloadedSize = 0;
                    while ((len = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, len);
                        downloadedSize += len;
                        final float downloadPercent = 100.0f * (float) downloadedSize / fileSize;

                        if (listener != null) {
                            G.HANDLER.post(new Runnable() {

                                @Override
                                public void run() {
                                    listener.onProgressDownload((int) downloadPercent);
                                }
                            });
                        }
                    }

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

        });
        thread.start();
    }
}

onprogressdownloadlistener.java

public interface OnProgressDownloadListener {

    public void onProgressDownload(int percent);
}

mainactivity.java

OnProgressDownloadListener listener = new OnProgressDownloadListener() {

     @Override
     public void onProgressDownload(final int percent) {
           Log.i(percent + "%");
     }
};
FileDownloader.download(dlFile, G.DIR_APP + "/" + fileName, listener);

下载返回大小百分比

开始下载并关闭页面并转到新页面后,我想返回下载页面。如何访问这个线程和监听器?

由于

1 个答案:

答案 0 :(得分:0)

- 您可以检查主要活动的侦听器对象中的 百分比 是否得到" 100%"那么你可以得到你想要的输出。