Android中的“再按一次返回键退出程序”代码实现
1
|
用户在退出应用前给出一个提示是很有必要的,因为可能是用户并不真的想退出,而只是一不小心按下了返回键,大部分应用也是这么做的,但也有些应用的做法是在应用退出去前给出一个Dialog,我觉得这样不太友好,用户还得移动手指去按dialog中的“确定”按钮。我觉得再按一次“返回”键退出程序是佳的用户体验,实现也很简单,代码如下: |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
private long exitTime = 0 ; @Override public boolean onKeyDown( int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ if ((System.currentTimeMillis()-exitTime) > 2000 ){ Toast.makeText(getApplicationContext(), "再按一次退出程序" , Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { finish(); System.exit( 0 ); } return true ; } return super .onKeyDown(keyCode, event); } |
1
|
|
1
|
|
1
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<span style= "white-space:pre" > </span> private long exitTime = 0 ; <span style= "white-space:pre" > </span> @Override <span style= "white-space:pre" > </span> public boolean onKeyDown( int keyCode, KeyEvent event) { <span style= "white-space:pre" > </span> // TODO Auto-generated method stub <span style= "white-space:pre" > </span> switch (keyCode) { <span style= "white-space:pre" > </span> case KeyEvent.KEYCODE_BACK: <span style= "white-space:pre" > </span> if ((System.currentTimeMillis() - exitTime) > 2000 ){ <span style= "white-space:pre" > </span>toast( "再按一次返回键退出程序!" ); <span style= "white-space:pre" > </span>exitTime = System.currentTimeMillis(); <span style= "white-space:pre" > </span> return false ; <span style= "white-space:pre" > </span>} else { <span style= "white-space:pre" > </span>finish(); <span style= "white-space:pre" > </span>System.exit( 0 ); <span style= "white-space:pre" > </span>} <span style= "white-space:pre" > </span> break ; <span style= "white-space:pre" > </span> default : <span style= "white-space:pre" > </span> break ; <span style= "white-space:pre" > </span>} <span style= "white-space:pre" > </span> return super .onKeyDown(keyCode, event); <span style= "white-space:pre" > </span>} |
结伴旅游,一个免费的交友网站:www.jieberu.com
推推族,免费得门票,游景区:www.tuituizu.com
以上内容,全部转载,如有侵权,请联系我!