Android determines whether a class exists in the Task Stack
During development projects, we often encounter some problems. In addition to setting the Startup Mode of some activities, we need to determine whether the class has been started, to determine whether a class exists in the task stack, we can use the following method:
/*** Determine whether a Class exists in the job stack * @ return */private boolean isExsitMianActivity (Class
Cls) {Intent intent = new Intent (this, cls); ComponentName cmpName = intent. resolveActivity (getPackageManager (); boolean flag = false; if (cmpName! = Null) {// This activity ActivityManager am = (ActivityManager) getSystemService (ACTIVITY_SERVICE); List
TaskInfoList = am. getRunningTasks (10); for (RunningTaskInfo taskInfo: taskInfoList) {if (taskInfo. baseActivity. equals (cmpName) {// It indicates that it has enabled flag = true; break; // jump out of the loop, Optimization Efficiency }}return flag ;} /*** perform logical processing */public void dealWithIntent () {if (isExsitMianActivity (MainActivity. class) {// This class exists // perform operations} else {// This class does not exist // perform operations }}
There are also:
1. determine whether an application exists based on the package name
public boolean checkApplication(String packageName) { if (packageName == null || .equals(packageName)){ return false; } try { ApplicationInfo info = getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES); return true; } catch (NameNotFoundException e) { return false; }}
Ii. determine whether an Activity exists
Intent intent = new Intent (); intent. setClassName (package name, class name );
Method 1:
If (getPackageManager (). resolveActivity (intent, 0) = null) {// This activity does not exist in the system}
Method 2:
If (intent. resolveActivity (getPackageManager () = null) {// This activity does not exist in the system}
Method 3:
List
List = getPackageManager (). queryIntentActivities (intent, 0); if (list. size () = 0) {// This activity does not exist in the system}