无法在移动网络上使用AsyncTask下载任何文件

时间:2017-05-01 07:52:15

标签: android android-asynctask httpurlconnection

我有一个用于下载JSON文件的AsyncTask方法。下载后,在postExecute上填充我的列表视图。

我的问题是,当我连接到移动网络时,此方法无效。我已尝试使用不同的手机,或者它会被卡在ProgressDialog微调器中,或者在postExecute上解除ProgressDialog后它将不会显示任何内容。

但是当手机连接到wifi网络时,它很好,我会得到我的结果。

方式

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

    private PowerManager.WakeLock mWakeLock;
    private FileOutputStream out = null;
    private File filename = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,getClass().getName());
        mWakeLock.acquire();
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setTitle("Preparing List...");
        mProgressDialog.setMessage("Please wait while list is populating...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(100);
        mProgressDialog.show();
        mProgressDialog.setContentView(R.layout.custom_progressdialog);
        ProgressBar progressbar=(ProgressBar)mProgressDialog.findViewById(R.id.pbar);
        progressbar.getIndeterminateDrawable().setColorFilter(Color.parseColor("#FF4081"), android.graphics.PorterDuff.Mode.SRC_IN);
    }


    @Override
    protected String doInBackground(String... image_urls) {
        InputStream input = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(image_urls[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }
            int fileLength = connection.getContentLength();
            input = connection.getInputStream();
            Log.i("in save()", "after mkdir");
            filename = new File(path+offlineJsonFileName +".txt");
            Log.i("in save()", "after file");
            out = new FileOutputStream(filename);
            Log.i("in save()", "after outputstream");
            out.flush();
            out.close();
            Log.i("in save()", "after outputstream closed");
            out = new FileOutputStream(filename);
            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                out.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (out != null)
                    out.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }
            if (connection != null)
                connection.disconnect();
        }
        return null;
    }
    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
    }
    @Override
    protected void onPostExecute(String args) {
        mWakeLock.release();
        mProgressDialog.dismiss();
            ReadFile();
    }
}

我按照这样执行:

jsonDownloader = new JsonDownloader();
jsonDownloader.execute(url);

2 个答案:

答案 0 :(得分:0)

        out.flush();
        out.close();
        Log.i("in save()", "after outputstream closed");
        out = new FileOutputStream(filename);

删除所有。为什么关闭并重新打开输出流?

完成写作后,请执行flush()。

答案 1 :(得分:0)

我通过以下方式使其成功

class JsonDownloaderNew extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        System.out.println("Starting download");
        mProgressDialog = new ProgressDialog(activity);
        mProgressDialog.setTitle("Preparing List...");
        mProgressDialog.setMessage("Please wait while list is populating...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(100);
        mProgressDialog.show();
        mProgressDialog.setContentView(R.layout.custom_progressdialog);
        ProgressBar progressbar=(ProgressBar)mProgressDialog.findViewById(R.id.pbar);
        progressbar.getIndeterminateDrawable().setColorFilter(Color.parseColor("#FF4081"), android.graphics.PorterDuff.Mode.SRC_IN);
    }

    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            System.out.println("Downloading");
            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
            File filename = new File(path+offlineJsonFileName +".txt");
            OutputStream output = new FileOutputStream(filename);
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // 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;
    }
    @Override
    protected void onPostExecute(String file_url) {
        System.out.println("Downloaded");
        mProgressDialog.dismiss();
        ReadFile();
    }
}