Example usage for android.content.pm PackageManager getApplicationInfo

List of usage examples for android.content.pm PackageManager getApplicationInfo

Introduction

In this page you can find the example usage for android.content.pm PackageManager getApplicationInfo.

Prototype

public abstract ApplicationInfo getApplicationInfo(String packageName, @ApplicationInfoFlags int flags)
        throws NameNotFoundException;

Source Link

Document

Retrieve all of the information we know about a particular package/application.

Usage

From source file:fr.inria.ucn.collectors.RunningAppsCollector.java

@SuppressLint("NewApi")
@Override/*from   w w  w  .  j  a  va  2 s .com*/
public void run(Context c, long ts) {
    try {
        ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager pm = c.getPackageManager();

        JSONObject data = new JSONObject();

        // running tasks
        JSONArray runTaskArray = new JSONArray();
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(50);
        boolean first = true;
        for (ActivityManager.RunningTaskInfo info : taskInfo) {
            JSONObject jinfo = new JSONObject();
            jinfo.put("task_id", info.id);
            jinfo.put("task_num_activities", info.numActivities);
            jinfo.put("task_num_running", info.numRunning);

            // is this the foreground process ?
            jinfo.put("task_foreground", first);
            if (first) {
                first = false;
            }

            if (info.topActivity != null) {
                jinfo.put("task_top_class_name", info.topActivity.getClassName());
                jinfo.put("task_top_package_name", info.topActivity.getPackageName());
                try {
                    // map package name to app label
                    CharSequence appLabel = pm.getApplicationLabel(pm.getApplicationInfo(
                            info.topActivity.getPackageName(), PackageManager.GET_META_DATA));
                    jinfo.put("task_app_label", appLabel.toString());
                } catch (NameNotFoundException e) {
                }
            }

            runTaskArray.put(jinfo);
        }
        data.put("runningTasks", runTaskArray);

        // processes
        JSONArray runProcArray = new JSONArray();
        for (ActivityManager.RunningAppProcessInfo pinfo : am.getRunningAppProcesses()) {
            JSONObject jinfo = new JSONObject();
            jinfo.put("proc_uid", pinfo.uid);
            jinfo.put("proc_name", pinfo.processName);
            jinfo.put("proc_packages", Helpers.getPackagesForUid(c, pinfo.uid));
            runProcArray.put(jinfo);
        }
        data.put("runningAppProcesses", runProcArray);

        // done
        Helpers.sendResultObj(c, "running_apps", ts, data);

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json obj", jex);
    }
}

From source file:com.apptentive.android.sdk.Apptentive.java

private static void init(Activity activity) {

    ////from w w w  .  j  a  v  a  2s.  c  o m
    // First, initialize data relies on synchronous reads from local resources.
    //

    final Context appContext = activity.getApplicationContext();

    if (!GlobalInfo.initialized) {
        SharedPreferences prefs = appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);

        // First, Get the api key, and figure out if app is debuggable.
        GlobalInfo.isAppDebuggable = false;
        String apiKey = null;
        boolean apptentiveDebug = false;
        String logLevelOverride = null;
        try {
            ApplicationInfo ai = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(),
                    PackageManager.GET_META_DATA);
            Bundle metaData = ai.metaData;
            if (metaData != null) {
                apiKey = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_API_KEY);
                logLevelOverride = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_LOG_LEVEL);
                apptentiveDebug = metaData.getBoolean(Constants.MANIFEST_KEY_APPTENTIVE_DEBUG);
                ApptentiveClient.useStagingServer = metaData
                        .getBoolean(Constants.MANIFEST_KEY_USE_STAGING_SERVER);
            }
            if (apptentiveDebug) {
                Log.i("Apptentive debug logging set to VERBOSE.");
                ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
            } else if (logLevelOverride != null) {
                Log.i("Overriding log level: %s", logLevelOverride);
                ApptentiveInternal.setMinimumLogLevel(Log.Level.parse(logLevelOverride));
            } else {
                GlobalInfo.isAppDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
                if (GlobalInfo.isAppDebuggable) {
                    ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
                }
            }
        } catch (Exception e) {
            Log.e("Unexpected error while reading application info.", e);
        }

        Log.i("Debug mode enabled? %b", GlobalInfo.isAppDebuggable);

        // If we are in debug mode, but no api key is found, throw an exception. Otherwise, just assert log. We don't want to crash a production app.
        String errorString = "No Apptentive api key specified. Please make sure you have specified your api key in your AndroidManifest.xml";
        if ((Util.isEmpty(apiKey))) {
            if (GlobalInfo.isAppDebuggable) {
                AlertDialog alertDialog = new AlertDialog.Builder(activity).setTitle("Error")
                        .setMessage(errorString).setPositiveButton("OK", null).create();
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            }
            Log.e(errorString);
        }
        GlobalInfo.apiKey = apiKey;

        Log.i("API Key: %s", GlobalInfo.apiKey);

        // Grab app info we need to access later on.
        GlobalInfo.appPackage = appContext.getPackageName();
        GlobalInfo.androidId = Settings.Secure.getString(appContext.getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);

        // Check the host app version, and notify modules if it's changed.
        try {
            PackageManager packageManager = appContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(appContext.getPackageName(), 0);

            Integer currentVersionCode = packageInfo.versionCode;
            String currentVersionName = packageInfo.versionName;
            VersionHistoryStore.VersionHistoryEntry lastVersionEntrySeen = VersionHistoryStore
                    .getLastVersionSeen(appContext);
            if (lastVersionEntrySeen == null) {
                onVersionChanged(appContext, null, currentVersionCode, null, currentVersionName);
            } else {
                if (!currentVersionCode.equals(lastVersionEntrySeen.versionCode)
                        || !currentVersionName.equals(lastVersionEntrySeen.versionName)) {
                    onVersionChanged(appContext, lastVersionEntrySeen.versionCode, currentVersionCode,
                            lastVersionEntrySeen.versionName, currentVersionName);
                }
            }

            GlobalInfo.appDisplayName = packageManager
                    .getApplicationLabel(packageManager.getApplicationInfo(packageInfo.packageName, 0))
                    .toString();
        } catch (PackageManager.NameNotFoundException e) {
            // Nothing we can do then.
            GlobalInfo.appDisplayName = "this app";
        }

        // Grab the conversation token from shared preferences.
        if (prefs.contains(Constants.PREF_KEY_CONVERSATION_TOKEN)
                && prefs.contains(Constants.PREF_KEY_PERSON_ID)) {
            GlobalInfo.conversationToken = prefs.getString(Constants.PREF_KEY_CONVERSATION_TOKEN, null);
            GlobalInfo.personId = prefs.getString(Constants.PREF_KEY_PERSON_ID, null);
        }

        GlobalInfo.initialized = true;
        Log.v("Done initializing...");
    } else {
        Log.v("Already initialized...");
    }

    // Initialize the Conversation Token, or fetch if needed. Fetch config it the token is available.
    if (GlobalInfo.conversationToken == null || GlobalInfo.personId == null) {
        asyncFetchConversationToken(appContext.getApplicationContext());
    } else {
        asyncFetchAppConfiguration(appContext.getApplicationContext());
        InteractionManager.asyncFetchAndStoreInteractions(appContext.getApplicationContext());
    }

    // TODO: Do this on a dedicated thread if it takes too long. Some devices are slow to read device data.
    syncDevice(appContext);
    syncSdk(appContext);
    syncPerson(appContext);

    Log.d("Default Locale: %s", Locale.getDefault().toString());
    SharedPreferences prefs = appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
    Log.d("Conversation id: %s", prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, "null"));
}

From source file:info.guardianproject.pixelknot.PixelKnotActivity.java

@Override
public List<TrustedShareActivity> getTrustedShareActivities() {
    if (trusted_share_activities == null) {
        trusted_share_activities = new Vector<TrustedShareActivity>();

        Intent intent = new Intent(Intent.ACTION_SEND).setType("image/jpeg");

        PackageManager pm = getPackageManager();
        for (ResolveInfo ri : pm.queryIntentActivities(intent, 0)) {
            if (Arrays.asList(Image.TRUSTED_SHARE_ACTIVITIES)
                    .contains(Image.Activities.get(ri.activityInfo.packageName))) {
                try {
                    ApplicationInfo ai = pm.getApplicationInfo(ri.activityInfo.packageName, 0);
                    TrustedShareActivity tsa = new TrustedShareActivity(
                            Image.Activities.get(ri.activityInfo.packageName), ri.activityInfo.packageName);

                    tsa.setIcon(pm.getApplicationIcon(ai));
                    tsa.createView();/*w  w w .  j av a  2 s. c  o  m*/
                    tsa.setIntent();

                    trusted_share_activities.add(tsa);

                } catch (PackageManager.NameNotFoundException e) {
                    Log.e(Logger.UI, e.toString());
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

    return trusted_share_activities;
}

From source file:net.inbox.InboxMessage.java

/**
 * Looks for available and supported encryption packages.
 * OpenKeychain for GPG.//from   w  w  w.  j  a v  a2  s .c  om
 **/
private boolean crypto_package() {
    PackageManager pack_man = getPackageManager();
    try {
        pack_man.getPackageInfo(Pager.open_key_chain, PackageManager.GET_ACTIVITIES);
        return pack_man.getApplicationInfo(Pager.open_key_chain, 0).enabled;
    } catch (PackageManager.NameNotFoundException e) {
        Dialogs.toaster(false, getString(R.string.open_pgp_none_found), this);
        return false;
    }
}

From source file:com.android.leanlauncher.IconCache.java

public ArrayMap<String, String> getAvailableIconPacks() {
    ArrayMap<String, String> availableIconPacks = new ArrayMap<>();

    PackageManager pm = mContext.getPackageManager();

    // fetch installed icon packs for popular launchers
    Intent novaIntent = new Intent(Intent.ACTION_MAIN);
    novaIntent.addCategory(NOVA_LAUNCHER_THEME_NAME);
    List<ResolveInfo> novaTheme = pm.queryIntentActivities(novaIntent, PackageManager.GET_META_DATA);
    List<ResolveInfo> goTheme = pm.queryIntentActivities(new Intent(GO_LAUNCHER_THEME_NAME),
            PackageManager.GET_META_DATA);

    // merge those lists
    List<ResolveInfo> rinfo = new ArrayList<>(novaTheme);
    rinfo.addAll(goTheme);/* ww  w .  ja  v  a2  s .  c om*/

    for (ResolveInfo ri : rinfo) {
        String packageName = ri.activityInfo.packageName;

        try {
            ApplicationInfo ai = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            String label = pm.getApplicationLabel(ai).toString();
            Log.d(TAG, "Icon package = " + packageName + " title " + label);
            availableIconPacks.put(packageName, label);
        } catch (NameNotFoundException e) {
            Log.e(TAG, "Package not found = " + e);
        }
    }

    return availableIconPacks;
}

From source file:com.rui.ruitime.AppUsageStatisticsFragment.java

/**
 * Updates the {@link #mRecyclerView} with the list of {@link UsageStats} passed as an argument.
 *
 * @param usageStatsList A list of {@link UsageStats} from which update the
 *                       {@link #mRecyclerView}.
 *//*w w  w  .  ja  v  a  2s. c  om*/
//VisibleForTesting
void updateAppsList(List<UsageStats> usageStatsList, int modeOfSorting) {

    customUsageStatsList.clear();
    PackageManager packageManager = getActivity().getPackageManager();

    for (int i = 0; i < usageStatsList.size(); i++) {
        CustomAppUsageStats customUsageStats = new CustomAppUsageStats();
        ApplicationInfo appInfo = new ApplicationInfo();
        customUsageStats.usageStats = usageStatsList.get(i);
        try {
            Drawable appIcon = getActivity().getPackageManager()
                    .getApplicationIcon(customUsageStats.usageStats.getPackageName());
            customUsageStats.appIcon = appIcon;

        } catch (PackageManager.NameNotFoundException e) {
            Log.w(TAG, String.format("App Icon is not found for %s",
                    customUsageStats.usageStats.getPackageName()));
            customUsageStats.appIcon = getActivity().getDrawable(R.drawable.ic_default_app_launcher);
        }

        try {
            appInfo = packageManager.getApplicationInfo(customUsageStats.usageStats.getPackageName(), 0);

        } catch (PackageManager.NameNotFoundException e) {
            Log.w(TAG, String.format("App Name is not interpreted for %s",
                    customUsageStats.usageStats.getPackageName()));
        }
        customUsageStats.appName = (String) (appInfo != null ? packageManager.getApplicationLabel(appInfo)
                : "Unknown");

        int[] statsDuration = { 0, 0, 0 };
        long lastTimeUsed = customUsageStats.usageStats.getLastTimeUsed();

        DateFormat df = new SimpleDateFormat();
        customUsageStats.lastUsedTimestampString = df.format(new Date(lastTimeUsed));

        long totalDurationUsed = (long) (customUsageStats.usageStats.getTotalTimeInForeground() / 1000.0D);

        statsDuration[0] = (int) (totalDurationUsed / 3600);
        statsDuration[1] = (int) ((totalDurationUsed - statsDuration[0] * 3600) / 60);
        statsDuration[2] = (int) ((totalDurationUsed - statsDuration[0] * 3600 - statsDuration[1] * 60));

        customUsageStats.totalUsedDurationString = ((statsDuration[0] > 0) ? statsDuration[0] + "h " : "")
                + ((statsDuration[1] > 0) ? statsDuration[1] + "m " : "")
                + ((statsDuration[2] > 0) ? statsDuration[2] + "s " : "1s");
        customUsageStatsList.add(customUsageStats);

    }

    if (modeOfSorting == 0) {
        Collections.sort(customUsageStatsList, new TotalDurationUsedComparatorDesc());
    } else if (modeOfSorting == 1) {
        Collections.sort(customUsageStatsList, new AlphabeticalComparatorDesc());
    }
    mUsageListAdapter.setCustomUsageStatsList(customUsageStatsList);
    mUsageListAdapter.notifyDataSetChanged();
    mRecyclerView.scrollToPosition(0);
}

From source file:com.rp.podemu.SettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);

    sharedPref = this.getSharedPreferences("PODEMU_PREFS", Context.MODE_PRIVATE);

    //String[] controlledApp = new String[appsRunning.size()];
    //Drawable[] icons = new Drawable[appsRunning.size()];
    //pm.getApplicationInfo(r.baseActivity.getPackageName(), PackageManager.GET_META_DATA);
    //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    //startActivity(intent);

    Intent intent = new Intent(Intent.ACTION_MAIN, null);
    intent.addCategory(Intent.CATEGORY_APP_MUSIC);

    PackageManager pm = getPackageManager();
    String text = "";
    List<ResolveInfo> packages = pm.queryIntentActivities(intent, 0);
    //get a list of installed apps.
    //List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

    //using hashset so that there will be no duplicate packages,
    //if no duplicate packages then there will be no duplicate apps
    HashSet<String> packageNames = new HashSet<String>(0);
    appInfos = new ArrayList<ApplicationInfo>(0);

    //getting package names and adding them to the hashset
    for (ResolveInfo resolveInfo : packages) {
        packageNames.add(resolveInfo.activityInfo.packageName);
    }/*from  w w w.  j  a va  2s.com*/

    // used just for tests
    /*
    ApplicationInfo dummyApp = new ApplicationInfo();
    dummyApp.name="select application";
    dummyApp.processName="dummy";
    appInfos.add(dummyApp);
    */

    for (String packageName : PodEmuIntentFilter.getAppList()) {
        try {
            appInfos.add(pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA));
        } catch (PackageManager.NameNotFoundException e) {
            //Do Nothing
        }
    }
    //now we have unique packages in the hashset, so get their application infos
    //and add them to the arraylist
    for (String packageName : packageNames) {
        try {
            appInfos.add(pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA));

        } catch (PackageManager.NameNotFoundException e) {
            //Do Nothing
        }
    }

    text += "Apps count: " + appInfos.size() + "\n";
    for (ApplicationInfo appInfo : appInfos) {
        //if (packageInfo.)
        {
            appInfo.name = (String) appInfo.loadLabel(pm);
            text += appInfo.loadLabel(pm) + "\n";
            //text += packageInfo.
            //text += "\n";
        }
    }

    //TextView textView = (TextView) findViewById(R.id.ctrlAppTitle);
    //textView.setText(text);

    //LauncherApps launcherApps=new LauncherApps();
    //List<LauncherActivityInfo> activities=launcherApps.getActivityList(null, android.os.Process.myUserHandle());
    //List<LauncherActivityInfo> activities=LauncherApps().getActivityList(null, android.os.Process.myUserHandle());

    baudRateList.add(9600);
    baudRateList.add(14400);
    baudRateList.add(19200);
    baudRateList.add(28800);
    baudRateList.add(38400);
    baudRateList.add(56000);
    baudRateList.add(57600);
    baudRateList.add(115200);

    try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        String version = pInfo.versionName;
        TextView versionHint = (TextView) findViewById(R.id.versionHint);
        versionHint.setText(getResources().getString(R.string.version_hint) + version);
    } catch (PackageManager.NameNotFoundException e) {
        // do nothing
    }

}

From source file:com.google.android.gms.common.C0270e.java

public static int m3379a(Context context) {
    PackageManager packageManager = context.getPackageManager();
    if (!C0418g.f2234a) {
        try {/*from   w w w .  j a v a 2 s .  c o  m*/
            context.getResources().getString(R.common_google_play_services_unknown_issue);
        } catch (Throwable th) {
            Log.e("GooglePlayServicesUtil",
                    "The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.");
        }
    }
    if (!C0418g.f2234a) {
        C0270e.m3398c(context);
    }
    try {
        PackageInfo packageInfo = packageManager.getPackageInfo("com.google.android.gms", 64);
        C0399i a = C0399i.m3510a();
        if (!C0516u.m4168c(packageInfo.versionCode) && !C0516u.m4166a(context)) {
            try {
                if (a.m3512a(packageManager.getPackageInfo("com.android.vending", 64), C0373r.f2177a) == null) {
                    Log.w("GooglePlayServicesUtil", "Google Play Store signature invalid.");
                    return 9;
                }
                if (a.m3512a(packageInfo, a.m3512a(packageManager.getPackageInfo("com.android.vending", 64),
                        C0373r.f2177a)) == null) {
                    Log.w("GooglePlayServicesUtil", "Google Play services signature invalid.");
                    return 9;
                }
            } catch (NameNotFoundException e) {
                Log.w("GooglePlayServicesUtil", "Google Play Store is missing.");
                return 9;
            }
        } else if (a.m3512a(packageInfo, C0373r.f2177a) == null) {
            Log.w("GooglePlayServicesUtil", "Google Play services signature invalid.");
            return 9;
        }
        if (C0516u.m4165a(packageInfo.versionCode) < C0516u.m4165a(7095000)) {
            Log.w("GooglePlayServicesUtil",
                    "Google Play services out of date.  Requires 7095000 but found " + packageInfo.versionCode);
            return 2;
        }
        try {
            return !packageManager.getApplicationInfo("com.google.android.gms", 0).enabled ? 3 : 0;
        } catch (NameNotFoundException e2) {
            Log.wtf("GooglePlayServicesUtil", "Google Play services missing when getting application info.");
            e2.printStackTrace();
            return 1;
        }
    } catch (NameNotFoundException e3) {
        Log.w("GooglePlayServicesUtil", "Google Play services is missing.");
        return 1;
    }
}

From source file:com.google.android.gms.common.GooglePlayServicesUtil.java

public static int isGooglePlayServicesAvailable(Context context) {
    PackageManager packageManager = context.getPackageManager();
    try {//w ww.j  a  v  a 2s.  c  o m
        context.getResources().getString(C0192R.string.common_google_play_services_unknown_issue);
    } catch (Throwable th) {
        Log.e("GooglePlayServicesUtil",
                "The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.");
    }
    if (System.currentTimeMillis() < 1227312000288L) {
        return 12;
    }
    m118t(context);
    try {
        PackageInfo packageInfo = packageManager.getPackageInfo(GOOGLE_PLAY_SERVICES_PACKAGE, 64);
        if (!gk.m1034y(context)) {
            try {
                if (m107a(packageManager.getPackageInfo(GOOGLE_PLAY_STORE_PACKAGE, 64), Aj) == null) {
                    Log.w("GooglePlayServicesUtil", "Google Play Store signature invalid.");
                    return 9;
                }
                if (m107a(packageInfo,
                        m107a(packageManager.getPackageInfo(GOOGLE_PLAY_STORE_PACKAGE, 64), Aj)) == null) {
                    Log.w("GooglePlayServicesUtil", "Google Play services signature invalid.");
                    return 9;
                }
            } catch (NameNotFoundException e) {
                Log.w("GooglePlayServicesUtil", "Google Play Store is missing.");
                return 9;
            }
        } else if (m107a(packageInfo, Aj) == null) {
            Log.w("GooglePlayServicesUtil", "Google Play services signature invalid.");
            return 9;
        }
        if (packageInfo.versionCode < GOOGLE_PLAY_SERVICES_VERSION_CODE) {
            Log.w("GooglePlayServicesUtil",
                    "Google Play services out of date.  Requires 4452000 but found " + packageInfo.versionCode);
            return 2;
        }
        try {
            return !packageManager.getApplicationInfo(GOOGLE_PLAY_SERVICES_PACKAGE, 0).enabled ? 3 : 0;
        } catch (NameNotFoundException e2) {
            Log.wtf("GooglePlayServicesUtil", "Google Play services missing when getting application info.");
            e2.printStackTrace();
            return 1;
        }
    } catch (NameNotFoundException e3) {
        Log.w("GooglePlayServicesUtil", "Google Play services is missing.");
        return 1;
    }
}