본문 바로가기

안드로이드

Back버튼 두번으로 액티비티 종료하기

Back버튼 두번으로 액티비티 종료하기



원리는 다음과 같다.

1) 처음 뒤로가기를 눌렀을때 backKeyPressedTime에 현재시간을 저장한다.

2) 2초안에 뒤로가기를 다시 눌렀을때 조건문이 통과하여 액티비티 종료

long backKeyPressedTime=0;
@Override
public void onBackPressed() {
if (System.currentTimeMillis() > backKeyPressedTime + 2000) {
backKeyPressedTime = System.currentTimeMillis();
return;
}
//현재 시간이 변수 backKeyPressedTime + 2000보다 작으면 앱 종료
if (System.currentTimeMillis() <= backKeyPressedTime + 2000) {
finish();
}
super.onBackPressed();
}