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.noveogroup.android.facebook.FacebookShareDialogFragment.java

private static boolean isAppPresent(final Context context) {
    try {//w  w  w.j  a  v a 2s  .co  m
        final PackageManager manager = context.getPackageManager();
        if (manager != null) {
            manager.getApplicationInfo(PACKAGE_FACEBOOK, 0);
            return true;
        }
    } catch (PackageManager.NameNotFoundException ignore) {
    }
    return false;
}

From source file:com.scoreflex.ScoreflexGcmClient.java

protected static Notification buildNotification(String text, Context context, int iconResource,
        PendingIntent pendingIntent) {/*from w w  w.j  a va 2 s.  c o m*/
    final PackageManager pm = context.getApplicationContext().getPackageManager();
    ApplicationInfo ai;
    try {
        ai = pm.getApplicationInfo(context.getPackageName(), 0);
    } catch (final NameNotFoundException e) {
        ai = null;
    }
    final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setContentTitle(applicationName).setContentText(text).setSmallIcon(iconResource);

    mBuilder.setContentIntent(pendingIntent);
    Notification notification = mBuilder.build();
    notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
    notification.flags = Notification.FLAG_AUTO_CANCEL;
    return notification;
}

From source file:Main.java

/**
 * /*from   w  w w .j  a va2 s  . c  o  m*/
 * @param c
 * @param uid
 * @return
 * @throws JSONException
 */
public static JSONArray getPackagesForUid(Context c, int uid) throws JSONException {
    PackageManager pm = c.getPackageManager();
    JSONArray res = new JSONArray();
    String[] pkgs = pm.getPackagesForUid(uid);
    if (pkgs != null) {
        for (int i = 0; i < pkgs.length; i++) {
            try {
                CharSequence appLabel = pm
                        .getApplicationLabel(pm.getApplicationInfo(pkgs[i], PackageManager.GET_META_DATA));
                JSONObject pkg = new JSONObject();
                pkg.put("package", pkgs[i]);
                pkg.put("app_label", appLabel.toString());
                res.put(pkg);
            } catch (NameNotFoundException e) {
            } catch (Exception e) {
            }
        }
    }
    return res;
}

From source file:com.harshad.linconnectclient.NotificationUtilities.java

public static boolean sendData(Context c, Notification n, String packageName) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);

    ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // Check Wifi state, whether notifications are enabled globally, and
    // whether notifications are enabled for specific application
    if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) {
        String ip = prefs.getString("pref_ip", "0.0.0.0:9090");

        // Magically extract text from notification
        ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n);

        // Use PackageManager to get application name and icon
        final PackageManager pm = c.getPackageManager();
        ApplicationInfo ai;//from   ww w  . j  a  va2 s .co m
        try {
            ai = pm.getApplicationInfo(packageName, 0);
        } catch (final NameNotFoundException e) {
            ai = null;
        }

        String notificationBody = "";
        String notificationHeader = "";
        // Create header and body of notification
        if (notificationData.size() > 0) {
            notificationHeader = notificationData.get(0);
            if (notificationData.size() > 1) {
                notificationBody = notificationData.get(1);
            }
        } else {
            return false;
        }

        for (int i = 2; i < notificationData.size(); i++) {
            notificationBody += "\n" + notificationData.get(i);
        }

        // Append application name to body
        if (pm.getApplicationLabel(ai) != null) {
            if (notificationBody.isEmpty()) {
                notificationBody = "via " + pm.getApplicationLabel(ai);
            } else {
                notificationBody += " (via " + pm.getApplicationLabel(ai) + ")";
            }
        }

        // Setup HTTP request
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // If the notification contains an icon, use it
        if (n.largeIcon != null) {
            entity.addPart("notificon",
                    new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png"));
        }
        // Otherwise, use the application's icon
        else {
            entity.addPart("notificon",
                    new InputStreamBody(
                            ImageUtilities.bitmapToInputStream(
                                    ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))),
                            "drawable.png"));
        }

        HttpPost post = new HttpPost("http://" + ip + "/notif");
        post.setEntity(entity);

        try {
            post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
        } catch (UnsupportedEncodingException e) {
            post.addHeader("notifheader",
                    Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription",
                    Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        }

        // Send HTTP request
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        try {
            response = client.execute(post);
            String html = EntityUtils.toString(response.getEntity());
            if (html.contains("true")) {
                return true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return false;
}

From source file:enterprayz.megatools.Tools.java

private static Intent newFacebookIntent(PackageManager pm, String url) {
    Uri uri = Uri.parse(url);//ww  w . jav a 2s.  co m
    try {
        ApplicationInfo applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
        if (applicationInfo.enabled) {
            uri = Uri.parse("fb://facewebmodal/f?href=" + url);
        }
    } catch (PackageManager.NameNotFoundException ignored) {
    }
    return new Intent(Intent.ACTION_VIEW, uri);
}

From source file:io.teak.sdk.NotificationBuilder.java

public static Notification createNativeNotification(final Context context, Bundle bundle,
        TeakNotification teakNotificaton) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Rich text message
    Spanned richMessageText = Html.fromHtml(teakNotificaton.message);

    // Configure notification behavior
    builder.setPriority(NotificationCompat.PRIORITY_MAX);
    builder.setDefaults(NotificationCompat.DEFAULT_ALL);
    builder.setOnlyAlertOnce(true);/*from  ww w  .  j av a2 s . c  o  m*/
    builder.setAutoCancel(true);
    builder.setTicker(richMessageText);

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    Random rng = new Random();

    // Create intent to fire if/when notification is cleared
    Intent pushClearedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_CLEARED_INTENT_ACTION_SUFFIX);
    pushClearedIntent.putExtras(bundle);
    PendingIntent pushClearedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(),
            pushClearedIntent, PendingIntent.FLAG_ONE_SHOT);
    builder.setDeleteIntent(pushClearedPendingIntent);

    // Create intent to fire if/when notification is opened, attach bundle info
    Intent pushOpenedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_OPENED_INTENT_ACTION_SUFFIX);
    pushOpenedIntent.putExtras(bundle);
    PendingIntent pushOpenedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(), pushOpenedIntent,
            PendingIntent.FLAG_ONE_SHOT);
    builder.setContentIntent(pushOpenedPendingIntent);

    // Because we can't be certain that the R class will line up with what is at SDK build time
    // like in the case of Unity et. al.
    class IdHelper {
        public int id(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "id", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.id." + identifier);
            }
            return ret;
        }

        public int layout(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "layout", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.layout." + identifier);
            }
            return ret;
        }
    }
    IdHelper R = new IdHelper(); // Declaring local as 'R' ensures we don't accidentally use the other R

    // Configure notification small view
    RemoteViews smallView = new RemoteViews(context.getPackageName(),
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_notif_no_title_v21")
                    : R.layout("teak_notif_no_title"));

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        smallView.setImageViewResource(R.id("left_image"), ai.icon);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    // Set small view text
    smallView.setTextViewText(R.id("text"), richMessageText);

    // Check for Jellybean (API 16, 4.1)+ for expanded view
    RemoteViews bigView = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && teakNotificaton.longText != null
            && !teakNotificaton.longText.isEmpty()) {
        bigView = new RemoteViews(context.getPackageName(),
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_big_notif_image_text_v21")
                        : R.layout("teak_big_notif_image_text"));

        // Set big view text
        bigView.setTextViewText(R.id("text"), Html.fromHtml(teakNotificaton.longText));

        URI imageAssetA = null;
        try {
            imageAssetA = new URI(teakNotificaton.imageAssetA);
        } catch (Exception ignored) {
        }

        Bitmap topImageBitmap = null;
        if (imageAssetA != null) {
            try {
                URL aURL = new URL(imageAssetA.toString());
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                topImageBitmap = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap == null) {
            try {
                InputStream istr = context.getAssets().open("teak_notif_large_image_default.png");
                topImageBitmap = BitmapFactory.decodeStream(istr);
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap != null) {
            // Set large bitmap
            bigView.setImageViewBitmap(R.id("top_image"), topImageBitmap);
        } else {
            Log.e(LOG_TAG, "Unable to load image asset for Notification.");
            // Hide pulldown
            smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
        }
    } else {
        // Hide pulldown
        smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
    }

    // Voodoo from http://stackoverflow.com/questions/28169474/notification-background-in-android-lollipop-is-white-can-we-change-it
    int topId = Resources.getSystem().getIdentifier("status_bar_latest_event_content", "id", "android");
    int topBigLayout = Resources.getSystem().getIdentifier("notification_template_material_big_media_narrow",
            "layout", "android");
    int topSmallLayout = Resources.getSystem().getIdentifier("notification_template_material_media", "layout",
            "android");

    RemoteViews topBigView = null;
    if (bigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // This is invisible inner view - to have media_actions in hierarchy
        RemoteViews innerTopView = new RemoteViews("android", topBigLayout);
        bigView.addView(android.R.id.empty, innerTopView);

        // This should be on top - we need status_bar_latest_event_content as top layout
        topBigView = new RemoteViews("android", topBigLayout);
        topBigView.removeAllViews(topId);
        topBigView.addView(topId, bigView);
    } else if (bigView != null) {
        topBigView = bigView;
    }

    // This should be on top - we need status_bar_latest_event_content as top layout
    RemoteViews topSmallView;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        topSmallView = new RemoteViews("android", topSmallLayout);
        topSmallView.removeAllViews(topId);
        topSmallView.addView(topId, smallView);
    } else {
        topSmallView = smallView;
    }

    builder.setContent(topSmallView);

    Notification n = builder.build();
    if (topBigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // Use reflection to avoid compile-time issues, we check minimum API version above
        try {
            Field bigContentViewField = n.getClass().getField("bigContentView");
            bigContentViewField.set(n, topBigView);
        } catch (Exception ignored) {
        }
    }

    return n;
}

From source file:it.scoppelletti.mobilepower.app.AppUtils.java

/**
 * Restituisce il nome del pacchetto di un&rsquo;applicazione.
 * //w w  w.j  a  v a2 s .c  o  m
 * @param  ctx        Contesto.
 * @param  onlyIfDemo Indica se restituire il nome del pacchetto solo se
 *                    l&rsquo;applicazione &egrave; una versione di demo.
 * @return            Nome del pacchetto. Se il parametro {@code onlyIfDemo}
 *                    &egrave; impostato, pu&ograve; essere {@code null}.
 */
static String getFullPackageName(Context ctx, boolean onlyIfDemo) {
    String pkgName, value;
    Bundle data;
    ApplicationInfo applInfo;
    PackageManager pkgMgr;

    if (ctx == null) {
        throw new NullPointerException("Argument ctx is null.");
    }

    pkgName = ctx.getPackageName();
    pkgMgr = ctx.getPackageManager();

    try {
        applInfo = pkgMgr.getApplicationInfo(pkgName, PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException ex) {
        myLogger.error("Failed to get ApplicationInfo.", ex);
        applInfo = ctx.getApplicationInfo();
    }

    data = applInfo.metaData;
    value = (data != null) ? data.getString(AppUtils.METADATA_FULLPACKAGE) : null;
    if (!StringUtils.isBlank(value)) {
        pkgName = value;
    } else if (onlyIfDemo) {
        return null;
    }

    return pkgName;
}

From source file:com.adam.aslfms.util.Util.java

public static String getAppName(Context ctx, String pkgName) {
    try {/*from w ww. ja  va  2  s.  com*/
        PackageManager pm = ctx.getPackageManager();
        ApplicationInfo appInfo = pm.getApplicationInfo(pkgName, 0);
        String label = pm.getApplicationLabel(appInfo).toString();
        return label;
    } catch (NameNotFoundException e) {
        return "";
    }
}

From source file:de.madvertise.android.sdk.MadUtil.java

/**
 * Returns the madvertise token// w  w w .  j  a  v  a 2 s .c  o  m
 * 
 * @param context
 *            application context
 * @return madvertise_token from AndroidManifest.xml or null
 */
protected static String getToken(Context context) {
    String madvertiseToken = null;

    PackageManager packageManager = context.getPackageManager();
    try {
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(),
                PackageManager.GET_META_DATA);
        madvertiseToken = applicationInfo.metaData.getString("madvertise_site_token");
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (madvertiseToken == null) {
        if (PRINT_LOG)
            Log.d(MadUtil.LOG, "Could not fetch \"madvertise_site_token\" from AndroidManifest.xml");

    }

    return madvertiseToken;
}

From source file:com.example.dashclock.examplehost.ExampleHostActivity.java

private static String packagesNameListToAppNameString(Context context, List<String> pkgs) {
    StringBuilder sb = new StringBuilder();
    final PackageManager pm = context.getPackageManager();
    for (String pkg : pkgs) {
        sb.append("\n\n\t");
        try {/*from  w  w w  . j a v a 2s.c o  m*/
            ApplicationInfo pi = pm.getApplicationInfo(pkg, 0);
            CharSequence name = pi.loadLabel(pm);
            if (name == null) {
                sb.append(pkg);
            } else {
                sb.append(name);
            }
        } catch (PackageManager.NameNotFoundException ex) {
            sb.append(pkg);
        }
    }
    return sb.toString();
}