¾È±Ô °øºÎ¹æ

Android > Back button 2¹ø Ŭ¸¯½Ã Á¾·á ½ÃÅ°´Â ·ÎÁ÷ - onBackPressed() ¸Þ¼Òµå + Handler

µî·ÏÀÏ : 2017-07-06 17:22 Á¶È¸¼ö : 53,090

À̹ø¿¡´Â ¾îÇÃÀ» °³¹ßÇϸé ÇÑ ¹ø °Ë»öÇÒ±î ¸»±îÇÑ 2¹ø ¹é¹öÆ°À¸·Î ¾îÇø®ÄÉÀ̼ÇÀ» Á¾·áÇÏ´Â °ÍÀ» ¾Ë¾Æ º¸µµ·ÏÇսôÙ.

°£´ÜÇÏ°Ô ¼Ò½ºÄڵ带 º¸¸é ¸ðµç °ÍÀÌ ÀÌÇØ°¡ µÇ±â¶§¹®¿¡ ¿©·¯°¡Áö ¸»Àº ÇÏÁö ¾ÊÀ» °ÍÀÔ´Ï´Ù.
 
	public class MainActivity extends Activity {
		
		// define variables for back key : 2 pressed end! 
		private boolean isBackKeyPressed = false;             // flag
		private long currentTimeByMillis = 0;                     // calculate time interval
		
		private static final int MSG_TIMER_EXPIRED = 1;    // switch - key
		private static final int BACKKEY_TIMEOUT = 2;      // define interval
		private static final int MILLIS_IN_SEC = 1000;        // define millisecond 
		// end of back key variable.
		
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState,R.layout.activity_main);

		}

		/*
		 * onBackPressed function override
		 *  - back 1 click : 2¹ø ´©¸£¸é Á¾·áµÇ°Ô ¸Þ¼¼Áö Ãâ·Â 
		 *  - back 2 click : 2¹ø ´©¸£¸é Á¾·á
		 */
		@Override
		public void onBackPressed(){
			if ( isBackKeyPressed == false ){
				// first click
				isBackKeyPressed = true;
				
				currentTimeByMillis = Calendar.getInstance().getTimeInMillis();
				Toast.makeText(this, "\'µÚ·Î\'¹öÆ°À» Çѹø ´õ ´©¸£½Ã¸é Á¾·áµË´Ï´Ù.", Toast.LENGTH_SHORT).show();
				
				startTimer();
			}else{
				// second click : 2ÃÊ À̳»¸é Á¾·á! ¾Æ´Ï¸é ¾Æ¹«°Íµµ ¾ÈÇÑ´Ù.
				isBackKeyPressed = false;
				if ( Calendar.getInstance().getTimeInMillis() <= (currentTimeByMillis + (BACKKEY_TIMEOUT * MILLIS_IN_SEC)) ) {
					finish();
				}
			}
		}
		
		// startTimer : 2ÃÊÀÇ ½Ã°£Àû ¿©À¯¸¦ °¡Áö°Ô delay ½ÃŲ´Ù.
		private void startTimer(){
			backTimerHandler.sendEmptyMessageDelayed(MSG_TIMER_EXPIRED, BACKKEY_TIMEOUT * MILLIS_IN_SEC);
		}
		
		private Handler backTimerHandler = new Handler(){
			public void handleMessage(Message msg){
				switch( msg.what ){
					case MSG_TIMER_EXPIRED:{
						isBackKeyPressed = false;
					}
					break;
				}
			}
		};
		// End of Back method
	}
	
¡Ø Ȥ½Ã µµ¿òÀÌ µÇ¼Ì´Ù¸é ´ñ±Û¿¡ ÇѸ¶µð ³²°ÜÁÖ¼¼¿ä!
ÀÛ¼ºÀÚ   ºñ¹Ð¹øÈ£
ÀÚµ¿±Û ¹æÁö     (ÀÚµ¿±Û ¹æÁö ±â´ÉÀÔ´Ï´Ù.)
³»¿ë   ´ñ±Û´Þ±â 
À̸ÞÀÏ ¹®ÀÇ : cak0280@nate.com  
Copyright 2000 By ENTERSOFT.KR All Rights Reserved.