==========================1. 知晓当前是在哪一个活动=========================
//
//新建一个BaseActivity继承Activity,重写onCreate()方法
//让BaseActivity成为其他自建Activity活动的父类
//
1 public class BaseActivity extends Activity 2 { 3 @Override 4 protected void onCreate(Bundle savedInstanceState) 5 { 6 super.onCreate(savedInstanceState); 7 Log.e("当前活动:", getClass().getSimpleName());//获取当前活动的类名 8 } 9 }
=========================2.随时随地退出程序=============================
//
//创建一个ActivityController类
//
1 public class ActivityController 2 { 3 private static List<Activity> activities = new LinkedList<>(); 4 5 public static void addActivity(Activity activity) 6 { 7 activities.add(activity); 8 } 9 10 public static void removeActivity(Activity activity) 11 { 12 activities.remove(activity); 13 } 14 15 public static void finishAll() 16 { 17 for (Activity activity : activities) 18 { 19 if (!activity.isFinishing()) 20 { 21 activity.finish(); 22 } 23 } 24 } 25 }
//
//修改BaseActivity类
//
1 public class BaseActivity extends Activity 2 { 3 @Override 4 protected void onCreate(Bundle savedInstanceState) 5 { 6 super.onCreate(savedInstanceState); 7 Log.e("当前活动:", getClass().getSimpleName());//获取当前活动的类名 8 ActivityController.addActivity(this);//将活动添加到集合中 9 } 10 11 @Override 12 protected void onDestroy() 13 { 14 super.onDestroy(); 15 ActivityController.removeActivity(this);////将活动从集合中移除 16 } 17 }
//
//在活动中退出程序时: 调用 ActivityController.finishAll() 方法
//
===================================3.启动活动的最佳写法=================================
//
//在自建的Activity中创建静态方法 actionStart(Context context, String data1, String data2, //..........)
//
1 public class SecondActivity extends BaseActivity 2 { 3 /** 4 * 启动活动的最佳写法 5 * 需要几个参数,传几个参数 6 */ 7 public static void actionStart(Context context, String data1, String data2) 8 { 9 Intent intent = new Intent(context, SecondActivity.class); 10 intent.putExtra("param1", data1); 11 intent.putExtra("param2", data2); 12 context.startActivity(intent); 13 } 14 //............. 15 }
//
//在某活动中调用静态方法SecondActivity.actionStart(Context context, String data1, String data2, //..........)
//跳转至SecondActivity
//
1 btn.setOnClickListener(new View.OnClickListener() 2 { 3 @Override 4 public void onClick(View v) 5 { 6 SecondActivity.actionStart(FirstActivity.this, "要传递的数据1", "要传递的数据1"); 7 } 8 });
时间: 2024-10-03 13:20:00