1.在實際開發中,咱們常常會遇到查看當前Activity叫什麼名字,是哪一個類,當咱們去翻閱別的的代碼時,真是頭疼,因此可已在項目的BaseActivity中寫一個獲得Activity名稱的方法,繼承這個Base的Activity的名字都會被打印出來,以下android
public class BaseActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e("className:", getActivityName()); } private String getActivityName() { return getClass().getSimpleName(); } }
運行結果:ide
2.在開發中可能會遇到隨時隨地退出程序的時候,這時候該怎麼處理呢,能夠寫一個Activity的管理類,想退出時,依次finish掉Activitythis
public class ActivityControler { private static List<Activity> activityList = new ArrayList<>(); //添加Actiivty public static void addActiivty(Activity activity) { activityList.add(activity); } //刪除Activity public static void removeActivity(Activity activity) { activityList.remove(activity); } //退出程序時逐個關閉 public static void removeAllActivity() { if (!activityList.isEmpty()) { for (Activity activity : activityList) { if (!activity.isFinishing()) activity.finish(); } } } }
而後在BaseActivity生命週期中作添加和刪除操做spa
public class BaseActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e("className:", getActivityName()); } private String getActivityName() { return getClass().getSimpleName(); } @Override protected void onResume() { super.onResume(); ActivityControler.addActiivty(this); } @Override protected void onDestroy() { super.onDestroy(); ActivityControler.removeActivity(this); } }
若是想在某一個Actiivty中退出程序code
public class SecondActivity extends BaseActivity { private Button mButton; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); mButton = (Button) findViewById(R.id.button); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ActivityControler.removeAllActivity(); //android.os.Process.killProcess(android.os.Process.myPid()); } }); } }
若是想保證程序徹底退出,能夠在finish掉全部Actiivty以後加上結束進程代碼android.os.Process.killProcess(android.os.Process.myPid())blog