Android 根据网络图片URL转Bitmap对象

Android 4.0之后不能在主线程中做网络请求

我找了很多方法,才解决
Android之NetworkOnMainThreadException异常

是指不能在主线程中做网络请求

代码如下:

 new Thread(new Runnable() {
            Bitmap bitmap = null;

            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL("http://test.zuihou99.com" + urls);
                    InputStream is = null;
                    BufferedInputStream bis = null;
                    try {
                        is = url.openConnection().getInputStream();
                        bis = new BufferedInputStream(is);
                        bitmap = BitmapFactory.decodeStream(bis);

                        boolean isSaveSuccess = ImgUtils.saveImageToGallery(getApplicationContext(), bitmap);
                        if (isSaveSuccess) {
                            Looper.prepare();
                            Toast.makeText(getApplicationContext(), "保存图片成功", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        } else {
                            Looper.prepare();
                            Toast.makeText(getApplicationContext(), "保存图片失败,请稍后重试", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }).start();
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页