【问题标题】:Why Android 4 doesn't download and show images from url为什么 Android 4 不从 url 下载和显示图像
【发布时间】:2012-12-05 12:55:57
【问题描述】:

这是一个用于加载图像的简单功能。它在 android 2.2 上运行良好,但它不会下载和显示任何适用于 android 4 的图像。 这是创建代码:

Bitmap bitmap = DownloadImage(weather.icon);
holder.imgIcon.setImageBitmap(bitmap);

支架工作正常 / 这是功能:

    private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

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

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        throw new IOException("Error connecting");
    }
    return in;
}

private Bitmap DownloadImage(String URL) {
    Bitmap bitmap = null;
    InputStream in = null;

    try {
        in = OpenHttpConnection(URL);
        BufferedInputStream bis = new BufferedInputStream(in, 8190);

        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        byte[] imageData = baf.toByteArray();
        bitmap = BitmapFactory.decodeByteArray(imageData, 0,
                imageData.length);
        in.close();
    } catch (IOException e1) {

        e1.printStackTrace();
    }
    return bitmap;
}

谁能帮帮我,我累了。 谢谢

【问题讨论】:

    标签: android image url


    【解决方案1】:

    您正在主 UI thread 上运行 Network Rquest

    android>=3.0 不允许在主 UI 线程上运行 Network Request。你需要使用

    AsyncTask做网络操作。 (下载图片,你的情况)

    【讨论】:

      【解决方案2】:
      private class DownloadFile extends AsyncTask<String, Integer, String> {
      ProgressDialog mProgressDialog;
      
      @Override
          protected void onPreExecute() {
              super.onPreExecute();
              // Create progress dialog
              mProgressDialog = new ProgressDialog(Your Activity.this);
              // Set your progress dialog Title
              mProgressDialog.setTitle("title");
              // Set your progress dialog Message
              mProgressDialog.setMessage(" message");
              mProgressDialog.setIndeterminate(false);
              mProgressDialog.setMax(100);
              mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
              // Show progress dialog
              mProgressDialog.show();
          }
      
      @Override
      protected String doInBackground(String... Url) {
          String filename = "image.jpg";
          try {
              URL url = new URL(mStrings[curruntPosition]);
              URLConnection connection = url.openConnection();
              connection.connect();
      
              // Detect the file length
              int fileLength = connection.getContentLength();
      
              // Locate storage location
              String filepath = Environment.getExternalStorageDirectory()
                      .getPath();
      
              // Download the file
              InputStream input = new BufferedInputStream(url.openStream());
      
              // Save the downloaded file
              OutputStream output = new FileOutputStream(filepath + "/"
                      + filename);
      
              // String fileName = "picss.jpg";
      
              byte data[] = new byte[1024];
              long total = 0;
              int count;
              while ((count = input.read(data)) != -1) {
                  total += count;
                  // Publish the progress
                  publishProgress((int) (total * 100 / fileLength));
                  output.write(data, 0, count);
              }
      
              // Close connection
              output.flush();
              output.close();
              input.close();
      
          } catch (Exception e) {
              // Error Log
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
      
          return null;
      }
      
      @Override
      protected void onProgressUpdate(Integer... progress) {
          super.onProgressUpdate(progress);
          // Update the progress dialog
          mProgressDialog.setProgress(progress[0]);
          // Dismiss the progress dialog
          mProgressDialog.dismiss();
      
      }
      

      }

      然后将以下代码放入您活动的下载按钮中。

      new DownloadFile().execute(your url);
      

      【讨论】:

        【解决方案3】:

        加入你的班级:

        在 Android Honeycomb StrictMode 已启用,将其关闭。

        使用Async Task进行网络操作。

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 
        

        阅读:
        https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

        【讨论】:

        • 是的,您可以通过这种方式修复它,但这只是禁用限制。您应该解决问题:在 UI 线程上下载。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2015-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多