【问题标题】:Android : Device 2.3.3 work well. But Device 4.0.3 don't work. Load ImageAndroid:设备 2.3.3 运行良好。但是设备 4.0.3 不起作用。加载图像
【发布时间】:2014-03-17 04:00:16
【问题描述】:

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

'公共静态位图 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;
    }

}'

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

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

位图 = null (4.2.2, 4.3)

位图不为空(2.3.3)

【问题讨论】:

    标签: android


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      试试这个:

      记得添加这些权限:

      <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) {}
          }
      }
      

      并从主类执行:

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

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 1970-01-01
      相关资源
      最近更新 更多