Beispiel #1
1
  public void onCreate(Activity activity, Bundle savedInstanceState) {
    PackageManager manager = activity.getBaseContext().getPackageManager();
    String[] keys = {"tapjoyAppID", "tapjoySecretKey"};
    try {
      Bundle meta =
          manager.getApplicationInfo(
                  activity.getApplicationContext().getPackageName(), PackageManager.GET_META_DATA)
              .metaData;
      for (String k : keys) {
        if (meta.containsKey(k)) {
          manifestKeyMap.put(k, meta.get(k).toString());
        }
      }
    } catch (Exception e) {
      logger.log("Exception while loading manifest keys:", e);
    }

    String tapJoyAppID = manifestKeyMap.get("tapjoyAppID");
    String tapJoySecretKey = manifestKeyMap.get("tapjoySecretKey");

    logger.log("{tapjoy} Installing for appID:", tapJoyAppID);

    // Enables logging to the console.
    // TapjoyLog.enableLogging(true);

    // Connect with the Tapjoy server.
    TapjoyConnect.requestTapjoyConnect(_ctx, tapJoyAppID, tapJoySecretKey);
  }
  @SuppressLint("NewApi")
  public DiskLruCache(Context context, String cacheName, long cacheSize) {
    mContext = context;
    mCacheName = cacheName;
    mCacheSize = cacheSize;

    int version;
    PackageManager pm = context.getPackageManager();
    try {
      PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
      version = pi.versionCode;
    } catch (NameNotFoundException e) {
      version = 1;
    }

    AsyncTask<Integer, Object, Object> task =
        new AsyncTask<Integer, Object, Object>() {
          @Override
          protected Object doInBackground(Integer... params) {
            initDiskCache(params[0]);
            return null;
          }
        };

    if (Build.VERSION.SDK_INT >= 11) {
      task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, version);
    } else {
      task.execute(version);
    }
  }
  /**
   * Switch to parent fragment and store the grand parent's info
   *
   * @param className name of the activity wrapper for the parent fragment.
   */
  private void switchToParent(String className) {
    final ComponentName cn = new ComponentName(this, className);
    try {
      final PackageManager pm = getPackageManager();
      final ActivityInfo parentInfo = pm.getActivityInfo(cn, PackageManager.GET_META_DATA);

      if (parentInfo != null && parentInfo.metaData != null) {
        String fragmentClass = parentInfo.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS);
        CharSequence fragmentTitle = parentInfo.loadLabel(pm);
        Header parentHeader = new Header();
        parentHeader.fragment = fragmentClass;
        parentHeader.title = fragmentTitle;
        mCurrentHeader = parentHeader;

        switchToHeaderLocal(parentHeader);
        highlightHeader(mTopLevelHeaderId);

        mParentHeader = new Header();
        mParentHeader.fragment = parentInfo.metaData.getString(META_DATA_KEY_PARENT_FRAGMENT_CLASS);
        mParentHeader.title = parentInfo.metaData.getString(META_DATA_KEY_PARENT_TITLE);
      }
    } catch (NameNotFoundException nnfe) {
      Log.w(LOG_TAG, "Could not find parent activity : " + className);
    }
  }
Beispiel #4
0
 private static void checkReceiver(Context context, Set<String> allowedReceivers, String action) {
   PackageManager pm = context.getPackageManager();
   String packageName = context.getPackageName();
   Intent intent = new Intent(action);
   intent.setPackage(packageName);
   List<ResolveInfo> receivers =
       pm.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS);
   if (receivers.isEmpty()) {
     throw new IllegalStateException("No receivers for action " + action);
   }
   if (Log.isLoggable(TAG, Log.VERBOSE)) {
     Log.v(TAG, "Found " + receivers.size() + " receivers for action " + action);
   }
   // make sure receivers match
   for (ResolveInfo receiver : receivers) {
     String name = receiver.activityInfo.name;
     if (!allowedReceivers.contains(name)) {
       throw new IllegalStateException(
           "Receiver "
               + name
               + " is not set with permission "
               + GCMConstants.PERMISSION_GCM_INTENTS);
     }
   }
 }
Beispiel #5
0
  protected List getData() {
    List<Map> myData = new ArrayList<Map>();

    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.setPackage(getPackageName());
    mainIntent.addCategory(Intent.CATEGORY_SAMPLE_CODE);

    PackageManager pm = getPackageManager();
    List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

    if (null == list) return myData;

    int len = list.size();

    String pkg = getPackageName();
    for (int i = 0; i < len; i++) {
      ResolveInfo info = list.get(i);
      CharSequence labelSeq = info.loadLabel(pm);
      if (info.activityInfo.packageName.equals(pkg) == false) {
        continue;
      }
      String label = labelSeq != null ? labelSeq.toString() : info.activityInfo.name;

      addItem(
          myData,
          label,
          activityIntent(info.activityInfo.applicationInfo.packageName, info.activityInfo.name));
    }

    Collections.sort(myData, sDisplayNameComparator);

    return myData;
  }
 /**
  * Indicates whether the specified action can be used as an intent. This method queries the
  * package manager for installed packages that can respond to an intent with the specified action.
  * If no suitable package is found, this method returns false.
  * http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
  *
  * @param context The application's environment.
  * @param action The Intent action to check for availability.
  * @return True if an Intent with the specified action can be sent and responded to, false
  *     otherwise.
  */
 public static boolean isIntentAvailable(Context context, String action) {
   final PackageManager packageManager = context.getPackageManager();
   final Intent intent = new Intent(action);
   List<ResolveInfo> list =
       packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
   return list.size() > 0;
 }
  /** {@inheritDoc} */
  @Override
  public void openActivityOrFragment(final Intent intent) {
    final PackageManager pm = getPackageManager();
    List<ResolveInfo> resolveInfoList =
        pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resolveInfoList) {
      final FragmentReplaceInfo fri =
          onSubstituteFragmentForActivityLaunch(resolveInfo.activityInfo.name);
      if (fri != null) {
        final Bundle arguments = intentToFragmentArguments(intent);
        final FragmentManager fm = getSupportFragmentManager();

        try {
          Fragment fragment = (Fragment) fri.getFragmentClass().newInstance();
          fragment.setArguments(arguments);

          FragmentTransaction ft = fm.beginTransaction();
          ft.replace(fri.getContainerId(), fragment, fri.getFragmentTag());
          onBeforeCommitReplaceFragment(fm, ft, fragment);
          ft.commit();
        } catch (InstantiationException e) {
          throw new IllegalStateException("Error creating new fragment.", e);
        } catch (IllegalAccessException e) {
          throw new IllegalStateException("Error creating new fragment.", e);
        }
        return;
      }
    }
    super.openActivityOrFragment(intent);
  }
    @Override
    public void onDownloadFinished(Context context, DownloadsUtil.DownloadInfo info) {
      File localFile = new File(info.localFilename);
      if (!localFile.isFile()) return;

      if (moduleVersion.md5sum != null && !moduleVersion.md5sum.isEmpty()) {
        try {
          String actualMd5Sum = HashUtil.md5(localFile);
          if (!moduleVersion.md5sum.equals(actualMd5Sum)) {
            Toast.makeText(
                    context,
                    context.getString(
                        R.string.download_md5sum_incorrect, actualMd5Sum, moduleVersion.md5sum),
                    Toast.LENGTH_LONG)
                .show();
            DownloadsUtil.removeById(context, info.id);
            return;
          }
        } catch (Exception e) {
          Toast.makeText(
                  context,
                  context.getString(R.string.download_could_not_read_file, e.getMessage()),
                  Toast.LENGTH_LONG)
              .show();
          DownloadsUtil.removeById(context, info.id);
          return;
        }
      }

      PackageManager pm = context.getPackageManager();
      PackageInfo packageInfo = pm.getPackageArchiveInfo(info.localFilename, 0);

      if (packageInfo == null) {
        Toast.makeText(context, R.string.download_no_valid_apk, Toast.LENGTH_LONG).show();
        DownloadsUtil.removeById(context, info.id);
        return;
      }

      if (!packageInfo.packageName.equals(moduleVersion.module.packageName)) {
        Toast.makeText(
                context,
                context.getString(
                    R.string.download_incorrect_package_name,
                    packageInfo.packageName,
                    moduleVersion.module.packageName),
                Toast.LENGTH_LONG)
            .show();
        DownloadsUtil.removeById(context, info.id);
        return;
      }

      Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
      installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      installIntent.setDataAndType(Uri.fromFile(localFile), DownloadsUtil.MIME_TYPE_APK);
      // installIntent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
      // installIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
      installIntent.putExtra(
          Intent.EXTRA_INSTALLER_PACKAGE_NAME, context.getApplicationInfo().packageName);
      context.startActivity(installIntent);
    }
Beispiel #9
0
  final void openGoogleShopper(String query) {

    // Construct Intent to launch Shopper
    Intent intent = new Intent(Intent.ACTION_SEARCH);
    intent.setClassName(GOOGLE_SHOPPER_PACKAGE, GOOGLE_SHOPPER_ACTIVITY);
    intent.putExtra(SearchManager.QUERY, query);

    // Is it available?
    PackageManager pm = activity.getPackageManager();
    Collection<?> availableApps =
        pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

    if (availableApps != null && !availableApps.isEmpty()) {
      // If something can handle it, start it
      activity.startActivity(intent);
    } else {
      // Otherwise offer to install it from Market.
      AlertDialog.Builder builder = new AlertDialog.Builder(activity);
      builder.setTitle(R.string.msg_google_shopper_missing);
      builder.setMessage(R.string.msg_install_google_shopper);
      builder.setIcon(R.drawable.shopper_icon);
      builder.setPositiveButton(R.string.button_ok, shopperMarketListener);
      builder.setNegativeButton(R.string.button_cancel, null);
      builder.show();
    }
  }
  @Override
  public void init() {
    try {
      this.loadOrCreateLastRun();
    } catch (IOException e) {
      Log.w(TAG, "couldn't read lastrun.txt", e);
    }
    makeSureDirectoryExists(ORIGINAL_EXTRACTED_DIR);
    makeSureDirectoryExists(TEMP_MODDED_DIR);

    PackageManager pm = WoGInitData.getPackageManager();

    String originalLocation = null;
    for (ApplicationInfo app : pm.getInstalledApplications(0)) {
      if (app.packageName.equals(WOG_PACKAGE_NAME)) {
        Log.i(TAG, String.format("Found World of Goo apk in %s", app.sourceDir));
        originalLocation = app.sourceDir;
        WOG_APK_FILE = new File(originalLocation);
        isWogFound = true;
      }
    }
    if (!isWogFound) {
      Log.i(TAG, "World of Goo apk not found. Is it installed?");
      return;
    }
    if (lastRunData.get("original_apk_extracted").equals("true")) {
      return;
    }
    forceClean();
    lastRunData.put("original_apk_extracted", "true");
    saveLastRun();
  }
Beispiel #11
0
  public void init() {
    instance = this;

    session = new HashMap<String, Object>();
    activityManager = new ArrayList<Activity>();
    if (fileDir != null) {
      imageLoader =
          new ImageLoader(
              instance, defaultImageId, fileDir); // 使用ImageLoader组件时,设置defaultImageId、fileDir
    } else {
      imageLoader = new ImageLoader(instance, defaultImageId); // 使用ImageLoader组件时,设置defaultImageId
    }

    PackageManager manager = this.getPackageManager();
    try {
      PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
      deviceid = getDeviceId();
      osVersion = Build.VERSION.RELEASE;
      mobileType = Build.MODEL;
      if (null != info) {
        version = info.versionName;
        versionCode = info.versionCode;
      }
    } catch (NameNotFoundException e) {
      e.printStackTrace();
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_student_guanyu);
    context = this;

    TextView titletext = (TextView) findViewById(R.id.title_text);
    titletext.setText("关于师课家教宝");

    findViewById(R.id.gongneng_jieshao_btn).setOnClickListener(listener);
    findViewById(R.id.faq_btn).setOnClickListener(listener);
    findViewById(R.id.wenti_fankui_btn).setOnClickListener(listener);
    findViewById(R.id.left_btn).setOnClickListener(listener);

    PackageManager packageManager = getPackageManager();
    // getPackageName()是你当前类的包名,0代表是获取版本信息
    PackageInfo packInfo = null;
    try {
      packInfo = packageManager.getPackageInfo(getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
    String localVersion = packInfo.versionName;
    TextView versiontext = (TextView) findViewById(R.id.ver_name);
    versiontext.setText("当前版本: V" + localVersion);

    Sofy_Info();
  }
Beispiel #13
0
 private void getAllGameApp() {
   List<PackageInfo> apps = new ArrayList<PackageInfo>();
   PackageManager pManager = getPackageManager();
   // 获取手机内所有应用
   List<PackageInfo> packlist = pManager.getInstalledPackages(0);
   for (int i = 0; i < packlist.size(); i++) {
     PackageInfo pak = packlist.get(i);
     // if()里的值如果==0则为自己装的程序,否则为系统工程自带
     if ((pak.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
       // 添加自己已经安装的应用程序
       apps.add(pak);
       String appName = pManager.getApplicationLabel(pak.applicationInfo).toString();
       if (MyApp.gnList.contains(appName)) {
         AppsItemInfo aii = new AppsItemInfo();
         aii.setIcon(pManager.getApplicationIcon(pak.applicationInfo));
         aii.setLabel(pManager.getApplicationLabel(pak.applicationInfo).toString());
         aii.setPackageName(pak.applicationInfo.packageName);
         String filePath = pak.applicationInfo.publicSourceDir;
         aii.setSize(
             Util.round(new File(filePath).length() * 1.0 / (1024 * 1024), 2, BigDecimal.ROUND_UP)
                 + "MB");
         appList.add(aii);
       }
     }
   }
 }
Beispiel #14
0
  public int addIntentOptions(
      int group,
      int id,
      int categoryOrder,
      ComponentName caller,
      Intent[] specifics,
      Intent intent,
      int flags,
      MenuItem[] outSpecificItems) {
    PackageManager pm = mContext.getPackageManager();
    final List<ResolveInfo> lri = pm.queryIntentActivityOptions(caller, specifics, intent, 0);
    final int N = lri != null ? lri.size() : 0;

    if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
      removeGroup(group);
    }

    for (int i = 0; i < N; i++) {
      final ResolveInfo ri = lri.get(i);
      Intent rintent = new Intent(ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
      rintent.setComponent(
          new ComponentName(ri.activityInfo.applicationInfo.packageName, ri.activityInfo.name));
      final MenuItem item =
          add(group, id, categoryOrder, ri.loadLabel(pm))
              .setIcon(ri.loadIcon(pm))
              .setIntent(rintent);
      if (outSpecificItems != null && ri.specificIndex >= 0) {
        outSpecificItems[ri.specificIndex] = item;
      }
    }

    return N;
  }
  private static List<String> getPackageDatas(Context context) {

    List<String> packageDatas = new ArrayList<String>();

    PackageManager packageManager = context.getPackageManager();
    List<ApplicationInfo> list =
        packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
    for (ApplicationInfo appInfo : list) {
      StringBuffer data = new StringBuffer();
      try {
        PackageInfo packageInfo =
            packageManager.getPackageInfo(appInfo.packageName, PackageManager.GET_META_DATA);
        data.append(appInfo.packageName); // パッケージ名
        data.append(",");
        data.append(packageInfo.versionName); // バージョン
      } catch (NameNotFoundException e) {
        e.printStackTrace();
      }
      packageDatas.add(data.toString());
    }
    Collections.sort(
        packageDatas,
        new Comparator<String>() {

          public int compare(String lhs, String rhs) {
            return lhs.compareTo(rhs);
          }
        });
    return packageDatas;
  }
Beispiel #16
0
  /**
   * Searches the given package for a resource to use to replace the Drawable on the target with the
   * given resource id
   *
   * @param component of the .apk that contains the resource
   * @param name of the metadata in the .apk
   * @param existingResId the resource id of the target to search for
   * @return true if found in the given package and replaced at least one target Drawables
   */
  public boolean replaceTargetDrawablesIfPresent(
      ComponentName component, String name, int existingResId) {
    if (existingResId == 0) return false;

    boolean replaced = false;
    if (component != null) {
      try {
        PackageManager packageManager = getContext().getPackageManager();
        // Look for the search icon specified in the activity meta-data
        Bundle metaData =
            packageManager.getActivityInfo(component, PackageManager.GET_META_DATA).metaData;
        if (metaData != null) {
          int iconResId = metaData.getInt(name);
          if (iconResId != 0) {
            Resources res = packageManager.getResourcesForActivity(component);
            replaced = replaceTargetDrawables(res, existingResId, iconResId);
          }
        }
      } catch (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);
      }
    }
    if (!replaced) {
      // Restore the original drawable
      replaceTargetDrawables(getContext().getResources(), existingResId, existingResId);
    }
    return replaced;
  }
 public static ActivityInfo[] getActivityList(Context context, String packageName)
     throws NameNotFoundException {
   PackageManager pm = context.getPackageManager();
   PackageInfo info = pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
   ActivityInfo[] list = info.activities;
   return list;
 }
 /**
  * 判断系统中是否存在可以启动的相机应用
  *
  * @return 存在返回true,不存在返回false
  */
 public boolean hasCamera() {
   PackageManager packageManager = mActivity.getPackageManager();
   Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
   List<ResolveInfo> list =
       packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
   return list.size() > 0;
 }
Beispiel #19
0
  /**
   * This method create a intent for posting a tweet on twitter by using the twitter app.
   *
   * @param tweetMessage message which should be posted
   */
  public static void tweetWithApp(String tweetMessage) {
    if (tweetMessage != null) {
      Intent tweetIntent = new Intent(Intent.ACTION_SEND);
      tweetIntent.putExtra(Intent.EXTRA_TEXT, tweetMessage);
      tweetIntent.setType("text/plain");
      tweetIntent.setFlags(
          Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

      PackageManager packManager = CreateContextForResource.getContext().getPackageManager();
      List<ResolveInfo> resolvedInfoList =
          packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);

      boolean resolved = false;
      for (ResolveInfo resolveInfo : resolvedInfoList) {
        if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) {
          tweetIntent.setClassName(
              resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name);
          resolved = true;
          break;
        }
      }
      if (resolved) {
        CreateContextForResource.getContext().startActivity(tweetIntent);
      } else {
        Toast.makeText(
                CreateContextForResource.getContext(),
                CreateContextForResource.getStringFromID(R.string.twitter_not_found),
                Toast.LENGTH_LONG)
            .show();
      }
    }
  }
Beispiel #20
0
  /** Generate a User Agent */
  public static String getUserAgent() {

    Context context = TramHunterApplication.getContext();
    final PackageManager pm = context.getPackageManager();

    String packageName = "Unknown";
    String packageVersion = "Unknown";
    String applicationName = "Unknown";

    String androidVersion = android.os.Build.VERSION.RELEASE;

    if (androidVersion == null) androidVersion = "N/A";

    try {

      packageName = context.getPackageName();

      // App info
      ApplicationInfo ai = pm.getApplicationInfo(packageName, 0);
      applicationName = (String) pm.getApplicationLabel(ai);

      // Package info
      PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0);
      packageVersion = pi.versionName;
    } catch (NameNotFoundException e) {
      return "Unknown";
    }

    return String.format("%s/%s (Android %s)", applicationName, packageVersion, androidVersion);
  }
Beispiel #21
0
 public static String getDefaultPkgName(MainAppContext appContext) {
   String defaultPkgName = null;
   PackageManager pm = appContext.mContainerContext.getPackageManager();
   Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
   List<ResolveInfo> resolveInfos =
       pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
   if (resolveInfos != null) {
     for (int i = 0; i < resolveInfos.size(); i++) {
       if ((resolveInfos.get(i).activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
           > 0) {
         defaultPkgName = resolveInfos.get(i).activityInfo.packageName;
         return defaultPkgName;
       }
     }
   } else {
     intent = new Intent(Intent.ACTION_MAIN);
     intent.addCategory(Intent.CATEGORY_APP_MUSIC);
     resolveInfos = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
     for (int i = 0; i < resolveInfos.size(); i++) {
       if ((resolveInfos.get(i).activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
           > 0) {
         defaultPkgName = resolveInfos.get(i).activityInfo.packageName;
         return defaultPkgName;
       }
     }
   }
   return null;
 }
Beispiel #22
0
  private void loadThirdPartyResources() {
    ImPluginHelper helper = ImPluginHelper.getInstance(this);
    helper.loadAvailablePlugins();
    ArrayList<ImPlugin> pluginList = helper.getPluginObjects();
    ArrayList<ImPluginInfo> infoList = helper.getPluginsInfo();
    int N = pluginList.size();
    PackageManager pm = getPackageManager();
    for (int i = 0; i < N; i++) {
      ImPlugin plugin = pluginList.get(i);
      ImPluginInfo pluginInfo = infoList.get(i);

      try {
        Resources packageRes = pm.getResourcesForApplication(pluginInfo.mPackageName);

        Map<Integer, Integer> resMap = plugin.getResourceMap();
        int[] smileyIcons = plugin.getSmileyIconIds();

        BrandingResources res =
            new BrandingResources(packageRes, resMap, smileyIcons, mDefaultBrandingResources);
        mBrandingResources.put(pluginInfo.mProviderName, res);
      } catch (NameNotFoundException e) {
        Log.e(LOG_TAG, "Failed to load third party resources.", e);
      }
    }
  }
  /** Must not hold the Context. */
  public ApplicationInfo(
      PackageManager pm,
      ResolveInfo info,
      IconCache iconCache,
      HashMap<Object, CharSequence> labelCache) {
    final String packageName = info.activityInfo.applicationInfo.packageName;

    this.componentName = new ComponentName(packageName, info.activityInfo.name);
    this.container = ItemInfo.NO_ID;
    this.setActivity(
        componentName, Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

    try {
      int appFlags = pm.getApplicationInfo(packageName, 0).flags;
      if ((appFlags & android.content.pm.ApplicationInfo.FLAG_SYSTEM) == 0) {
        flags |= DOWNLOADED_FLAG;

        if ((appFlags & android.content.pm.ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
          flags |= UPDATED_SYSTEM_APP_FLAG;
        }
      }
      firstInstallTime = pm.getPackageInfo(packageName, 0).firstInstallTime;
    } catch (NameNotFoundException e) {
      Log.d(TAG, "PackageManager.getApplicationInfo failed for " + packageName);
    }

    iconCache.getTitleAndIcon(this, info, labelCache);
  }
Beispiel #24
0
 /**
  * check the application process name if process name is not qualified, then we think it is a
  * service process and we will not init SDK
  *
  * @param pID
  * @return
  */
 private String getAppName(int pID) {
   String processName = null;
   ActivityManager am = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
   List l = am.getRunningAppProcesses();
   Iterator i = l.iterator();
   PackageManager pm = appContext.getPackageManager();
   while (i.hasNext()) {
     ActivityManager.RunningAppProcessInfo info =
         (ActivityManager.RunningAppProcessInfo) (i.next());
     try {
       if (info.pid == pID) {
         CharSequence c =
             pm.getApplicationLabel(
                 pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
         // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
         // info.processName +"  Label: "+c.toString());
         // processName = c.toString();
         processName = info.processName;
         return processName;
       }
     } catch (Exception e) {
       // Log.d("Process", "Error>> :"+ e.toString());
     }
   }
   return processName;
 }
  /*
     This test checks to make sure that the content provider is registered correctly.
     Students: Uncomment this test to make sure you've correctly registered the WeatherProvider.
  */
  public void testProviderRegistry() {
    PackageManager pm = mContext.getPackageManager();

    // We define the component name based on the package name from the context and the
    // WeatherProvider class.
    ComponentName componentName =
        new ComponentName(mContext.getPackageName(), WeatherProvider.class.getName());
    try {
      // Fetch the provider info using the component name from the PackageManager
      // This throws an exception if the provider isn't registered.
      ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0);

      // Make sure that the registered authority matches the authority from the Contract.
      assertEquals(
          "Error: WeatherProvider registered with authority: "
              + providerInfo.authority
              + " instead of authority: "
              + WeatherContract.CONTENT_AUTHORITY,
          providerInfo.authority,
          WeatherContract.CONTENT_AUTHORITY);
    } catch (PackageManager.NameNotFoundException e) {
      // I guess the provider isn't registered correctly.
      assertTrue("Error: WeatherProvider not registered at " + mContext.getPackageName(), false);
    }
  }
Beispiel #26
0
 public static List<AppInfo> getAppInfoMd5(Context context) {
   PackageManager pm = context.getPackageManager();
   // 所有的安装在系统上的应用程序包信息。
   List<PackageInfo> packInfos = pm.getInstalledPackages(0);
   List<AppInfo> appInfos = new ArrayList<AppInfo>();
   for (PackageInfo packInfo : packInfos) {
     AppInfo appInfo = new AppInfo();
     // packInfo 相当于一个应用程序apk包的清单文件
     String packname = packInfo.packageName;
     Drawable icon = packInfo.applicationInfo.loadIcon(pm);
     String name = packInfo.applicationInfo.loadLabel(pm).toString();
     String sourceDir = packInfo.applicationInfo.sourceDir;
     int flags = packInfo.applicationInfo.flags; // 应用程序信息的标记 相当于用户提交的答卷
     if ((flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
       // 用户程序
       appInfo.setUserApp(true);
     } else {
       // 系统程序
       appInfo.setUserApp(false);
     }
     appInfo.setPackname(packname);
     appInfo.setIcon(icon);
     appInfo.setName(name);
     appInfo.sourceDir = sourceDir;
     appInfos.add(appInfo);
   }
   return appInfos;
 }
    @Override
    protected List<AppInfo> doInBackground(Void... v) {
      final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
      mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

      final PackageManager pm = getPackageManager();
      final List<ResolveInfo> apps = pm.queryIntentActivities(mainIntent, 0);
      final List<AppInfo> appList = new ArrayList<AppInfo>(apps.size());
      for (ResolveInfo info : apps) {
        final String packageName = info.activityInfo.packageName;
        if (packageName == null) {
          continue;
        }
        final String activityFqcn = info.activityInfo.name;
        final CharSequence label = info.loadLabel(pm);
        final Drawable icon = info.activityInfo.loadIcon(pm);

        final AppInfo appInfo = new AppInfo(label.toString(), icon, activityFqcn, packageName);
        appList.add(appInfo);
      }
      Collections.sort(
          appList,
          new Comparator<AppInfo>() {
            @Override
            public int compare(AppInfo app1, AppInfo app2) {
              return app1.getLabel().compareTo(app2.getLabel());
            }
          });

      return appList;
    }
 private Drawable getSubtypeIcon(InputMethodInfo imi, InputMethodSubtype subtype) {
   if (imi != null) {
     if (DEBUG) {
       Log.d(TAG, "Update icons of IME: " + imi.getPackageName());
       if (subtype != null) {
         Log.d(TAG, "subtype =" + subtype.getLocale() + "," + subtype.getMode());
       }
     }
     if (subtype != null) {
       return mPackageManager.getDrawable(
           imi.getPackageName(), subtype.getIconResId(), imi.getServiceInfo().applicationInfo);
     } else if (imi.getSubtypeCount() > 0) {
       return mPackageManager.getDrawable(
           imi.getPackageName(),
           imi.getSubtypeAt(0).getIconResId(),
           imi.getServiceInfo().applicationInfo);
     } else {
       try {
         return mPackageManager
             .getApplicationInfo(imi.getPackageName(), 0)
             .loadIcon(mPackageManager);
       } catch (PackageManager.NameNotFoundException e) {
         Log.w(TAG, "IME can't be found: " + imi.getPackageName());
       }
     }
   }
   return null;
 }
 /**
  * returns list of all packages installed
  *
  * @return List<String> of all installed packages
  */
 public List<String> getAllPackages() {
   settingsDB dataSrc = new settingsDB(context);
   dataSrc.open();
   showadv = Boolean.parseBoolean(dataSrc.getSetting("showadv"));
   boolean tmp = false;
   List<String> out = new ArrayList<String>();
   final PackageManager pm = context.getPackageManager();
   List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
   allNames.clear();
   allEnabled.clear();
   for (ApplicationInfo packageInfo : packages) {
     for (int i = 0; i < MainActivity.CBAllBlackList.length; i++) {
       if (MainActivity.CBAllBlackList[i].contains(packageInfo.packageName)) {
         tmp = true;
         break;
       }
     }
     if (!tmp || showadv) {
       out.add(packageInfo.packageName);
       allNames.add(pm.getApplicationLabel(packageInfo).toString());
       allEnabled.add(packageInfo.enabled);
     }
     allAdv.add(tmp);
     tmp = false;
   }
   dataSrc.close();
   return out;
 }
 private void openInMaps() {
   // get preferences
   SharedPreferences sharedPrefs =
       PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
   // build location from preferences
   Uri location = Uri.parse("geo:0,0?q=" + sharedPrefs.getString("location", "94043"));
   // build intent
   Intent intent = new Intent(Intent.ACTION_VIEW, location);
   // make sure theres an app available to respond by checking list of apps that can handle it is >
   // 0
   PackageManager packageManager = getActivity().getPackageManager();
   List activities =
       packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
   boolean isIntentSafe = activities.size() > 0;
   // start the intent only if its safe
   if (isIntentSafe) {
     startActivity(intent);
   } else {
     Toast.makeText(
             getActivity().getApplicationContext(),
             "Not apps to launch activity",
             Toast.LENGTH_LONG)
         .show();
   }
 }