티스토리 뷰

Developer/Android

02. Back 버튼 두번눌러 종료하기

여행가고싶다... 2011. 11. 17. 11:47
이번에 알아볼 기능은 가장 알려져있는 Nave* 어플에서 Back 버튼을 두번눌러 종료하는 기능에 대해서 알아보자.
이 기능은 Back 버튼에 대한 이벤트를 받아 Timer를 동작시켜 Timer 시간 내에 한번더 Back 버튼이 눌러지게 되면 그때 어플을 종료하도록 구현되어있다.

메인 화면 진입시
Back 버튼 한번 눌렀을 경우 
 

 



Back 버튼에 대한 처리를 위해 선언된 변수이다.
	private static final int MSG_TIMER_EXPIRED = 1;
	private static final int BACKEY_TIMEOUT = 2000;
	private boolean mIsBackKeyPressed = false;
	private long mCurrentTimeInMillis = 0;

Back 버튼이 발생하면 아래의 onBackPressed()함수가 호출되고 최초 진입시 mIsBackKeyPressed 변수를 true로 값을 넣어주고 Timer 처리를 위해 현재 시간의 밀리세컨드 값을 구한다.
Toast를 사용하여 뒤로 버튼을 한번 더 눌러야 종료가 된다는 문구를 보여주고 startTimer()로 실제 timer를 구동시킨다.
Timer는 위에서 선언된 BACKEY_TIMEOUT 값(2초)에 의해 현재의 밀리세컨드 값과 더해서 2초가 넘지 않을 경우 한번 더 Back 버튼이 눌러지면 finish()로 현재의 어플을 종료하게된다.
	
	@Override
	public void onBackPressed() {
		if(mIsBackKeyPressed == false){
			mIsBackKeyPressed = true;
			
			mCurrentTimeInMillis = Calendar.getInstance().getTimeInMillis();
			
			Toast.makeText(this, "\'뒤로\'버튼을 한번 더 누르시면 종료됩니다.", Toast.LENGTH_SHORT).show();
			startTimer();
		} else {
			mIsBackKeyPressed = false;
			
			if(Calendar.getInstance().getTimeInMillis() <= (mCurrentTimeInMillis + (BACKEY_TIMEOUT))){
				finish();
			}
		}
	}

	private void startTimer(){
		mTimerHander.sendEmptyMessageDelayed(MSG_TIMER_EXPIRED, BACKEY_TIMEOUT);
	}

	private Handler mTimerHander = new Handler(){
		public void handleMessage(Message msg){
			switch(msg.what){
				case MSG_TIMER_EXPIRED:
				{
					mIsBackKeyPressed = false;
				}
			break;
			}
		}
	};
	/* Back key 두번눌러 종료 코드 끝*/


[MainMenu.java 파일 전체내용 보기]
package com.alieneye.mash;

import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainMenu extends Activity {
    /** Called when the activity is first created. */
	
	/* Back key 두번눌러 종료 코드 시작 */
	private static final int MSG_TIMER_EXPIRED = 1;
	private static final int BACKEY_TIMEOUT = 2000;
	private boolean mIsBackKeyPressed = false;
	private long mCurrentTimeInMillis = 0;

	@Override
	public void onBackPressed() {
		if(mIsBackKeyPressed == false){
			mIsBackKeyPressed = true;
			
			mCurrentTimeInMillis = Calendar.getInstance().getTimeInMillis();
			
			Toast.makeText(this, "\'뒤로\'버튼을 한번 더 누르시면 종료됩니다.", Toast.LENGTH_SHORT).show();
			startTimer();
		} else {
			mIsBackKeyPressed = false;
			
			if(Calendar.getInstance().getTimeInMillis() <= (mCurrentTimeInMillis + (BACKEY_TIMEOUT))){
				finish();
			}
		}
	}
	
	private void startTimer(){
		mTimerHander.sendEmptyMessageDelayed(MSG_TIMER_EXPIRED, BACKEY_TIMEOUT);
	}
	
	private Handler mTimerHander = new Handler(){
		public void handleMessage(Message msg){
			switch(msg.what){
				case MSG_TIMER_EXPIRED:
				{
					mIsBackKeyPressed = false;
				}
			break;
			}
		}
	};
	/* Back key 두번눌러 종료 코드 끝*/
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Title bar 제거
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.menu);
        
        // Profile 메뉴로 이동
        Button menu_profile_button = (Button) findViewById(R.id.menubar_profile);
        
        menu_profile_button.setOnClickListener(
    		new OnClickListener(){
    			public void onClick(View v){
    				Intent intent = new Intent(MainMenu.this, MenuProfile.class);
    				startActivity(intent);
    			}
    		}
        );
        
        // Album 메뉴로 이동
        Button menu_album_button = (Button) findViewById(R.id.menubar_album);
        
        menu_album_button.setOnClickListener(
    		new OnClickListener(){
    			public void onClick(View v){
    				Toast.makeText(MainMenu.this, "Tip. 사진을 보시다가 사진을 길게 터치하여 배경화면으로 지정이 가능합니다.", Toast.LENGTH_SHORT).show();
    				Intent intent = new Intent(MainMenu.this, MenuAlbum.class);
    				startActivity(intent);
    			}
    		}
        );
        
        // Play 메뉴로 이동
        Button menu_play_button = (Button) findViewById(R.id.menubar_play);
        
        menu_play_button.setOnClickListener(
    		new OnClickListener(){
    			public void onClick(View v){
    				Toast.makeText(MainMenu.this, "네트워크 상태에 따라서 미리듣기 및 다운로드가 다소 지연이 될 수 있습니다.", Toast.LENGTH_SHORT).show();
    				Intent intent = new Intent(MainMenu.this, MenuPlay.class);
    				startActivity(intent);
    			}
    		}
        );
        
        // Info 메뉴로 이동
        Button menu_info_button = (Button) findViewById(R.id.menubar_info);
        
        menu_info_button.setOnClickListener(
    		new OnClickListener(){
    			public void onClick(View v){
    				Intent intent = new Intent(MainMenu.this, MenuInfo.class);
    				startActivity(intent);
    			}
    		}
        );
    }
}
댓글