关于安卓应用账号退出

首先,我们将管理Activity的功能通过一个扩展的Application类来实现。
public class MyApplication extends Application {
   
    private static Stack<Activity> activityStack;
    private static MyApplication singleton;
    @Override
    public void onCreate()
    {
        super.onCreate();
        singleton=this;
    }
    // Returns the application instance
    public static MyApplication getInstance() {
        return singleton;
    }

    /**
     * add Activity 添加Activity到栈
     */
    public void addActivity(Activity activity){
        if(activityStack ==null){
            activityStack =new Stack<Activity>();
        }
        activityStack.add(activity);
    }
    /**
     * get current Activity 获取当前Activity(栈中最后一个压入的)
     */
    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }
    /**
     * 结束当前Activity(栈中最后一个压入的)
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public void AppExit() {
        try {
            finishAllActivity();
        } catch (Exception e) {
        }
    }

}
注意,为了在我们自己的应用程序中使用这个自定义的Application类,而不是默认的Application类。需要在Manifest文件中修改一下<Application>的属性( android:name)

例如:


1 <application
2    android:icon="@drawable/icon"
3    android:label="@string/app_name"
4    android:name="your_package_name_here.MyApplication">


使用方法:

方法1: 之后我们在所有的activity的oncreate方法中通过getinstance得到一个MyApplication的实例,然后调用addActivity方法把当前的activity加入到stack中,如果要退出应用程序只需要调用AppExit方法即可。

方法2: 自定义一个继承Activity类的BaseActivity
1 public class BaseActivity extends Activity{
2     @Override
3     protected void onCreate(Bundle savedInstanceState){
4         super.onCreate(savedInstanceState);
5         //添加Activity到堆栈
6         MyApplication.getInstance().addActivity(this);
7     }

9     @Override
10     protected void onDestroy(){
11         super.onDestroy();
12         //结束Activity&从栈中移除该Activity
13         MyApplication.getInstance().finishActivity(this);
14     }
15 
16 }

你可能感兴趣的:(android)