在Android开发中,有时候会遇到我们需要退出应用程序的时候,对于退出问题,众说纷云,有很多方法,至今本人没有发现较好的方法来解决这个问题:
1. 什么是”堆栈法“?
2.什么时候适用”堆栈法“?
当app不支持横竖屏切换的时候,这时候用”堆栈法“来退出应用程序是最好的选择。如果你的app支持横竖屏切换,你需要保证你的Activity不被destroy(),否则就会直接退出,返回到桌面了。
3. 如何实现退出app的功能
step1.把ScreenManager.java加到你的项目util工具包下,源代码如下:
/**
* This is a class used to exit from application. (poup all activities from stack)
*
*/
public class ScreenManager {
private static Stack<BaseActivity> activityStack;
private static ScreenManager instance;
private ScreenManager() {
}
public static ScreenManager getScreenManager() {
if (instance == null) {
instance = new ScreenManager();
}
if (activityStack == null) {
activityStack = new Stack<BaseActivity>();
}
return instance;
}
public void popActivity() {
BaseActivity activity = activityStack.lastElement();
if (activity != null) {
activity.finish();
activity = null;
}
}
public void popActivity(BaseActivity activity) {
if (activity != null) {
activity.finish();
activityStack.remove(activity);
activity = null;
}
}
public BaseActivity currentActivity() {
try {
BaseActivity activity = activityStack.lastElement();
return activity;
} catch (Exception e) {
return null;
}
}
public void pushActivity(BaseActivity activity) {
activityStack.add(activity);
}
public void popAllActivityExceptOne(Class<?> cls) {
while (true) {
BaseActivity activity = currentActivity();
if (activity == null) {
break;
}
if (activity.getClass().equals(cls)) {
break;
}
popActivity(activity);
}
}
public void popAllActivityAddMe(BaseActivity activity) {
while (true) {
BaseActivity a = currentActivity();
if (a == null) {
break;
}
if(!activity.equals(a))
popActivity(a);
else
activityStack.remove(activity);
}
pushActivity(activity);
}
public void popAllActivity() {
activityStack.removeAllElements();
activityStack.clear();
}
}
step2.让所有yourActivity继承 BaseActivity.java, BaseActivity.java的代码如下:
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ScreenManager.getScreenManager().popAllActivityAddMe(this);
}
}
step3.设置用户操作接口,用来退出。如在登录页面当用户按back键时,这时候调用退出app功能。
在LoginActivity中添加:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
// skill LoginActivity or close the application
new AlertDialog.Builder(this).setTitle("").setIcon(R.drawable.icon).setMessage(
R.string.exit).setNegativeButton(
R.string.str_no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setPositiveButton(R.string.str_yes,
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
int whichButton) {
dialog.dismiss();
ScreenManager.getScreenManager().popAllActivity();
android.os.Process.killProcess(android.os.Process.myPid());
finish();
System.exit(0);
}
}).show();
return false;
}
return super.onKeyDown(keyCode, event);
}
这样就可以完全退出app了,且此法通用于各个sdk version