新建Java Class
BaseActivity代码如下
让其他活动都继承BaseActivity
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("BaseActivity",getClass().getSimpleName());//打印当前活动类
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
}
AcivityCollector 代码如下
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();
}
}
activities.clear();
}
}
ThirdActivity 代码如下
public class ThirdActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third_layout);
/*
* 点击按钮结束所有活动*/
Button button3= (Button) findViewById(R.id.button_3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCollector.finishAll();
android.os.Process.killProcess(android.os.Process.myPid());
}
});
}
}
启动活动的最佳写法
在SecondActivity中添加如下代码
//启动活动的最佳写法
public static void actionStart(Context context, String data1, String data2) {
Intent intent=new Intent(context,SecondActivity.class);
intent.putExtra("param1",data1);
intent.putExtra("param2",data2);
context.startActivity(intent);
}
启动SecondActivity的代码如下
Button button1=(Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SecondActivity.actionStart(MainActivity.this,"android","studio");
}
});