重写activty的onkeydown在用户按下返回键的时候调用,所以我们可以通过重写onkeydown的方法实现,还有可能到了MainActivity前面还有其他acitivty存活这,我们需要在onkeydown的时候把所有的activity都结束掉,为了实现这个我们先定义一个BaseActivity,在Oncreate和ondestroy生命周期里存储acitivty的引用
用一个List集合存储存活的acitivity,我们把list作为application成员
写一个MyApp类,作为程序启动的application
public class MyApp extends Application{
private List activities = new ArrayList();
public List getActivities(){
return activities;
}
}
BaseActivity代码如下
class BaseActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MyApp)getApplication()).getActivities().add(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
((MyApp)getApplication()).getActivities().remove(this);
}
}
以后工程里的所有Activity都继承于BaseActivity即可
最后是MainAcitivty的代码,在onkeydown方法里遍历list集合,调用每个activity的finish方法即可
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
List activities = ((MyApp)getApplication()).getActivities();
for(Activity activity:activities){
activity.finish();
}
return super.onKeyDown(keyCode, event);
}
}
// 捕获返回按钮事件
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { dialog(); return false; } else { return super.onKeyDown(keyCode, event); } } // 提示框 protected void dialog() { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle("").setIcon(android.R.drawable.ic_dialog_info) .setMessage(" 您确认退出程序吗?").setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel();// 取消弹出框 } }).create().show(); }
开发吗????
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
AlertDialog.Builder build=new AlertDialog.Builder(this);
build.setTitle("注意")
.setMessage("确定要退出吗?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.show();
break;
default:
break;
}
return false;
//return super.onKeyDown(keyCode, event);
}
在A、B两个Activity之间跳转,A是主Activity。首先在A中实现下面的推荐答案,然后在B中跳转语句中加一句:intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
这是因为你以前的activity没有finish();
按返回不是已经退出了么?
去任务管理器退出