1.两次返回键,直接结束当前Activity
重写返回onBackPressed方法,其原理十分简单,判断两次点击的事件间隔,若大于两秒则将exitTime更新为当前时间,小于则退出;
private long exitTime = 0;
@Override
public void onBackPressed() {
if (System.currentTimeMillis() - exitTime > 2000) {
showToastShort("再按一次返回");
exitTime = System.currentTimeMillis();
}else {
super.onBackPressed();
}
}
2.两次返回键,返回桌面
private long exitTime = 0;
@Override
public void onBackPressed() {
if (System.currentTimeMillis() - exitTime > 2000) {
showToastShort("再按一次返回桌面");
exitTime = System.currentTimeMillis();
}else {
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
}
|