为什么Android 4不下载并显示来自网址的图片

时间:2012-12-05 12:55:57

标签: android image url

这是一个用于加载图像的简单功能。它在Android 2.2上工作正常,但它不下载并显示android 4的任何图像。 这是create:

上的代码
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;
}

任何人都可以帮助我,这让我很累。 谢谢

3 个答案:

答案 0 :(得分:1)

您正在主Network Rquest上投放UI thread

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

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

答案 1 :(得分:0)

在课堂上添加:

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

使用Async Task执行网络操作。

OR

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

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

答案 2 :(得分:0)

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);