MainThread에 접근하는 3가지 방법

나고수·2022년 5월 8일
0

1일1공부

목록 보기
39/67

Handler(Looper.getMainLooper())

  • 메인쓰레드와 다른쓰레드를 handler를 이용하여 연결해주는 방법

Activity.runOnUiThread(Runnable)

  • 현재 쓰레드가 메인쓰레드이면 바로 작업 실행, 현재 쓰레드가 메인쓰레드가 아니라면 메인쓰레드 message Queue에 작업 할당.
@Override
public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}

View.post(Runnable)

  • runOnUiThread와 비슷하지만, view가 attach 되었는지 체크한다는 차이점이 있음.
  • view가 attach 되었다면, 작업을 메인쓰레드 message Queue에 할당.
  • view가 아직 attach 되지 않았다면, RunQueue-지연된 작업들이 모여있는 queue이며 view에만 존재한다.-에 작업을 할당.
  • public boolean postDelayed (Runnable action, long delayMillis) 을 이용해서 시간 경과 후 작업을 시작하도록 할 수도 있음.
  • view가 Gone , detach 된 후에는 post를 불러도 함수가 작동되지 않음.
public boolean post(Runnable action) {
    final AttachInfo attachInfo = mAttachInfo;
    if (attachInfo != null) {
    //view가 attach 되었음.
        return attachInfo.mHandler.post(action); //메인쓰레드 message queue에 할당
    }

    // Postpone the runnable until we know on which thread it needs to run.
    // Assume that the runnable will be successfully placed after attach.
    getRunQueue().post(action);
    return true;
}
  • 뷰A의 matchParent 일 때 width 길이를 기준으로 다른 뷰들의 width 길이를 변경하고 싶었는데,
    이때 view.post 를 사용하였습니다.
  • 그냥 binding.textView.getWidth()를 하면 항상 0 이 나옵니다.
  • 하지만 post 함수는 뷰A가 attach 된 이후에 작동하는 함수이기 때문에, matchParent width 길이를 정확히 잘 가져 올 수 있습니다.
 binding.textView.post {
	matchParentWidth = binding.textView.width //width is ready
	//matchParent Width를 이용하여 무언가 진행.. 
}

참고블로그

profile
되고싶다

0개의 댓글