Android 5.0:android.os.NetworkOnMainThreadException试图获取Bitmap对象时

时间:2014-12-30 20:04:57

标签: android android-asynctask

当我编写我的android项目时,我需要使用URL加载一个位图对象。 运行以下代码时抛出异常:

Bitmap bm = GetLoginUserInfoUtil.getBitmap(object.getString("profile_image_url"));

例外:

12-30 21:01:14.440: W/System.err(6025): android.os.NetworkOnMainThreadException
12-30 21:01:14.440: W/System.err(6025): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)

这是我的方法getBitmap:

public static Bitmap getBitmap(String biturl) {

    Bitmap bitmap=null;

    try {
        URL url = new URL(biturl);

        URLConnection conn = url.openConnection();
        InputStream in = conn.getInputStream();
        bitmap = BitmapFactory.decodeStream(new BufferedInputStream(in));

    } 
    catch (Exception e) {

        e.printStackTrace();
    }
    return bitmap;


}

我发现了类似的关于android.os.NetworkOnMainThreadException的问题,最推荐的解决方案是使用AsyncTask。

如何在我的类GetLoginUserInfoUtil中实现AsyncTask?

编辑: 这是我加载位图文件的原始方法:

public static void reqUserInfo(final Oauth2AccessToken accessToken, long uid) {

    user = new LoginUserInfo();
    UsersAPI userapi = new UsersAPI(accessToken);

    userapi.show(uid, new RequestListener() {

        public void onComplete(String arg0) {

            JSONObject object;

            try {
                object = new JSONObject(arg0);

                Bitmap bm = GetLoginUserInfoUtil.getBitmap(object.getString("profile_image_url"));
                GetLoginUserInfoUtil.user.setUserIcon(bm);
                GetLoginUserInfoUtil.user.setIsDefault("0");
                GetLoginUserInfoUtil.user.setToken(accessToken.getToken());
                GetLoginUserInfoUtil.user.setUserName(object.getString("screen_name"));

            } 
            catch (JSONException e) {

                e.printStackTrace();
            }


        }

现在我在类中添加了建议的AsyncTask:

private class GetBitmapTask extends AsyncTask<String, Void, Bitmap> {

    @Override
    protected Bitmap doInBackground(String... params) {
        return GetLoginUserInfoUtil.getBitmap(params[0]);
    }

    @Override
    protected void onPostExecute(Bitmap result) {

        GetLoginUserInfoUtil.user.setUserIcon(result);
    }

}

在onComplete中,我添加了:

new GetBitmapTask().execute(object.getString("profile_image_url"));

但我收到了错误:

No enclosing instance of type GetLoginUserInfoUtil is accessible. Must qualify the allocation with an enclosing instance of type 
GetLoginUserInfoUtil (e.g. x.new A() where x is an instance of GetLoginUserInfoUtil).

1 个答案:

答案 0 :(得分:0)

private class GetBitmapTask extends AsyncTask<String, Void, Bitmap> {

    @Override
    protected Bitmap doInBackground(String... params) {
        return GetLoginUserInfoUtil.getBitmap(params[0]);
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        bm = result;
    }

}

使用它:

new GetBitmapTask(object.getString("profile_image_url")).execute();