Android method to determine if the interface you are currently on is home's main desktop

  • 2020-06-19 11:43:17
  • OfStack

This article illustrates how Android can determine if the interface is home's main desktop. Share to everybody for everybody reference. Specific implementation methods are as follows:


/** 
*  Gets the name of the application package that belongs to the desktop application  
* @return  Returns a list of strings containing all package names  
*/ 
private List<String> getHomes() { 
  List<String> names = new ArrayList<String>(); 
  PackageManager packageManager = this.getPackageManager(); 
  // attribute  
  Intent intent = new Intent(Intent.ACTION_MAIN);
  intent.addCategory(Intent.CATEGORY_HOME); 
  List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, 
    PackageManager.MATCH_DEFAULT_ONLY); 
  for(ResolveInfo ri : resolveInfo){ 
   names.add(ri.activityInfo.packageName); 
   Log.i("zhangyinfu PinyinIME.java", "packageName =" + ri.activityInfo.packageName);
  } 
  return names;
}

Analysis:

1) Since you want to judge the current interface, it is necessary to judge the first item in the current RunningTasks;

2) Introduce ActivityManager to obtain RunningTasks;

3) Take out PackageName of topActivity in RunningTasks;

4) Finally, compare with List obtained in step 1!

5) Relevant permissions shall be added

<uses-permission android:name="android.permission.GET_TASKS" />


/** 
*  Determine if the current interface is desktop  
*/ 
public boolean isHome(){ 
  ActivityManager mActivityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); 
  List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
  List<String> strs = getHomes();
  if(strs != null && strs.size() > 0){
   return strs.contains(rti.get(0).topActivity.getPackageName());
  }else{
   return false;
  }
}

I hope this article has been helpful for your Android programming.


Related articles: