实现退出确认和销毁所有活动

一、实现退出确认

 

实现方式:在Android平台上捕获Back键的事件,super.onBackPressed()是执行系统的默认动作,就是退出当前activity,我们要做的就是重写onBackPressed()函数

@Override
    public void onBackPressed() {
        new CommomDialog(Home.this, R.style.dialog, "确认退出此程序?", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    ActivityCollector.FinishAll();
                    dialog.dismiss();
                }
            }
        }).setTitle("提示").show();
    }

 

 

二、销毁所有活动

1.新建ActivityCollector存放活动

public class ActivityCollector {
    public static List<Activity> activities = new ArrayList<>();

    public static void AddActivity(Activity activity) {
        activities.add(activity);
    }

    public static void RemoveActivity(Activity activity) {
        activities.remove(activity);
    }

    public static void FinishAll() {
        for (Activity activity : activities) {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }
}

 

2.新建BaseActivity继承AppCompatActivity

public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.AddActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.RemoveActivity(this);
    }
}

 

3.每个活动继承BaseActivity而不是AppCompatActivity

public class Home extends BaseActivity implements View.OnClickListener {

 

4.销毁所有活动

 ActivityCollector.FinishAll();

 

posted @ 2017-08-24 14:32  XinYiBuFang  阅读(402)  评论(0编辑  收藏  举报