今天早上帮朋友调试代码,说是退出应用代码无效,仔细看了代码,写法上的确没什么问题,于是研究了一下,原因如下:
先看两种情况:
(1)public class MainActivity extends TabActivity implements OnCheckedChangeListener
(2)public class MainActivity extends Activity
都是要在MainActivity下退出整个应用,第一种情况主Activity继承自TabActivity,第二种情况主Activity继承自Activity,这是两者最大的不同,也就是这点差异,能把有效的退出应用代码变的无效。
虽然TabActivity是Activity的间接子类,但是在TabActivity中,OnKeyDown()事件无法获取焦点,因为焦点都在子activity里面,本人亲自做了验证,在(1)情况下,在onKeyDown()处打断点无效,无法进行DeBug调试,但在(2)情况下,可以进入DeBug中。下面是退出引用程序的代码
(1)情况下适用代码:
@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
// TODO Auto-generated method stub
if (event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_BACK)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("您确定要退出应用?").setTitle("提醒")
.setNegativeButton("取消", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
arg0.cancel();
}
}).setPositiveButton("确定", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
return false;
}
return super.dispatchKeyEvent(event);
}
(2)情况下适用代码一:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提醒");
builder.setMessage("确认退出应用?");
builder.setPositiveButton("确定", new OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
builder.setNegativeButton("取消", new OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
}
});
builder.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
(2)情况下适用代码二:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示ʾ");
builder.setMessage("确定要退出应用");
builder.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
finish();
// System.exit(code);
}
});
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
});
builder.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
总之一句话,如果继承的是Activity,就通过OnKeyDown()方法退出程序,如果继承的事TabActivity,就通过dispathKeyEvent()方法退出应用。