Android:Device 2.3.3运行良好。但Device 4.0.3不起作用。加载图片

时间:2014-03-17 04:00:17

标签: android

Android:Device 2.3.3运行良好。但Device 4.3(HTC One),4.2.2不起作用。加载图片

'public static Bitmap getBitmapFroUrl(String url){

    URL m;
    InputStream i = null;
    BufferedInputStream bis = null;
    ByteArrayOutputStream out =null;
    try {
        m = new URL(url);
        URLConnection connection = m.openConnection();
        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                i = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        bis = new BufferedInputStream(i,1024 * 8);
        out = new ByteArrayOutputStream();
        int len=0;
        byte[] buffer = new byte[1024];
        while((len = bis.read(buffer)) != -1){
            out.write(buffer, 0, len);
        }
        byte[] data = out.toByteArray();  
        out.close(); 
        bis.close();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);        
        return bitmap;
    } catch (Exception e) {
        return null;
    }

}'

我不知道为什么?请帮我。谢谢!

我知道:Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,options);

bitmap = null(4.2.2,4.3)

位图不为空(2.3.3)

2 个答案:

答案 0 :(得分:0)

您似乎在UI线程上使用网络。您需要在其他线程中访问网络。看看AsyncTask

答案 1 :(得分:0)

试试这个:

记得添加这些权限:

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

class BitmapGetter extends AsyncTask<String, Integer, Drawable> {
    @Override
    protected Drawable doInBackground(String... params) {
        Drawable bmpRet = null;
        try {
            BufferedInputStream in = new BufferedInputStream(new URL(params[0]).openStream());
            bmpRet = new BitmapDrawable(getResources(), BitmapFactory.decodeStream(in));
            in.close();
        } catch (Exception e) {return null;}
        return bmpRet;
    }

    public void onPostExecute(Drawable result) {
        try {
            (findViewById(R.id.imageView1)).setBackgroundDrawable(result);
        } catch (Exception ex) {}
    }
}

并从Main类执行它:

    new BitmapGetter().execute("http://i.stack.imgur.com/MuhXg.jpg");