whether context is system application - Android App

Android examples for App:App Running

Description

whether context is system application

Demo Code

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

public class Main {
  /**/*from  w w  w .ja v  a 2  s.co  m*/
   * whether context is system application
   * 
   * @param context
   * @return
   */
  public static boolean isSystemApplication(Context context) {
    if (context == null) {
      return false;
    }

    return isSystemApplication(context, context.getPackageName());
  }

  /**
   * whether packageName is system application
   * 
   * @param context
   * @param packageName
   * @return
   */
  public static boolean isSystemApplication(Context context, String packageName) {
    if (context == null) {
      return false;
    }

    return isSystemApplication(context.getPackageManager(), packageName);
  }

  /**
   * whether packageName is system application
   * 
   * @param packageManager
   * @param packageName
   * @return
   *         <ul>
   *         <li>if packageManager is null, return false</li>
   *         <li>if package name is null or is empty, return false</li>
   *         <li>if package name not exit, return false</li>
   *         <li>if package name exit, but not system app, return false</li>
   *         <li>else return true</li>
   *         </ul>
   */
  public static boolean isSystemApplication(PackageManager packageManager, String packageName) {
    if (packageManager == null || packageName == null || packageName.length() == 0) {
      return false;
    }

    try {
      ApplicationInfo app = packageManager.getApplicationInfo(packageName, 0);
      return (app != null && (app.flags & ApplicationInfo.FLAG_SYSTEM) > 0);
    } catch (NameNotFoundException e) {
      e.printStackTrace();
    }
    return false;
  }
}

Related Tutorials