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:com.cmgapps.android.util.CMGAppRater.java

/**
 * Shows a default {@link AlertDialog}/*  w w w .j  a  v  a  2 s.  c o m*/
 *
 * @param context A Context to show the dialog
 */
public void show(final Context context) {
    if (context == null) {
        throw new IllegalArgumentException("context cannot be null");
    }

    if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
        throw new RuntimeException("CMGAppRater.show() must be called from main thread");
    }

    if (mDialog != null && mDialog.isShowing())
        return;

    final Editor editor = mPref.edit();
    final PackageManager pm = context.getPackageManager();

    String appName;
    try {
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        appName = (String) pm.getApplicationLabel(ai);
    } catch (NameNotFoundException e) {
        LOGE(TAG, "Application name can not be found");
        appName = "App";
    }

    mDialog = new AlertDialog.Builder(context).setTitle(R.string.dialog_cmgrate_title)
            .setMessage(context.getString(R.string.dialog_cmgrate_message, appName)).setCancelable(false)
            .setIcon(context.getApplicationInfo().icon)
            .setPositiveButton(context.getString(R.string.dialog_cmgrate_ok),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            editor.putBoolean(APP_RATED, true);
                            Intent intent = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("market://details?id=" + context.getPackageName()));
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(intent);

                            PreferenceEditorHelper.commit(editor);
                            dialog.dismiss();
                        }
                    })
            .setNegativeButton(R.string.dialog_cmgrate_no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    PreferenceEditorHelper.commit(editor.putBoolean(DECLINED_RATE, true));
                    dialog.dismiss();
                }
            }).setNeutralButton(R.string.dialog_cmgrate_later, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    PreferenceEditorHelper
                            .commit(editor.putLong(REMIND_LATER_DATE, System.currentTimeMillis()));
                    dialog.dismiss();
                }
            }).show();
    PreferenceEditorHelper.commit(editor);
}

From source file:com.android.talkback.labeling.LabelDialogManager.java

/**
 * Computes the common name for an application.
 *
 * @param packageName The package name of the application
 * @return The common name for the application
 *//* ww w  .ja va  2  s.  c  o  m*/
private CharSequence getApplicationName(String packageName) {
    final PackageManager pm = mContext.getPackageManager();
    ApplicationInfo appInfo;
    try {
        appInfo = pm.getApplicationInfo(packageName, 0);
    } catch (NameNotFoundException e) {
        appInfo = null;
    }

    final CharSequence appLabel;
    if (appInfo != null) {
        appLabel = mContext.getPackageManager().getApplicationLabel(appInfo);
    } else {
        appLabel = null;
    }

    return appLabel;
}

From source file:net.sf.fakenames.fddemo.PermissionActivity.java

private CharSequence toLabel(int uid, String[] packages) {
    final SpannableStringBuilder ssb = new SpannableStringBuilder();

    if (packages != null) {
        try {//from w  w  w  . j a v  a 2s  . c o  m
            final PackageManager pm = getPackageManager();

            if (packages.length == 1) {
                final ApplicationInfo soleInfo = pm.getApplicationInfo(packages[0], 0);
                if (soleInfo != null) {
                    final CharSequence label = soleInfo.loadLabel(pm);

                    if (!TextUtils.isEmpty(label)) {
                        ssb.append(label);
                        setBold(ssb, 0, ssb.length());
                        return ssb;
                    }
                }

                ssb.append(packages[0]);
                setBold(ssb, 0, ssb.length());
                return ssb;
            } else {
                Arrays.sort(packages);

                int named = 0;

                ssb.append("UID ").append(String.valueOf(uid)).append(" (");

                final ApplicationInfo firstInfo = pm.getApplicationInfo(packages[0], 0);

                if (firstInfo != null) {
                    final CharSequence label = firstInfo.loadLabel(pm);

                    if (!TextUtils.isEmpty(label)) {
                        ++named;

                        int old = ssb.length();
                        ssb.append(label);
                        setBold(ssb, old, ssb.length());
                    }
                }

                final int maxSummary = Math.min(packages.length, 3);
                int i;
                for (i = 1; i < maxSummary; ++i) {
                    final ApplicationInfo appInfo = pm.getApplicationInfo(packages[i], 0);

                    if (appInfo != null) {
                        final CharSequence label = appInfo.loadLabel(pm);

                        if (!TextUtils.isEmpty(label)) {
                            ++named;

                            ssb.append(", ");
                            int old = ssb.length();
                            ssb.append(label);
                            setBold(ssb, old, ssb.length());
                        }
                    }
                }

                if (named == 0) {
                    ssb.append(String.valueOf(packages.length)).append(" packages)");
                    setBold(ssb, 0, ssb.length());
                } else {
                    if (packages.length <= 4) {
                        ssb.append(")");
                    } else {
                        ssb.append(" and ");
                        ssb.append(String.valueOf(packages.length - named));
                        ssb.append(" others)");
                    }
                }

                return ssb;
            }
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    }

    ssb.append("UID ").append(String.valueOf(uid));
    setBold(ssb, 0, ssb.length());
    return ssb;
}

From source file:androidx.media.SessionToken2.java

/**
 * Constructor for the token. You can only create token for session service or library service
 * to use by {@link MediaController2} or {@link MediaBrowser2}.
 *
 * @param context The context./* w  w w.  ja va2  s  .  c  o  m*/
 * @param serviceComponent The component name of the media browser service.
 * @param uid uid of the app.
 * @hide
 */
@RestrictTo(LIBRARY_GROUP)
public SessionToken2(@NonNull Context context, @NonNull ComponentName serviceComponent, int uid) {
    if (serviceComponent == null) {
        throw new IllegalArgumentException("serviceComponent shouldn't be null");
    }
    mComponentName = serviceComponent;
    mPackageName = serviceComponent.getPackageName();
    mServiceName = serviceComponent.getClassName();
    // Calculate uid if it's not specified.
    final PackageManager manager = context.getPackageManager();
    if (uid < 0) {
        try {
            uid = manager.getApplicationInfo(mPackageName, 0).uid;
        } catch (PackageManager.NameNotFoundException e) {
            throw new IllegalArgumentException("Cannot find package " + mPackageName);
        }
    }
    mUid = uid;

    // Infer id and type from package name and service name
    String id = getSessionIdFromService(manager, MediaLibraryService2.SERVICE_INTERFACE, serviceComponent);
    if (id != null) {
        mId = id;
        mType = TYPE_LIBRARY_SERVICE;
    } else {
        // retry with session service
        mId = getSessionIdFromService(manager, MediaSessionService2.SERVICE_INTERFACE, serviceComponent);
        mType = TYPE_SESSION_SERVICE;
    }
    if (mId == null) {
        throw new IllegalArgumentException("service " + mServiceName + " doesn't implement"
                + " session service nor library service. Use service's full name.");
    }
    mSessionCompatToken = null;
}

From source file:com.intel.xdk.notification.Notification.java

public void showBusyIndicator() {
    if (spinner != null)
        return;//from ww  w . j  a  v  a 2  s  .c om

    //get a reference to the service
    String ns = Context.NOTIFICATION_SERVICE;
    final NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(ns);
    //create the notification instance
    int icon = activity.getResources().getIdentifier("spinner_n", "drawable", activity.getPackageName());//R.drawable.spinner_n;

    PackageManager packageManager = activity.getPackageManager();
    ApplicationInfo applicationInfo = null;
    try {
        applicationInfo = packageManager.getApplicationInfo(activity.getPackageName(), 0);
    } catch (final NameNotFoundException e) {
    }
    final String title = (String) ((applicationInfo != null)
            ? packageManager.getApplicationLabel(applicationInfo)
            : "???");

    CharSequence tickerText = title + " is busy...";//activity.getString(R.string.app_name) + " is busy...";
    long when = System.currentTimeMillis();
    final android.app.Notification notification = new android.app.Notification(icon, tickerText, when);
    //initialize latest event info
    Context context = activity.getApplicationContext();
    CharSequence contentTitle = title + " is busy...";//activity.getString(R.string.app_name) + " is busy...";
    CharSequence contentText = "...just a moment please.";
    Intent notificationIntent = new Intent(activity, activity.getClass());
    PendingIntent contentIntent = PendingIntent.getActivity(activity, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    //make notification non-cancellable
    notification.flags = notification.flags | android.app.Notification.FLAG_NO_CLEAR;
    //show in status bar
    mNotificationManager.notify(BUSY_INDICATOR, notification);
    //animate the icon
    spinner = new Thread("intel.xdk.notification:showBusyIndicator") {
        public void run() {
            //frame pointer
            int currentFrame = 0;
            //frame array
            //int[] frames = new int[]{R.drawable.spinner_ne, R.drawable.spinner_e, R.drawable.spinner_se, R.drawable.spinner_s, R.drawable.spinner_sw, R.drawable.spinner_w, R.drawable.spinner_nw, R.drawable.spinner_n};
            int[] frames = new int[] {
                    activity.getResources().getIdentifier("spinner_ne", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_e", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_se", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_s", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_sw", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_w", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_nw", "drawable", activity.getPackageName()),
                    activity.getResources().getIdentifier("spinner_n", "drawable", activity.getPackageName()) };
            Thread thisThread = Thread.currentThread();
            while (spinner == thisThread) {
                //loop over the frames, updating the icon every 200 ms
                currentFrame++;
                currentFrame %= frames.length;
                notification.icon = frames[currentFrame];
                mNotificationManager.notify(BUSY_INDICATOR, notification);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //when looping ends, remove notification from status bar
            mNotificationManager.cancel(BUSY_INDICATOR);
        }

        @Override
        protected void finalize() throws Throwable {
            //in case the process crashes, try to remove notification from status bar
            super.finalize();
            mNotificationManager.cancel(BUSY_INDICATOR);
        }
    };
    spinner.start();
}

From source file:me.piebridge.prevent.framework.SystemReceiver.java

private String getLabel(PackageManager pm, String packageName) {
    try {// w w w .j  a  v  a2s.c o m
        return pm.getApplicationInfo(packageName, 0).loadLabel(pm).toString();
    } catch (PackageManager.NameNotFoundException e) {
        PreventLog.d("cannot find application " + packageName, e);
        return packageName;
    }
}

From source file:com.oasisfeng.nevo.decorators.bundle.BundleDecorator.java

private String getSourceNames(final Set<String> pkgs) {
    final PackageManager pm = getPackageManager();
    final StringBuilder names = new StringBuilder();
    for (final String pkg : pkgs)
        try {//from w  w  w  . j a va 2s. c o  m
            final ApplicationInfo app_info = pm.getApplicationInfo(pkg,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            names.append(", ").append(app_info.loadLabel(pm));
        } catch (final NameNotFoundException ignored) {
        } // TODO: Packages from other user profiles?
    return names.substring(2);
}

From source file:org.apache.cordova.AndroidWebViewClient.java

/**
 * Notify the host application that an SSL error occurred while loading a resource.
 * The host application must call either handler.cancel() or handler.proceed().
 * Note that the decision may be retained for use in response to future SSL errors.
 * The default behavior is to cancel the load.
 *
 * @param view          The WebView that is initiating the callback.
 * @param handler       An SslErrorHandler object that will handle the user's response.
 * @param error         The SSL error object.
 *//*  w w  w  . j  a v  a  2  s .c  o  m*/
@TargetApi(8)
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

    final String packageName = this.cordova.getActivity().getPackageName();
    final PackageManager pm = this.cordova.getActivity().getPackageManager();

    ApplicationInfo appInfo;
    try {
        appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
        if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
            // debug = true
            handler.proceed();
            return;
        } else {
            // debug = false
            super.onReceivedSslError(view, handler, error);
        }
    } catch (NameNotFoundException e) {
        // When it doubt, lock it out!
        super.onReceivedSslError(view, handler, error);
    }
}

From source file:com.ayogo.cordova.notification.ScheduledNotificationManager.java

public void showNotification(ScheduledNotification scheduledNotification) {
    LOG.v(NotificationPlugin.TAG, "showNotification: " + scheduledNotification.toString());

    NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Build the notification options
    builder.setDefaults(Notification.DEFAULT_ALL).setTicker(scheduledNotification.body)
            .setPriority(Notification.PRIORITY_HIGH).setAutoCancel(true);

    // TODO: add sound support
    // if (scheduledNotification.sound != null) {
    //     builder.setSound(sound);
    // }/*www  .j  a v  a2 s  .  c  o  m*/

    if (scheduledNotification.body != null) {
        builder.setContentTitle(scheduledNotification.title);
        builder.setContentText(scheduledNotification.body);
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(scheduledNotification.body));
    } else {
        //Default the title to the app name
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);

            String appName = applicationInfo.loadLabel(pm).toString();

            builder.setContentTitle(appName);
            builder.setContentText(scheduledNotification.title);
            builder.setStyle(new NotificationCompat.BigTextStyle().bigText(scheduledNotification.title));
        } catch (NameNotFoundException e) {
            LOG.v(NotificationPlugin.TAG, "Failed to set title for notification!");
            return;
        }
    }

    if (scheduledNotification.badge != null) {
        LOG.v(NotificationPlugin.TAG, "showNotification: has a badge!");
        builder.setSmallIcon(getResIdForDrawable(scheduledNotification.badge));
    } else {
        LOG.v(NotificationPlugin.TAG, "showNotification: has no badge, use app icon!");
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            Resources resources = pm.getResourcesForApplication(applicationInfo);
            builder.setSmallIcon(applicationInfo.icon);
        } catch (NameNotFoundException e) {
            LOG.v(NotificationPlugin.TAG, "Failed to set badge for notification!");
            return;
        }
    }

    if (scheduledNotification.icon != null) {
        LOG.v(NotificationPlugin.TAG, "showNotification: has an icon!");
        builder.setLargeIcon(getIconFromUri(scheduledNotification.icon));
    } else {
        LOG.v(NotificationPlugin.TAG, "showNotification: has no icon, use app icon!");
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo applicationInfo = pm.getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            Resources resources = pm.getResourcesForApplication(applicationInfo);
            Bitmap appIconBitmap = BitmapFactory.decodeResource(resources, applicationInfo.icon);
            builder.setLargeIcon(appIconBitmap);
        } catch (NameNotFoundException e) {
            LOG.v(NotificationPlugin.TAG, "Failed to set icon for notification!");
            return;
        }
    }

    Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    launchIntent.setAction("notification");

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launchIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);

    Notification notification = builder.build();

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    LOG.v(NotificationPlugin.TAG, "notify!");
    notificationManager.notify(scheduledNotification.tag.hashCode(), notification);
}