public void replaceDrawable(
     ImageView v, ComponentName component, String name, boolean isService) {
   if (component != null) {
     try {
       PackageManager packageManager = mContext.getPackageManager();
       // Look for the search icon specified in the activity meta-data
       Bundle metaData =
           isService
               ? packageManager.getServiceInfo(component, PackageManager.GET_META_DATA).metaData
               : packageManager.getActivityInfo(component, PackageManager.GET_META_DATA).metaData;
       if (metaData != null) {
         int iconResId = metaData.getInt(name);
         if (iconResId != 0) {
           Resources res = packageManager.getResourcesForApplication(component.getPackageName());
           v.setImageDrawable(res.getDrawable(iconResId));
           return;
         }
       }
     } catch (PackageManager.NameNotFoundException e) {
       Log.w(
           TAG, "Failed to swap drawable; " + component.flattenToShortString() + " not found", e);
     } catch (Resources.NotFoundException nfe) {
       Log.w(TAG, "Failed to swap drawable from " + component.flattenToShortString(), nfe);
     }
   }
   v.setImageDrawable(null);
 }
  /**
   * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX} provided
   * by the same package which is set to be global search activity. If widgetCategory is not
   * supported, or no such widget is found, returns the first widget provided by the package.
   */
  @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
  public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
    SearchManager searchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
    ComponentName searchComponent = searchManager.getGlobalSearchActivity();
    if (searchComponent == null) return null;
    String providerPkg = searchComponent.getPackageName();

    AppWidgetProviderInfo defaultWidgetForSearchPackage = null;

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
      if (info.provider.getPackageName().equals(providerPkg)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
          if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
            return info;
          } else if (defaultWidgetForSearchPackage == null) {
            defaultWidgetForSearchPackage = info;
          }
        } else {
          return info;
        }
      }
    }
    return defaultWidgetForSearchPackage;
  }
  // sets the preferred launcher; if svmp is true, will set to LauncherActivity, otherwise will set
  // to aosp launcher
  protected static void setDefaultLauncher(
      Context context, PackageManager packageManager, boolean svmp) {
    Log.d(TAG, "Setting default launcher to: " + (svmp ? "svmp" : "aosp"));

    // set up args
    IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
    filter.addCategory(Intent.CATEGORY_HOME);
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    int bestMatch = IntentFilter.MATCH_CATEGORY_EMPTY;
    ComponentName aospComponent =
        new ComponentName("com.cyanogenmod.trebuchet", "com.android.launcher3.Launcher");
    ComponentName svmpComponent =
        new ComponentName(context.getPackageName(), LauncherActivity.class.getName());
    ComponentName[] components = new ComponentName[] {aospComponent, svmpComponent};

    // set preferred launcher and clear preferences for other launcher
    ComponentName preferred = svmp ? svmpComponent : aospComponent,
        other = svmp ? aospComponent : svmpComponent;
    packageManager.clearPackagePreferredActivities(other.getPackageName());
    packageManager.addPreferredActivity(filter, bestMatch, components, preferred);

    if (svmp) {
      // start the preferred launcher
      Intent launchIntent = new Intent(Intent.ACTION_MAIN);
      launchIntent.setComponent(preferred);
      launchIntent.addCategory(Intent.CATEGORY_HOME);
      launchIntent.addFlags(
          Intent
              .FLAG_ACTIVITY_NEW_TASK); // required to start an activity from outside of an Activity
                                        // context
      launchIntent.addFlags(
          Intent.FLAG_ACTIVITY_CLEAR_TASK); // when this is started, clear other launcher activities
      context.startActivity(launchIntent);
    }
  }
Exemple #4
0
        public void run() {

          Logger.getLogger().d("block service is running...");

          mBlockList = BlockUtils.getBlockList(getApplicationContext());

          String packageName;

          if (Build.VERSION.SDK_INT >= 21) {
            List<ActivityManager.AppTask> appTasks = getAppTasks();
            ActivityManager.AppTask appTask = appTasks.get(0);

            packageName = appTask.getTaskInfo().baseIntent.getComponent().getPackageName();
          } else {

            ComponentName topActivity = mActivityManager.getRunningTasks(1).get(0).topActivity;
            packageName = topActivity.getPackageName();
          }

          if (mBlockList != null && mBlockList.contains(packageName)) {
            Intent intent = new Intent(getApplicationContext(), WarningActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
          }

          mHandler.postDelayed(mRunnable, delayMillis);
        }
  protected Bitmap cachedIconHelper(ComponentName componentTask) {
    Drawable iconPackIcon = null;
    String cachedIconString = IconCacheHelper.getPreloadedComponentUri(mContext, componentTask);
    ResolveInfo rInfo =
        new Tools().cachedImageResolveInfo(mContext, componentTask.getPackageName());
    if (rInfo == null) return null;

    mCount++;

    if (cachedIconString == null) {
      if (ich == null) {
        ich = new IconCacheHelper(mContext);
        Tools.HangarLog("Loading new IconCacheHelper instance");
      }
      iconPackIcon = ich.getFullResIcon(rInfo);
      IconCacheHelper.preloadComponent(
          mContext,
          componentTask,
          Tools.drawableToBitmap(iconPackIcon),
          Tools.dpToPx(mContext, Settings.CACHED_ICON_SIZE));
    }
    if (iconPackIcon == null) {
      return IconCacheHelper.getPreloadedComponent(mContext, componentTask);
    } else {
      return Tools.drawableToBitmap(iconPackIcon);
    }
  }
Exemple #6
0
  @Override
  public ActivityInfo getReceiverInfo(ComponentName className, int flags)
      throws NameNotFoundException {
    String packageName = className.getPackageName();
    AndroidManifest androidManifest = androidManifests.get(packageName);
    String classString = className.getClassName();
    int index = classString.indexOf('.');
    if (index == -1) {
      classString = packageName + "." + classString;
    } else if (index == 0) {
      classString = packageName + classString;
    }

    ActivityInfo activityInfo = new ActivityInfo();
    activityInfo.packageName = packageName;
    activityInfo.name = classString;
    if ((flags & GET_META_DATA) != 0) {
      for (BroadcastReceiverData receiver : androidManifest.getBroadcastReceivers()) {
        if (receiver.getClassName().equals(classString)) {
          activityInfo.metaData = metaDataToBundle(receiver.getMetaData().getValueMap());
          break;
        }
      }
    }
    return activityInfo;
  }
  /**
   * As of ICE_CREAM_SANDWICH we are automatically adding padding to widgets targeting
   * ICE_CREAM_SANDWICH and higher. The new widget design guidelines strongly recommend that widget
   * developers do not add extra padding to their widgets. This will help achieve consistency among
   * widgets.
   *
   * <p>Note: this method is only needed by developers of AppWidgetHosts. The method is provided in
   * order for the AppWidgetHost to account for the automatic padding when computing the number of
   * cells to allocate to a particular widget.
   *
   * @param context the current context
   * @param component the component name of the widget
   * @param padding Rect in which to place the output, if null, a new Rect will be allocated and
   *     returned
   * @return default padding for this widget, in pixels
   */
  public static Rect getDefaultPaddingForWidget(
      Context context, ComponentName component, Rect padding) {
    PackageManager packageManager = context.getPackageManager();
    ApplicationInfo appInfo;

    if (padding == null) {
      padding = new Rect(0, 0, 0, 0);
    } else {
      padding.set(0, 0, 0, 0);
    }

    try {
      appInfo = packageManager.getApplicationInfo(component.getPackageName(), 0);
    } catch (NameNotFoundException e) {
      // if we can't find the package, return 0 padding
      return padding;
    }

    if (appInfo.targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
      Resources r = context.getResources();
      padding.left =
          r.getDimensionPixelSize(com.android.internal.R.dimen.default_app_widget_padding_left);
      padding.right =
          r.getDimensionPixelSize(com.android.internal.R.dimen.default_app_widget_padding_right);
      padding.top =
          r.getDimensionPixelSize(com.android.internal.R.dimen.default_app_widget_padding_top);
      padding.bottom =
          r.getDimensionPixelSize(com.android.internal.R.dimen.default_app_widget_padding_bottom);
    }
    return padding;
  }
  protected boolean cachedIconHelper(ImageView taskIcon, ComponentName componentTask) {
    Drawable iconPackIcon;
    String cachedIconString = IconCacheHelper.getPreloadedComponentUri(mContext, componentTask);
    ResolveInfo rInfo =
        new Tools().cachedImageResolveInfo(mContext, componentTask.getPackageName());
    if (rInfo == null) return false;

    mCount++;

    if (cachedIconString == null) {
      if (ich == null) {
        ich = new IconCacheHelper(mContext);
        Tools.HangarLog("Loading new IconCacheHelper instance");
      }
      iconPackIcon = ich.getFullResIcon(rInfo);
      cachedIconString =
          IconCacheHelper.preloadComponent(
              mContext,
              componentTask,
              Tools.drawableToBitmap(iconPackIcon),
              Tools.dpToPx(mContext, Settings.CACHED_ICON_SIZE));
    }
    taskIcon.setImageURI(Uri.parse(cachedIconString));
    return true;
  }
 private ComponentName getSearchWidgetProvider() {
   SearchManager searchManager =
       (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
   ComponentName searchComponent = searchManager.getGlobalSearchActivity();
   if (searchComponent == null) return null;
   return getProviderInPackage(searchComponent.getPackageName());
 }
  private boolean applicationIsRunning(Context context) {
    ActivityManager activityManager =
        (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
      List<RunningAppProcessInfo> processInfos = activityManager.getRunningAppProcesses();
      for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {
        if (processInfo.processName.equals(context.getApplicationContext().getPackageName())) {
          if (processInfo.importance
              == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            for (String d : processInfo.pkgList) {
              Log.v("ReactSystemNotification", "NotificationEventReceiver: ok: " + d);
              return true;
            }
          }
        }
      }
    } else {
      List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
      ComponentName componentInfo = taskInfo.get(0).topActivity;
      if (componentInfo.getPackageName().equals(context.getPackageName())) {
        return true;
      }
    }

    return false;
  }
  @Override
  public ActivityInfo getActivityInfo(ComponentName className, int flags)
      throws NameNotFoundException {
    String packageName = className.getPackageName();
    AndroidManifest androidManifest = androidManifests.get(packageName);
    String activityName = className.getClassName();
    ActivityData activityData = androidManifest.getActivityData(activityName);
    ActivityInfo activityInfo = new ActivityInfo();
    activityInfo.packageName = packageName;
    activityInfo.name = activityName;
    if (activityData != null) {
      activityInfo.parentActivityName = activityData.getParentActivityName();
      activityInfo.metaData = metaDataToBundle(activityData.getMetaData().getValueMap());
      ResourceIndex resourceIndex = shadowsAdapter.getResourceLoader().getResourceIndex();
      String themeRef;

      // Based on ShadowActivity
      if (activityData.getThemeRef() != null) {
        themeRef = activityData.getThemeRef();
      } else {
        themeRef = androidManifest.getThemeRef();
      }
      if (themeRef != null) {
        ResName style = ResName.qualifyResName(themeRef.replace("@", ""), packageName, "style");
        activityInfo.theme = resourceIndex.getResourceId(style);
      }
    }
    activityInfo.applicationInfo = getApplicationInfo(packageName, flags);
    return activityInfo;
  }
  @Override
  public void onReceive(Context context, Intent intent) {
    ExtensionManager extensionManager = ExtensionManager.getInstance(context);
    if (extensionManager.cleanupExtensions()) {
      LOGD(TAG, "Extension cleanup performed and action taken.");

      Intent widgetUpdateIntent = new Intent(context, DashClockService.class);
      widgetUpdateIntent.setAction(DashClockService.ACTION_UPDATE_WIDGETS);
      context.startService(widgetUpdateIntent);
    }

    // If this is a replacement or change in the package, update all active extensions from
    // this package.
    String action = intent.getAction();
    if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
        || Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
      String packageName = intent.getData().getSchemeSpecificPart();
      if (TextUtils.isEmpty(packageName)) {
        return;
      }

      List<ComponentName> activeExtensions = extensionManager.getActiveExtensionNames();
      for (ComponentName cn : activeExtensions) {
        if (packageName.equals(cn.getPackageName())) {
          Intent extensionUpdateIntent = new Intent(context, DashClockService.class);
          extensionUpdateIntent.setAction(DashClockService.ACTION_UPDATE_EXTENSIONS);
          extensionUpdateIntent.putExtra(
              DashClockService.EXTRA_COMPONENT_NAME, cn.flattenToShortString());
          context.startService(extensionUpdateIntent);
        }
      }
    }
  }
 static boolean isSystemApp(Context context, Intent intent) {
   PackageManager pm = context.getPackageManager();
   ComponentName cn = intent.getComponent();
   String packageName = null;
   if (cn == null) {
     ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
     if ((info != null) && (info.activityInfo != null)) {
       packageName = info.activityInfo.packageName;
     }
   } else {
     packageName = cn.getPackageName();
   }
   if (packageName != null) {
     try {
       PackageInfo info = pm.getPackageInfo(packageName, 0);
       return (info != null)
           && (info.applicationInfo != null)
           && ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
     } catch (NameNotFoundException e) {
       return false;
     }
   } else {
     return false;
   }
 }
 private Drawable getActivityIcon(ComponentName componentname)
 {
     Object obj = mContext.getPackageManager();
     ActivityInfo activityinfo;
     int i;
     try
     {
         activityinfo = ((PackageManager) (obj)).getActivityInfo(componentname, 128);
     }
     // Misplaced declaration of an exception variable
     catch (ComponentName componentname)
     {
         componentname.toString();
         return null;
     }
     i = activityinfo.getIconResource();
     if (i == 0)
     {
         return null;
     }
     obj = ((PackageManager) (obj)).getDrawable(componentname.getPackageName(), i, activityinfo.applicationInfo);
     if (obj == null)
     {
         (new StringBuilder()).append("Invalid icon resource ").append(i).append(" for ").append(componentname.flattenToShortString()).toString();
         return null;
     } else
     {
         return ((Drawable) (obj));
     }
 }
Exemple #15
0
  /** Add and remove icons for this package which has been updated. */
  public void updatePackage(Context context, String packageName) {
    final List<ResolveInfo> matches = findActivitiesForPackage(context, packageName);
    if (matches.size() > 0) {
      // Find disabled/removed activities and remove them from data and add them
      // to the removed list.
      for (int i = data.size() - 1; i >= 0; i--) {
        final AppInfo applicationInfo = data.get(i);
        final ComponentName component = applicationInfo.intent.getComponent();
        if (packageName.equals(component.getPackageName())) {
          if (!findActivity(matches, component)) {
            removed.add(applicationInfo);
            mIconCache.remove(component);
            data.remove(i);
          }
        }
      }

      // Find enabled activities and add them to the adapter
      // Also updates existing activities with new labels/icons
      int count = matches.size();
      for (int i = 0; i < count; i++) {
        final ResolveInfo info = matches.get(i);
        AppInfo applicationInfo =
            findApplicationInfoLocked(
                info.activityInfo.applicationInfo.packageName, info.activityInfo.name);
        if (applicationInfo == null) {
          add(new AppInfo(context.getPackageManager(), info, mIconCache, null));
        } else {
          mIconCache.remove(applicationInfo.componentName);
          mIconCache.getTitleAndIcon(applicationInfo, info, null);
          modified.add(applicationInfo);
        }
      }
    } else {
      // Remove all data for this package.
      for (int i = data.size() - 1; i >= 0; i--) {
        final AppInfo applicationInfo = data.get(i);
        final ComponentName component = applicationInfo.intent.getComponent();
        if (packageName.equals(component.getPackageName())) {
          removed.add(applicationInfo);
          mIconCache.remove(component);
          data.remove(i);
        }
      }
    }
  }
 @Override
 public ProviderInfo getProviderInfo(ComponentName className, int flags) throws RemoteException {
   waitForReadyInner();
   try {
     String pkg = getAndCheckCallingPkg(className.getPackageName());
     if (pkg != null) {
       enforcePluginFileExists();
       PluginPackageParser parser = mPluginCache.get(className.getPackageName());
       if (parser != null) {
         return parser.getProviderInfo(className, flags);
       }
     }
   } catch (Exception e) {
     handleException(e);
   }
   return null;
 }
  /** Add and remove icons for this package which has been updated. */
  public void updatePackage(Context context, String packageName, UserHandleCompat user) {
    final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
    final List<LauncherActivityInfoCompat> matches =
        launcherApps.getActivityList(packageName, user);
    if (matches.size() > 0) {
      // Find disabled/removed activities and remove them from data and add them
      // to the removed list.
      for (int i = data.size() - 1; i >= 0; i--) {
        final AppInfo applicationInfo = data.get(i);
        final ComponentName component = applicationInfo.intent.getComponent();
        if (user.equals(applicationInfo.user) && packageName.equals(component.getPackageName())) {
          if (!findActivity(matches, component)) {
            removed.add(applicationInfo);
            data.remove(i);
          }
        }
      }

      // Find enabled activities and add them to the adapter
      // Also updates existing activities with new labels/icons
      for (final LauncherActivityInfoCompat info : matches) {
        AppInfo applicationInfo =
            findApplicationInfoLocked(
                info.getComponentName().getPackageName(),
                user,
                info.getComponentName().getClassName());
        if (applicationInfo == null) {
          add(new AppInfo(context, info, user, mIconCache));
        } else {
          mIconCache.getTitleAndIcon(applicationInfo, info, true /* useLowResIcon */);
          modified.add(applicationInfo);
        }
      }
    } else {
      // Remove all data for this package.
      for (int i = data.size() - 1; i >= 0; i--) {
        final AppInfo applicationInfo = data.get(i);
        final ComponentName component = applicationInfo.intent.getComponent();
        if (user.equals(applicationInfo.user) && packageName.equals(component.getPackageName())) {
          removed.add(applicationInfo);
          mIconCache.remove(component, user);
          data.remove(i);
        }
      }
    }
  }
 private static void executeBadgeByBroadcast(
     Context context, ComponentName componentName, int badgeCount) {
   Intent intent = new Intent(INTENT_ACTION);
   intent.putExtra(INTENT_EXTRA_PACKAGE_NAME, componentName.getPackageName());
   intent.putExtra(INTENT_EXTRA_ACTIVITY_NAME, componentName.getClassName());
   intent.putExtra(INTENT_EXTRA_MESSAGE, String.valueOf(badgeCount));
   intent.putExtra(INTENT_EXTRA_SHOW_MESSAGE, badgeCount > 0);
   context.sendBroadcast(intent);
 }
 @Override
 public Object call(Object who, Method method, Object... args) throws Throwable {
   ComponentName componentName = (ComponentName) args[0];
   int flags = (int) args[1];
   if (getHostPkg().equals(componentName.getPackageName())) {
     return method.invoke(who, args);
   }
   int userId = VUserHandle.myUserId();
   return VPackageManager.get().getProviderInfo(componentName, flags, userId);
 }
Exemple #20
0
 public static Intent m1120a(Context context, ComponentName componentName) {
   String b = m1123b(context, componentName);
   if (b == null) {
     return null;
   }
   ComponentName componentName2 = new ComponentName(componentName.getPackageName(), b);
   return m1123b(context, componentName2) == null
       ? C0168n.m1535a(componentName2)
       : new Intent().setComponent(componentName2);
 }
Exemple #21
0
 /** Find an ApplicationInfo object for the given packageName and className. */
 private AppInfo findApplicationInfoLocked(String packageName, String className) {
   for (AppInfo info : data) {
     final ComponentName component = info.intent.getComponent();
     if (packageName.equals(component.getPackageName())
         && className.equals(component.getClassName())) {
       return info;
     }
   }
   return null;
 }
  public static void load(Context ctx, String pkg)
      throws NameNotFoundException, XmlPullParserException, IOException {

    sPackageName = pkg;
    Context extCtx = ctx.createPackageContext(pkg, Context.CONTEXT_IGNORE_SECURITY);
    sRes = extCtx.getResources();
    int id = sRes.getIdentifier("appfilter", "xml", sPackageName);
    boolean loadFromAssets = false;
    if (id != 0) {
      sParser = sRes.getXml(id);
    } else {
      loadFromAssets = true;
      Log.e(
          TAG,
          "Failed to get appfilter.xml from resources of package "
              + sPackageName
              + ", attempting load from assets...");
    }

    if (loadFromAssets) {
      InputStream is = sRes.getAssets().open("appfilter.xml");
      sParser = XmlPullParserFactory.newInstance().newPullParser();
      sParser.setInput(is, null);
    }

    if (sParser == null) throw new XmlPullParserException("Parser is null!");

    SharedPreferences prefs = ctx.getSharedPreferences("icon_pack", Context.MODE_PRIVATE);
    prefs.edit().clear().commit();
    SharedPreferences.Editor editor = prefs.edit();

    while (sParser.getEventType() != XmlPullParser.END_DOCUMENT) {
      int type = sParser.getEventType();
      switch (type) {
        case XmlPullParser.START_TAG:
          String currentComponent = sParser.getAttributeValue(null, "component");
          String drawable = sParser.getAttributeValue(null, "drawable");
          if (currentComponent != null) {
            ComponentName cmpName = ComponentNameParser.parse(currentComponent);
            if (cmpName != null && drawable != null) {
              int drawableId = sRes.getIdentifier(drawable, "drawable", sPackageName);
              if (drawableId != 0) {
                // TODO: replace by SQL database
                String pref = cmpName.getPackageName() + "/" + cmpName.getClassName();
                editor.putInt(pref, drawableId);
              }
            }
          }
          break;
      }

      sParser.next();
    }
    editor.commit();
  }
Exemple #23
0
 public static Intent a(Context paramContext, ComponentName paramComponentName) {
   String str = b(paramContext, paramComponentName);
   if (str == null) {
     return null;
   }
   paramComponentName = new ComponentName(paramComponentName.getPackageName(), str);
   if (b(paramContext, paramComponentName) == null) {
     return a.makeMainActivity(paramComponentName);
   }
   return new Intent().setComponent(paramComponentName);
 }
Exemple #24
0
  public static String getTopPackage(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    String ret = "";
    try {
      ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
      ret = cn.getPackageName();
    } catch (Exception e) {

    }
    return ret;
  }
Exemple #25
0
 public static boolean isApplicationBroughtToBackground(Context context) {
   ActivityManager am = (ActivityManager) context.getSystemService("activity");
   List tasks = am.getRunningTasks(1);
   if (!tasks.isEmpty()) {
     ComponentName topActivity = ((ActivityManager.RunningTaskInfo) tasks.get(0)).topActivity;
     if (!topActivity.getPackageName().equals(context.getPackageName())) {
       return true;
     }
   }
   return false;
 }
 /** Remove the apps for the given apk identified by packageName. */
 public void removePackage(String packageName, UserHandleCompat user) {
   final List<AppInfo> data = this.data;
   for (int i = data.size() - 1; i >= 0; i--) {
     AppInfo info = data.get(i);
     final ComponentName component = info.intent.getComponent();
     if (info.user.equals(user) && packageName.equals(component.getPackageName())) {
       removed.add(info);
       data.remove(i);
     }
   }
 }
 /**
  * whether application is in background
  *
  * <ul>
  *   <li>need use permission android.permission.GET_TASKS in Manifest.xml
  * </ul>
  *
  * @param context
  * @return if application is in background return true, otherwise return false
  */
 public static boolean isApplicationInBackground(Context context) {
   ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   List<RunningTaskInfo> taskList = am.getRunningTasks(1);
   if (taskList != null && !taskList.isEmpty()) {
     ComponentName topActivity = taskList.get(0).topActivity;
     if (topActivity != null && !topActivity.getPackageName().equals(context.getPackageName())) {
       return true;
     }
   }
   return false;
 }
 /** 判断当前应用程序处于前台还是后台 false为在后台运行 */
 public static boolean isApplicationBroughtToBackground(final Context context, String pakname) {
   ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   List<RunningTaskInfo> tasks = am.getRunningTasks(1);
   if (!tasks.isEmpty()) {
     ComponentName topActivity = tasks.get(0).topActivity;
     if (!topActivity.getPackageName().equals(pakname)) {
       return true;
     }
   }
   return false;
 }
Exemple #29
0
 /**
  * 判断当前App处于前台还是后台
  *
  * <p>需添加<uses-permission android:name="android.permission.GET_TASKS"/>
  *
  * <p>并且必须是系统应用该方法才有效
  */
 public static boolean isAppBackground(Context context) {
   ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   @SuppressWarnings("deprecation")
   List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
   if (!tasks.isEmpty()) {
     ComponentName topActivity = tasks.get(0).topActivity;
     if (!topActivity.getPackageName().equals(context.getPackageName())) {
       return true;
     }
   }
   return false;
 }
  private boolean appEstaRodando(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);

    if (!tasks.isEmpty()) {
      ComponentName topActivity = tasks.get(0).topActivity;
      if (!topActivity.getPackageName().equals(context.getPackageName())) {
        return false;
      }
    }
    return true;
  }