【问题标题】:Android async get imageAndroid异步获取图像
【发布时间】:2018-03-19 14:49:42
【问题描述】:

我尝试从输入流 URL 解码为 bipmap

公共类 Presenter 实现 MVPmain.presenter {

String LOG_TAG = "Presenter: ";

private final MVPmain.view view;
String url = "https://jsonplaceholder.typicode.com/";

public Presenter(MVPmain.view view) {
    this.view = view;
}


void photosUrl() {
        String photoUrl = "http://placehold.it/600/92c952";
        AsyncLoadImage asyncLoadImage = new AsyncLoadImage();
        asyncLoadImage.execute(photoUrl);
    }
}

@Override
public void button_photos_clicked() {
    photosUrl();
}

Bitmap loadImage(String url) {
    Bitmap bitmapImage = null;
    URL imageUrl = null;
    HttpURLConnection httpURLConnection = null;
    try {
        imageUrl = new URL(url.replaceAll("\\r|\\n", ""));
        httpURLConnection = (HttpURLConnection) imageUrl.openConnection();
        bitmapImage = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
        Log.d(LOG_TAG, "Runneble: " + "OK");
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "image url error: " + e);
        e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return bitmapImage;
}


class AsyncLoadImage extends AsyncTask<String, Void, Bitmap> {
    String LOG_TAG = "AsyncLoadImage: ";
    Bitmap bitmapImage;

    @Override
    protected Bitmap doInBackground(String... strings) {
        String request = "";
        final URL imageUrl = null;
        JSONObject jsonObject = null;
        for (final String address : strings) {
            Log.d(LOG_TAG, "img url: " + address);
            bitmapImage = loadImage(address);

        }
        return bitmapImage;
    }

    @Override
    protected void onPostExecute(Bitmap bitmapImg) {
            view.setPhotos(bitmapImg);
    }

}

}

这是代码的一部分,我得到异常:httpURLConnection.getInputStream() 中的连接被拒绝。我尝试 .getContent 并得到这个错误。 请告诉我,我该怎么做。

已解决 AdWay 出现此错误!)

【问题讨论】:

标签: android bitmap android-asynctask


【解决方案1】:

您的代码在我的设备上运行良好。

确保您的互联网连接正常工作,并直接从您的 android 设备的浏览器中打开图像 URL,以验证您是否有权访问该 URL。

【讨论】:

  • 手机上的 chrome 我可以打开这张图片。但从我的应用程序没有。错误截图:i.stack.imgur.com/3vwlK.png
  • 在其他设备上测试。这可能是特定于设备的问题。
  • 你说得对!在虚拟设备上代码是有效的......我之前在我的 nexus 5 7.1.2 上尝试过
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
相关资源
最近更新 更多