본문 바로가기
Android

[Android] 안드로이드 Activity 뒤로가기 (MainBackPressCloseHandler) 딜레이 주기

by 유혁. 2017. 7. 14.

결과화면

 

 

 

 

 

 

 

MainBackPressCloseHandler.class 생성

 

 

import android.app.Activity;
import android.widget.Toast;

public class MainBackPressCloseHandler {

private long backKeyPressedTime = 0;
private Toast toast;

private Activity activity;

public MainBackPressCloseHandler(Activity context) {
this.activity = context;
}

public void onBackPressed() {
if (System.currentTimeMillis() > backKeyPressedTime + 2000) {
backKeyPressedTime = System.currentTimeMillis();
showGuide();
return;
}
if (System.currentTimeMillis() <= backKeyPressedTime + 2000) {
activity.finish();
android.os.Process.killProcess(android.os.Process.myPid());
toast.cancel();
}
}

public void showGuide() {
toast = Toast.makeText(activity, "\'뒤로\'버튼을 한번 더 누르시면 종료됩니다.",
Toast.LENGTH_SHORT);
toast.show();
}
}

 

 

 

private MainBackPressCloseHandler mainBackPressCloseHandler ;

사용하고 싶은 페이지에

MainBackPressCloseHandler 선언

 

 

 

mainBackPressCloseHandler = new MainBackPressCloseHandler(this);

객체 생성

 

 

 

 

@Override
public void onBackPressed() {
mainBackPressCloseHandler.onBackPressed();
}

onBackPressed() 오버라이드

 

 

 

 

 

MainActivity.class


import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends Activity {
private MainBackPressCloseHandler mainBackPressCloseHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainBackPressCloseHandler = new MainBackPressCloseHandler(this);

}

@Override
public void onBackPressed() {
mainBackPressCloseHandler.onBackPressed();
}

}