The method of obtaining Activity stack and judging the current Activity position
- 2021-08-28 20:57:22
- OfStack
Demand
It is necessary to pop up the pop-up box globally in the whole app, and process it when receiving the broadcast.
However, BaseActivity derives N Activity, and the broadcast in BaseActivity will execute N times, resulting in repeated addition of bullet boxes. All the decisions made in the broadcast, only Activity at the top of the stack can process broadcast messages.
Realization
Get the task stack
You must add permissions:
<!-- Get Activity Task stack Authority -->
<uses-permission android:name="android.permission.GET_TASKS" />
Specific implementation, acquisition stack and its contents:
// Get activity Task stack
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.RunningTaskInfo info = manager.getRunningTasks(1).get(0);
// Class name .ui.mobile.activity.WebsiteLoginActivity
String shortClassName = info.topActivity.getShortClassName();
// Full class name com.haofang.testapp.ui.mobile.activity.WebsiteLoginActivity
String className = info.topActivity.getClassName();
// Package name com.haofang.testapp
String packageName = info.topActivity.getPackageName();
Package name and full name of current Activity:
// Package name com.haofang.testapp
BaseActivity.this.getPackageName()
// Class name ui.main.MainActivity
BaseActivity.this.getLocalClassName()
After comparison, the non-target Activity can be avoided