woong's

Android Handler 사용하기 본문

Develop/Android

Android Handler 사용하기

dlsdnd345 2016. 2. 14. 00:26
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Android Handler 사용하기


안녕하세요 . 오늘은 Activity 사 아닌 Class 에서 Handler 를 사용하는 방법에 대해서  

말씀 드리겠습니다 .


Web Socket 을 공부하다 보니 MainThread 가 아닌 곳에서 UI 를 접근 하는 경우가 발생했습니다 .


그 경우에 Handler 로 처리 하지 않으면 아래와 같은 경고를 받게 됩니다 .



android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

 

이와 같은 경고를 받게 됩니다 . 


이 경고는 MainThread 에서 UI 를 접근 하지 않은 경우에 발생하는 경고 Exception 입니다 .


이 경우에 Handler 를 통해서 해결하면 될 것 같습니다 .


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    private void deliveryMassage(String massage) {
        Message msg = Message.obtain(mHandler, MSG_MESSAGE);
        Bundle bundle = new Bundle ();
        bundle.putString(MESSAGE, massage);
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }
 
    private final Handler mHandler = new Handler ( new Handler.Callback() 
    {    
        @Override
        public boolean handleMessage(Message message) {
            Bundle bundle = message.getData();
            if ( message.what == MSG_MESSAGE )
            {
                String rawMsg = bundle.getString(MESSAGE);
                responseMessageTextMain.setText(rawMsg);
            }
            return false;
        }
    });
 

 

 

Handler 를 사용하면 코드가 지저분해서 메서드화 시켜 보았습니다 .


deliveryMassage 는 String Data 를 Handler Message 화 시켜 보내게 되는 부분 입니다 .


이렇게 전달된 Message 는 


public boolean handleMessage(Message message)


message 부분으로 전달이 됩니다 .


전달된 message 에서 Data 를 받아 Android UI 에 접근하면 위에서 보신 거와 같은 경고를 피하실 수 있습니다 .


Comments