UI는 UI Thread에게.

2012. 8. 20. 22:27

Only the original thread that created a view hierarchy can touch its views.

다른 Thread에서 UI에 access 하려고 하면 위와 같은 에러가 발생한다.

다시 말해 UI Thread에서 UI를 처리하란 소리인데

그 해결책은 여러가지가 있을 수 있겠지만... 

아래의 간단한 방법을 메모한다.


당연하겠지만, 아래 handler는 UI Thread에서 생성이 되어여 UI Thread에 bounding되어 작업할 수 있다.

    // Define the Handler that receives messages from the thread

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {

            Bundle data = msg.getData();

            String result = data.getString("data");

            tw.setText(result);

        }

    };


아래 함수가 다른 Thread에 의해 호출된 함수이다. 

여기에서 UI Thread에서 작업할 수 있도록 handler를 통해 Message를 보내야 한다.

    public void onChanged(Object data) {

        // TODO Auto-generated method stub

        Bundle b = new Bundle();

        b.putString("data", (String)data);

        Message msg = handler.obtainMessage();

        msg.setData(b);

        handler.sendMessage(msg);

    }

    


'관심거리 > Android' 카테고리의 다른 글

Google Navigation 실행  (0) 2012.08.21
startManagingCursor()  (2) 2012.02.26
아는만큼만 말할 수 있다  (0) 2012.02.26

+ Recent posts