본문 바로가기
Android 기법/# Study

[Android]Handler와 Splash

by 퍼즐잎 2016. 11. 6.

Splash Activity를 구현하려고 구글링을 해보니 

Handler를 사용하는 코드가 많아서 정리를 해 보았다.




Handler는 다른 객체가 보낸 메시지를 수신, 처리하는 객체로 볼 수 있다.

(참고 - 스레드와 핸들러의 관계 : http://itmir.tistory.com/366)




Handler는 대략 아래와 같은 코드로 기본형을 생성하고 사용할 수 있다.

Message 타입의 msg는 what, arg1, arg2, arg3, obj를 가질 수 있다.




Handler에서 sendEmptyMessage() 함수를 이용하면 what 값을 전달할 수 있고

sendMessage() 함수를 이용하면 Message 객체를 전달할 수 있다.



1
2
3
4
if(msg.what == 0)
{
    //분기
}
cs




1
2
3
4
5
6
7
8
9
10
11
12
  Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
 
            }
        };
 
        handler.sendEmptyMessage(1);
        handler.sendEmptyMessageDelayed(1,지연시간);
        handler.sendMessage(Message 객체);
 
cs



Splash Activity를 구현하기 위해서 Handler를 사용하면 다음과 같다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.os.PersistableBundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    
    
    public class Splash extends AppCompatActivity {
    
        //Splash 화면이 떠 있을 시간 지정
        private final int SPLASH_DISPLAY_TIME = 3000;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_splash);
 
            final Handler handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    Intent intent = new Intent(Splash.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            };
    
            handler.sendEmptyMessageDelayed(0,SPLASH_DISPLAY_TIME);
    
    
        }
    }
 
 
cs


댓글