活动中的两个下载任务

时间:2014-09-09 07:39:47

标签: android json android-asynctask connection

我在一项活动中有4项任务。有两个任务,我从服务器获得了json信息。这两项任务正常。

在另外两个任务中,首先我用这段代码下载了一些文件:

class DownloadImageTask extends AsyncTask<String, Void, String> {
    List<DownloadResourcesUrls> complete_res_url = new ArrayList<DownloadResourcesUrls>();
    int current = 0;

    public DownloadImageTask(List<DownloadResourcesUrls> url_dir) {
        complete_res_url = url_dir;
    }

    protected String doInBackground(String... urls) {
        int count;
        InputStream input = null;
        String f_path = "mypath";
        URLConnection conection = null;
        while (current < complete_res_url.size()) {
            try {
                URL url = new URL(complete_res_url.get(current).getCompleted_res());
                conection = url.openConnection();
                conection.connect();

                input = new BufferedInputStream(url.openStream(), 8192);
                output = new FileOutputStream(f_path);
                byte data[] = new byte[4096];


                while ((count = input.read(data)) != -1) {
                    if (isCancelled()) {
                        output.close();
                        conection = null;
                        input.close();
                        return null;
                    }

                    output.write(data, 0, count);
                }
                //show = true;
                current++;

                output.flush();

                // closing streams
                output.close();
                input.close();
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }
                if (conection != null)
                    conection = null;
            }
        }
        return f_path;
    }

    protected void onPostExecute(String result) {

    }

    protected void onPreExecute() {

    }
}

我的上一个任务有这个代码:

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

    private Context context;
    private PowerManager.WakeLock mWakeLock;
    int lenghtOfFile = 0;
    public boolean STATUS = false;


    public DownloadTask(Context context, boolean status) {
        this.context = context;
        STATUS = status;
    }

    @Override
    protected String doInBackground(String... sUrl) {

        InputStream input = null;
        HttpURLConnection conection = null;
        BufferedOutputStream bout = null;
        FileOutputStream fos = null;
        int downloaded = 0;

        try {
            URL url = new URL(sUrl[0]);
            conection = (HttpURLConnection) url.openConnection();
            int lenghtOfFile = conection.getContentLength();

            conection.disconnect();
            conection = (HttpURLConnection) url.openConnection();

            if(STATUS) {
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/myfile.extension");
                if (file.exists()) {
                    downloaded = (int) file.length();
                    conection.setRequestProperty("Range", "bytes=" + (file.length()) + "-");
                    //conection.connect();
                }
            }
            else {
                conection.setRequestProperty("Range", "bytes=" + downloaded + "-");
                //conection.connect();
            }
            conection.setDoInput(true);
            conection.setDoOutput(true);
            input = new BufferedInputStream(url.openStream());
            fos=(downloaded==0)? new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/myfile.extension"): new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/myfile.extension",true);
            bout = new BufferedOutputStream(fos, 1024);
            byte data[] = new byte[1024];

            long total = 0;
            int count = 0;
            while ((count = input.read(data, 0, 1024)) >= 0) {
                if (isCancelled()) {
                    input.close();
                    return null;
                }


                // publishing the progress....
                // After this onProgressUpdate will be called

                bout.write(data, 0, count);
                downloaded += count;
                publishProgress((int)(downloaded * 100/ lenghtOfFile) );
                total += count;
            }

            // flushing output
            bout.flush();

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

} catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        } finally {
            try {
                if (conection != null)
                    conection.disconnect();
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
                if (fos != null)
                    fos.close();
                if (bout != null)
                    bout.close();
            } catch (IOException ignored) {
            }

            /*if (conection != null)
                conection = null;*/
            if (conection != null)
                conection.disconnect();
        }

        return null;
    }

    protected void onPostExecute(String result) {

    }

    protected void onPreExecute() {

    }

最后,我在两个按钮OnClick事件中执行了这两个任务,如下所示:
第一个按钮:

downloadImageTask = new DownloadImageTask(resources_urls);

btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                      downloadImageTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    else
                      downloadImageTask.execute();
            });

第二个按钮:

downloadTask  = new DownloadTask(MyActivity.this, false);
btnfull.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        downloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mydownloadurl);
                    else
                        downloadTask.execute(mydownloadurl);
                }
            });

第一个按钮任务正常工作。第二个按钮任务正确下载了我的文件,但我无法更新我的进度条,因为conection.getContentLength()返回-1。

注1 :如果我首先启动第二个按钮任务,conection.getContentLength()将返回正确的文件大小。

Note2 :第一个和第二个按钮任务在我的第一个asynctask 4task的onPostExecute()方法中定义和执行,它从服务器获取JSON信息并在上面提到。

提前谢谢。

0 个答案:

没有答案