Heim > Fragen und Antworten > Hauptteil
好多程序返回到第一个activity的时候,再按back会弹出吐司提示双击退出程序
在网上查了一下发现都是用keycode来实现的,用onBackPressed能实现同样的效果吗?
两种哪种方式好一点?用java计时器和handle延时发送两种之间哪个好一点?
迷茫2017-04-17 14:20:18
没那么麻烦,直接用toast的getView().getParent() 判断是不是空就ok了。API 16 测试通过
public class MainActivity extends Activity {
private Toast toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toast = Toast.makeText(getApplicationContext(), "确定退出?", 0);
}
public void onBackPressed() {
quitToast();
}
/*
public boolean onKeyDown(int keyCode, KeyEvent event) {
System.out.println(keyCode + "...." + event.getKeyCode());
if(keyCode == KeyEvent.KEYCODE_BACK){
quitToast();
}
return super.onKeyDown(keyCode, event);
}
*/
private void quitToast() {
if(null == toast.getView().getParent()){
toast.show();
}else{
System.exit(0);
}
}
}
迷茫2017-04-17 14:20:18
onbackpressed可以,http://tianmaying.com/snippet/8ab3eda84dd8bc9f014de5eab9bf036c
话说你确定有好多程序用到了双击退出?
哪个好点不好说 我一般用onbackpressed.
天蓬老师2017-04-17 14:20:18
/* 上一次按返回按键的时间 */
long preBackPressTime;
/* 按返回按键的次数 */
long pressTimes;
@Override
public void onBackPressed() {
super.onBackPressed();
long cBackPressTime = SystemClock.uptimeMillis();
if (cBackPressTime - preBackPressTime < 2000) {
pressTimes++;
if (pressTimes >= 2) {
finish();
}
} else {
pressTimes = 1;
}
if (pressTimes == 1) {
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
}
preBackPressTime = cBackPressTime;
}