nicole (안드로이드 무비플레이어 프로젝트명;;)을 만들면서 xml로딩과 같이 시간이 소요되는 작업들은 대부분 Thread로 소화했다. 그런데 Thread 작업중에 UI를 업데이트 하는 작업중 자주 보이는 err stack 내용 중에 CalledFromWrongThreadException 가 자주 보였다. 결국 찾다보니 아래와 같이 떡하니;; 안된다고 한다.

My god, you must change your UI in main thread  but not your new thread , it is  android's rule .
오! 이런, 너는 메인쓰레드에서 너의 UI를 변화시킬려고 하구나, 하지만 네 새 쓰레드에서는 안된단다. 그게 안드로이드 룰이야!!

참고 본문 : http://durl.me/5mse

그렇군;; 

그래서 어쩔수 없이 Thread와 통신할 수 있는 handler를 만들어서 해결했다.
예로 들어보자. 아래와 같은 간단한 쓰레드 작업이 있다.

new Thread() {
   public void run() {
    setClipList();  // 어떤 리스트를 세팅한다. = 쓰레드에서 하는 주 작업
    Message msg = handler.obtainMessage();
    handler.sendMessage(msg);

   }
  }.start();

그러면 아래와 같이 핸들러를 만들어준다.

 final Handler handler = new Handler() {
  public void handleMessage(Message msg) {
   aa.notifyDataSetChanged();  //필자가 원했던 UI 업데이트 작업
  }
}; 

* 위에서는 현재 두 소스가 한 activity에 같이 있는 경우이라서 hander 클래스를 내부 클래스로 선언하는데 문제가 없었으며 만약 Thread를 따로 클래스로 빼고자 할경우엔, 인스턴스 생성시엔 해당 handler를 넘기며 Thread 클래스 생성자에서는 handler값을 받도록 구현하면 된다.

또 하나, 단순히 msg만 가는게 아니고 아래와 같이 msg에 보내고 싶은 값을 설정할 수도 있다.

  Message msg = mHandler.obtainMessage();
   Bundle b = new Bundle();
   b.putInt("downSize", total);
   msg.setData(b);
   mHandler.sendMessage(msg);

자.. 그럼 또 다음 해결책을 찾으러 떠나볼까;;


이글을 쓴지 벌써 4여년이 흘렀네요;;; 휴.. 세월이란..
좋은 API가 1때부터 지원되는게 있었네요
이제는 워낙 좋은 자료들이 많아서 구글링해 보시면 잘 나와있습니다.

다들 건승하세요~

public final void runOnUiThread (Runnable action)

Added in API level 1

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

Parameters
actionthe action to run on the UI thread

Posted by 빈솔B
,