获取远程图片导致android中的NetworkOnMainThreadException

时间:2012-05-04 09:20:43

标签: android facebook get image

首先,抱歉我的英语不好。

我试图创建一个使用官方Facebook API连接到Facebook的简单Android应用程序。当用户登录并授权我的应用时,我想获取他/她的用户名和个人资料图片,然后显示在我的应用中。我已经采用了Facebook API附带的Hackbook示例应用程序中的一些代码。这是我在主要活动课程中的代码。

public class SocialApp2Activity extends Activity {
    private Handler handler;

    private Facebook facebook;
    private AsyncFacebookRunner asyncRunner;

    private TextView text;
    private ImageView imgUserPic;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        handler = new Handler();

        text = (TextView) findViewById(R.id.txt);
        imgUserPic = (ImageView) findViewById(R.id.user_pic);

        facebook = new Facebook("MY_FB_APP_ID");
        asyncRunner = new AsyncFacebookRunner(facebook);

        facebook.authorize(this, new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
                Bundle params = new Bundle();
                params.putString("fields", "name, picture");
                asyncRunner.request("me", params, new UserRequestListener());
            }

            ... 

        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        facebook.authorizeCallback(requestCode, resultCode, data);
    }


    /* Callback for fetching username and profile picture */
    public class UserRequestListener implements RequestListener {

        @Override
        public void onComplete(final String response, final Object state) {

            JSONObject jsonObject;

            try {
                jsonObject = new JSONObject(response);

                final String picURL = jsonObject.getString("picture");
                final String name = jsonObject.getString("name");

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        text.setText(name);

                        /********************************
                         *** This line cause an error ***
                         ********************************/
                        imgUserPic.setImageBitmap(Utility.getBitmap(picURL));

                    }
                });
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        ...
    }
}

我在调用自己的方法时遇到错误,该方法从远程服务器读取配置文件图片的位图数据。错误是NetworkOnMainThreadException,并且有一些堆栈跟踪在这里。

05-04 14:37:28.898: W/System.err(1117): android.os.NetworkOnMainThreadException
05-04 14:37:28.905: W/System.err(1117):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
05-04 14:37:28.905: W/System.err(1117):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
...
05-04 14:37:29.005: W/System.err(1117):     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164)
05-04 14:37:29.005: W/System.err(1117):     at promlert.socialapp2.Utility.getBitmap(Utility.java:26)
05-04 14:37:29.016: W/System.err(1117):     at promlert.socialapp2.SocialApp2Activity$UserRequestListener$1.run(SocialApp2Activity.java:95)
...

您能否告诉我如何解决此问题。感谢

1 个答案:

答案 0 :(得分:1)

handler.post(Runnable runnable)正在UI线程上执行runnable。因此,如果您尝试在UI线程上执行网络操作 - 您将获得此异常。避免这种情况:首先调用Utility.getBitmap(picURL)而不是从UI线程调用,然后在UI线程上只发布imgUserPic.setImageBitmap()方法:

new Thread(new Runnable() {

                @Override
                public void run() {
                    //this line must be called not from the UI  thread
                final Bitmap bitmap = Utility.getBitmap(picURL)
                handler.post(new Runnable() {
                @Override
                public void run() {
                                   text.setText(name);
                                   imgUserPic.setImageBitmap(bitmap );

                                  }
                  });   
                }
}).start();