java - 下载照片时遇到问题

标签 java android image android-asynctask urlconnection

我写了一个程序 从网址下载照片... 但我有一个问题... 一些照片已下载。 而且没有任何问题。

但是有些图片无法完整下载:( 在文件管理器中我查看 它被打破 你能帮忙吗?

我的代码是:

公共(public)类 DownloadFileFromURL_img 扩展了 AsyncTask {

    private viewHolderPost holderPOST;

    public DownloadFileFromURL_img(viewHolderPost holderPOST) {
        Log.d(TAG, "DownloadFileFromURL_img: ");
        this.holderPOST = holderPOST;

    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    /**
     * Downloading file in background thread
     */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {

            File file = new File(Environment.getExternalStorageDirectory(), "98Diha/img");

            if (!file.exists()) {
                if (!file.mkdirs()) {

                    file.createNewFile();
                }
            }



            InputStream input = null;
            int response = -1;

            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();

            if (!(conection instanceof HttpURLConnection))
                throw new IOException("Not an HTTP connection");

            try{
                HttpURLConnection httpConn = (HttpURLConnection) conection;
                httpConn.setAllowUserInteraction(false);
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.connect();

                response = httpConn.getResponseCode();
                if (response == HttpURLConnection.HTTP_OK) {
                    input = httpConn.getInputStream();
                }
            }
            catch (Exception ex)
            {
                throw new IOException("Error connecting");
            }






            int lenghtOfFile = conection.getContentLength();



             input = new BufferedInputStream(url.openStream());


            String imgS[] = f_url[0].split("/");
            String name = imgS[imgS.length - 1];



            String path = Environment
                    .getExternalStorageDirectory().toString()
                    + "/98diha/img/" + name;


            File filePath = new File(path);

            if (!filePath.exists()) {

                OutputStream output = new FileOutputStream(path);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;


                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));


                    output.write(data, 0, count);
                }


                output.flush();


                output.close();
                input.close();

            } else {
                SSToast(context, "Exist!");

                holderPOST.dowload_img.setVisibility(View.GONE);
                holderPOST.setWallpaper.setVisibility(View.VISIBLE);
                holderPOST.setWallpaper.setText(context.getString(R.string.set_wp));


                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    holderPOST.setWallpaper.setTextColor(ContextCompat.getColor(context, R.color.Teal_400));
                } else {
                    holderPOST.setWallpaper.setTextColor(context.getResources().getColor(R.color.Teal_400));
                }
            }

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

        return null;
    }

    /**
     * Updating progress bar
     */
    protected void onProgressUpdate(String... progress) {

        holderPOST.dowload_img.setVisibility(View.GONE);
        holderPOST.setWallpaper.setVisibility(View.VISIBLE);
        holderPOST.setWallpaper.setText(context.getString(R.string.dowloading));


    }

    /**
     * After completing background task Dismiss the progress dialog
     **/
    @Override
    protected void onPostExecute(String file_url) {


        holderPOST.setWallpaper.setText(context.getString(R.string.set_wp));
        holderPOST.setWallpaper.setTextColor(context.getResources().getColor(R.color.Teal_400));

        Log.d(TAG, "onPostExecute: ");
    }

}

最佳答案

而不是使用 AsyncTask 从 URL 下载图像。您可以使用诸如Glide之类的库或Picasso只需一行即可快速完成。但如果您不想使用库,则可以使用 DownloadManager下载它并将其保存在文件中。您可以查看这个tutorial或网上其他有关 DownloadManager 实现的教程。

关于java - 下载照片时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56855048/

相关文章:

java - 如何模拟一个 void 方法,该方法采用模拟对象并期望为模拟对象实例设置一些值

android - 如何获取 'PCL' 版本的 Nodatime?

image - Rust + Rust 图像 - 私有(private) 'Associated Type' ?

java - 如何将每个 RDD 分区限制为仅 'n' 条记录?

Java线程池求解单个结果

java - 寻找 Dagger 辅助注入(inject)的示例

java - 在 facebook android sdk 中处理传入通知中的请求 ID 为空

android - 在回调中使用正确的上下文

android - SimpleDraweeView 在 fresco 中缩放图像后不调整大小

css - 在其他图形之前加载背景图像