Looper가 뭐고 언제 쓰는건가요?

조회수 5366회

이번에 안드로이드를 배우고있는데요. Looper라는 클래스가 뭔지 알고싶어요. 그리고 그걸 어떻게 쓰는지도요. 안드로이드 Looper 클래스에 관한 문서를 읽어봤는데 완전히 이해한것 같지 않아서요. 용도가 다양한것 같은데 그걸 쓰는 이유를 잘 이해 못했어요. Looper가 정확히 뭔지 그리고 그걸 언제 쓰는지 설명좀 해주세요.

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    루퍼가 뭔가요?

    : 메세지는 스레드간의 신호이므로 handler에 보낸다고 해서 곧바로 처리되는 것이 아닙니다. 동시다발적으로 메세지가 발생할 수 있기 때문에 메세지 큐(Message Queue)에 쌓았다가 처리합니다. 큐(Queue)에 들어있는 내용을 하나하나 꺼내 처리하는 놈이 바로 루퍼입니다. 메인 쓰레드가 looper를 가지고 있으며 무한 루프를 돌며 큐의 내용을 처리합니다.

    APIs.

    static void prepare()
    static void loop()
    void quit()
    
    Thread getThread()  // 루퍼와 연결된 쓰레드 구하기.
    static Looper getMainLooper()  // 응용 프로그램의 주 루퍼 구하기
    static Looper myLooper()  // 현재 thread의 looper를 구함. 모든 쓰레드가 looper를 가지는게 아니므로 null 이 리턴될수도 있다.
    

    Looper 사용하는 sample code 좀 보여주세요.

     Message msg = Message.obtain();
    msg.what = 0;
    mThread.mBackHandler.sendMessage(msg);
    
    CalcThread mThread = new CalcThread(mHandler);
    mThread.setDaemon(true);
    mThread.start();
    
    Handler mHandler = new Handler(){
       public void handleMessage(Message msg){
          switch(msg.what) {
          case 0:
             // To do
          }
       }
    }
    
    class CalcThread extends Thread{
       Handler mMainHandler;
       CalcThread(Handler handler){
             mMainHandler = handler;
       }
    
       public void run(){
          Looper.prepare();
          Looper.loop();
       }
    
       public Handler mBackHandler = new Handler(){
          public void handleMessage(Message msg){
             Message retmsg = Message.obtain();
             switch(msg.what){
             case 0:
                try{ Thread.sleep(100); } catch (InterruptedException e) { ; }
                retmsg.what = 0;
                retmsg.arg1 = msg.arg1 * msg.arg1;
                retmsg.obj = new Double(Math.sqrt((double)msg.arg1));
             }
             mMainHandler.sendMessage(retmsg);
          }
       }
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)