Java Code Examples for android.app.Activity#getPackageManager()

The following examples show how to use android.app.Activity#getPackageManager() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static void onAbout(final Activity activity) {
    String versionName = "";
    try {
        PackageManager packageManager = activity.getPackageManager();
        String packageName = activity.getPackageName();
        versionName = packageManager.getPackageInfo(packageName, 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        versionName = "unknown";
    }
    new AlertDialog.Builder(activity)
            .setTitle(R.string.about_title)
            .setMessage(activity.getString(R.string.about_text, versionName))
            .setPositiveButton(R.string.alert_ok_button, null)
            .setCancelable(false)
            .show();
}
 
Example 2
Source Project: AgentWebX5   File: DefaultWebClient.java    License: Apache License 2.0 6 votes vote down vote up
private boolean openOtherPage(String intentUrl) {
	try {
		Intent intent;
		Activity mActivity = null;
		if ((mActivity = mWeakReference.get()) == null)
			return true;
		PackageManager packageManager = mActivity.getPackageManager();
		intent = new Intent().parseUri(intentUrl, Intent.URI_INTENT_SCHEME);
		ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
		LogUtils.i(TAG, "resolveInfo:" + info + "   package:" + intent.getPackage());
		if (info != null) {  //跳到该应用
			mActivity.startActivity(intent);
			return true;
		}
	} catch (Throwable ignore) {
		if (LogUtils.isDebug()) {
			ignore.printStackTrace();
		}
	}

	return false;
}
 
Example 3
Source Project: AgentWebX5   File: DefaultWebClient.java    License: Apache License 2.0 6 votes vote down vote up
private void handleIntentUrl(String intentUrl) {
	try {

		Intent intent = null;
		if (TextUtils.isEmpty(intentUrl) || !intentUrl.startsWith(INTENT_SCHEME))
			return;

		Activity mActivity = null;
		if ((mActivity = mWeakReference.get()) == null)
			return;
		PackageManager packageManager = mActivity.getPackageManager();
		intent = new Intent().parseUri(intentUrl, Intent.URI_INTENT_SCHEME);
		ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
		LogUtils.i("Info", "resolveInfo:" + info + "   package:" + intent.getPackage());
		if (info != null) {  //跳到该应用
			mActivity.startActivity(intent);
			return;
		}
	} catch (Exception e) {
		e.printStackTrace();
	}


}
 
Example 4
/**
 * 获取 Activity 的 title
 *
 * @param activity Activity
 * @return Activity 的 title
 */
private static String getActivityTitle(Activity activity) {
    if (activity != null) {
        try {
            String activityTitle = null;

            if (Build.VERSION.SDK_INT >= 11) {
                String toolbarTitle = getToolbarTitle(activity);
                if (!TextUtils.isEmpty(toolbarTitle)) {
                    activityTitle = toolbarTitle;
                }
            }

            if (!TextUtils.isEmpty(activityTitle)) {
                activityTitle = activity.getTitle().toString();
            }

            if (TextUtils.isEmpty(activityTitle)) {
                PackageManager packageManager = activity.getPackageManager();
                if (packageManager != null) {
                    ActivityInfo activityInfo = packageManager.getActivityInfo(activity.getComponentName(), 0);
                    if (!TextUtils.isEmpty(activityInfo.loadLabel(packageManager))) {
                        activityTitle = activityInfo.loadLabel(packageManager).toString();
                    }
                }
            }

            return activityTitle;
        } catch (Throwable ignore) {
            ExceptionUtil.exceptionThrow(ignore);
            return null;
        }
    }
    return null;
}
 
Example 5
@Nullable
private static String getTitle(@NonNull Activity activity, @NonNull String packageName) {
    PackageManager pm = activity.getPackageManager();
    try {
        ApplicationInfo info = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
        CharSequence title = pm.getApplicationLabel(info);
        if (title != null) {
            return title.toString();
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 6
Source Project: iBeebo   File: Utility.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static boolean isGooglePlaySafe(Activity activity) {
    Uri uri = Uri.parse("http://play.google.com/store/apps/details?id=com.google.android.gms");
    Intent mapCall = new Intent(Intent.ACTION_VIEW, uri);
    mapCall.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
    mapCall.setPackage("com.android.vending");
    PackageManager packageManager = activity.getPackageManager();
    List<ResolveInfo> activities = packageManager.queryIntentActivities(mapCall, 0);
    return activities.size() > 0;
}
 
Example 7
Source Project: JianDan_OkHttp   File: AppInfoUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String getVersionName(Activity activity) {
    // 获取packagemanager的实例
    PackageManager packageManager = activity.getPackageManager();
    // getPackageName()是你当前类的包名,0代表是获取版本信息
    PackageInfo packInfo = null;
    try {
        packInfo = packageManager.getPackageInfo(activity.getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return "0";
    }
}
 
Example 8
Source Project: iBeebo   File: Utility.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static boolean isGooglePlaySafe(Activity activity) {
    Uri uri = Uri.parse("http://play.google.com/store/apps/details?id=com.google.android.gms");
    Intent mapCall = new Intent(Intent.ACTION_VIEW, uri);
    mapCall.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
    mapCall.setPackage("com.android.vending");
    PackageManager packageManager = activity.getPackageManager();
    List<ResolveInfo> activities = packageManager.queryIntentActivities(mapCall, 0);
    return activities.size() > 0;
}
 
Example 9
/**
 * Loads an icon from the icon pack based on the received package name.
 *
 * @param activity       where LauncherApps service can be retrieved.
 * @param appPackageName Package name of the app whose icon is to be loaded.
 *
 * @return Drawable Will return null if there is no icon associated with the package name,
 * otherwise an associated icon from the icon pack will be returned.
 */
private static Drawable getIconDrawable(Activity activity, String appPackageName, long user) {
    PackageManager packageManager = activity.getPackageManager();
    String componentName = "ComponentInfo{" + appPackageName + "}";
    Resources iconRes = null;
    Drawable defaultIcon = null;

    try {
        if (Utils.atLeastLollipop()) {
            LauncherApps launcher = (LauncherApps) activity.getSystemService(
                    Context.LAUNCHER_APPS_SERVICE);
            UserManager userManager = (UserManager) activity.getSystemService(
                    Context.USER_SERVICE);

            if (userManager != null && launcher != null) {
                defaultIcon = launcher.getActivityList(AppUtils.getPackageName(appPackageName),
                        userManager.getUserForSerialNumber(user))
                                      .get(0).getBadgedIcon(0);
            }
        } else {
            defaultIcon = packageManager.getActivityIcon(
                    ComponentName.unflattenFromString(appPackageName));
        }

        if (!"default".equals(iconPackageName)) {
            iconRes = packageManager.getResourcesForApplication(iconPackageName);
        } else {
            return defaultIcon;
        }
    } catch (PackageManager.NameNotFoundException e) {
        Utils.sendLog(Utils.LogLevel.ERROR, e.toString());
    }

    String drawable = mPackagesDrawables.get(componentName);
    if (drawable != null && iconRes != null) {
        return loadDrawable(iconRes, drawable, iconPackageName);
    } else {
        return defaultIcon;
    }
}
 
Example 10
Source Project: TGPassportAndroidSDK   File: TelegramPassport.java    License: MIT License 5 votes vote down vote up
/**
 * Show an app installation alert, in case you need to do that yourself.
 * @param activity calling Activity
 */
public static void showAppInstallAlert(final Activity activity){
	String appName=null;
	try{
		PackageManager pm=activity.getPackageManager();
		appName=pm.getApplicationLabel(pm.getApplicationInfo(activity.getPackageName(), 0)).toString().replace("<", "&lt;");
	}catch(PackageManager.NameNotFoundException ignore){}
	ImageView banner=new ImageView(activity);
	banner.setImageResource(R.drawable.telegram_logo_large);
	banner.setBackgroundColor(0xFF4fa9e6);
	float dp=activity.getResources().getDisplayMetrics().density;
	int pad=Math.round(34*dp);
	banner.setPadding(0, pad, 0, pad);
	LinearLayout content=new LinearLayout(activity);
	content.setOrientation(LinearLayout.VERTICAL);
	content.addView(banner);
	TextView alertText=new TextView(activity);
	alertText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
	alertText.setTextColor(0xFF000000);
	alertText.setText(Html.fromHtml(activity.getString(R.string.PassportSDK_DownloadTelegram, appName).replaceAll("\\*\\*([^*]+)\\*\\*", "<b>$1</b>")));
	alertText.setPadding(Math.round(24*dp), Math.round(24*dp), Math.round(24*dp), Build.VERSION.SDK_INT<Build.VERSION_CODES.LOLLIPOP ? Math.round(24*dp) : Math.round(2*dp));
	content.addView(alertText);
	AlertDialog alert=new AlertDialog.Builder(activity, /*Build.VERSION.SDK_INT<Build.VERSION_CODES.LOLLIPOP ? AlertDialog.THEME_HOLO_LIGHT :*/ R.style.Theme_Telegram_Alert)
			.setView(content)
			.setPositiveButton(R.string.PassportSDK_OpenGooglePlay, new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which){
					activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=org.telegram.messenger")));
				}
			})
			.setNegativeButton(R.string.PassportSDK_Cancel, null)
			.show();
	if(Build.VERSION.SDK_INT<Build.VERSION_CODES.LOLLIPOP){
		int titleDividerId=activity.getResources().getIdentifier("titleDivider", "id", "android");
		View titleDivider=alert.findViewById(titleDividerId);
		if(titleDivider!=null){
			titleDivider.setVisibility(View.GONE);
		}
	}
}
 
Example 11
private void updateUi(Activity activity) {
    PackageManager packageManager = activity.getPackageManager();
    try {
        int packageFlags;
        if (Build.VERSION.SDK_INT < 24) {
            //noinspection deprecation
            packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
        } else {
            packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
        }
        ApplicationInfo info = packageManager.getApplicationInfo(
                Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA,
                packageFlags);
        DevicePolicyManager devicePolicyManager =
                (DevicePolicyManager) activity.getSystemService(Activity.DEVICE_POLICY_SERVICE);
        if ((info.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
            if (!devicePolicyManager.isApplicationHidden(
                    EnforcerDeviceAdminReceiver.getComponentName(activity),
                    Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA)) {
                // The app is ready to enforce restrictions
                // This is unlikely to happen in this sample as unhideApp() handles it.
                mListener.onStatusUpdated();
            } else {
                // The app is installed but hidden in this profile
                mTextStatus.setText(R.string.status_not_activated);
                mButtonUnhide.setVisibility(View.VISIBLE);
            }
        } else {
            // Need to reinstall the sample app
            mTextStatus.setText(R.string.status_need_reinstall);
            mButtonUnhide.setVisibility(View.GONE);
        }
    } catch (PackageManager.NameNotFoundException e) {
        // Need to reinstall the sample app
        mTextStatus.setText(R.string.status_need_reinstall);
        mButtonUnhide.setVisibility(View.GONE);
    }
}
 
Example 12
/** Launch an email intent if the device is capable.
 *
 * @param activity The parent activity (for context)
 * @param addr The address to email (not the full URI)
 * @param text The email body
 */
public static void launchEmailIntent(final Activity activity, String addr, String text) {
    Log.i(LOG_TAG,"Launch email intent from "+activity.getLocalClassName());
    // create email intent
    Intent emailIntent = new Intent(Intent.ACTION_SEND);
    emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {addr});
    emailIntent.setType("text/plain");
    // make sure there is an activity which can handle the intent.
    PackageManager emailpackageManager = activity.getPackageManager();
    List<ResolveInfo> emailresolveInfos = emailpackageManager.queryIntentActivities(emailIntent, 0);
    if(emailresolveInfos.size() > 0) {
        activity.startActivity(emailIntent);
    }
}
 
Example 13
Source Project: JianDanRxJava   File: AppInfoUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String getVersionName(Activity activity) {
    // 获取packagemanager的实例
    PackageManager packageManager = activity.getPackageManager();
    // getPackageName()是你当前类的包名,0代表是获取版本信息
    PackageInfo packInfo = null;
    try {
        packInfo = packageManager.getPackageInfo(activity.getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return "0";
    }
}
 
Example 14
/**
 * Checks if the application is available in this profile.
 *
 * @param packageName The package name
 * @return True if the application is available in this profile.
 */
private boolean isApplicationEnabled(String packageName) {
    Activity activity = getActivity();
    PackageManager packageManager = activity.getPackageManager();
    try {
        int packageFlags;
        if(Build.VERSION.SDK_INT < 24){
            //noinspection deprecation
            packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
        }else{
            packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
        }
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(
                packageName, packageFlags);
        // Return false if the app is not installed in this profile
        if (0 == (applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED)) {
            return false;
        }
        // Check if the app is not hidden in this profile
        DevicePolicyManager devicePolicyManager =
                (DevicePolicyManager) activity.getSystemService(Activity.DEVICE_POLICY_SERVICE);
        return !devicePolicyManager.isApplicationHidden(
                BasicDeviceAdminReceiver.getComponentName(activity), packageName);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}
 
Example 15
/** Checks if the intent could be performed by a system. */
private static boolean systemCanHandleIntent(Activity activity, Intent intent) {
  if (activity == null) {
    return false;
  }

  PackageManager manager = activity.getPackageManager();
  List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
  return infos != null && !infos.isEmpty();
}
 
Example 16
Source Project: RxZhihuPager   File: AppInfoUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取版本名
 *
 * @param activity
 * @return
 */
public static String getVersionName(Activity activity) {
    PackageManager packageManager = activity.getPackageManager();
    PackageInfo packInfo;
    try {
        packInfo = packageManager.getPackageInfo(activity.getPackageName(), 0);
        return packInfo.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return "1.0";
    }
}
 
Example 17
Source Project: android-utils   File: MediaUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Creates an intent to take a video from camera or gallery or any other application that can
 * handle the intent.
 *
 * @param ctx
 * @param savingUri
 * @param durationInSeconds
 * @return
 */
public static Intent createTakeVideoIntent(Activity ctx, Uri savingUri, int durationInSeconds) {

    if (savingUri == null) {
        throw new NullPointerException("Uri cannot be null");
    }

    final List<Intent> cameraIntents = new ArrayList<Intent>();
    final Intent captureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    final PackageManager packageManager = ctx.getPackageManager();
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for (ResolveInfo res : listCam) {
        final String packageName = res.activityInfo.packageName;
        final Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, savingUri);
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, durationInSeconds);
        cameraIntents.add(intent);
    }

    // Filesystem.
    final Intent galleryIntent = new Intent();
    galleryIntent.setType("video/*");
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

    // Chooser of filesystem options.
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

    // Add the camera options.
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));

    return chooserIntent;
}
 
Example 18
Source Project: android-utils   File: Utils.java    License: MIT License 5 votes vote down vote up
/**
 * @param ctx
 * @param savingUri
 * @param durationInSeconds
 * @return
 * @deprecated Use {@link MediaUtils#createTakeVideoIntent(Activity, Uri, int)}
 * Creates an intent to take a video from camera or gallery or any other application that can
 * handle the intent.
 */
public static Intent createTakeVideoIntent(Activity ctx, Uri savingUri, int durationInSeconds) {

    if (savingUri == null) {
        throw new NullPointerException("Uri cannot be null");
    }

    final List<Intent> cameraIntents = new ArrayList<Intent>();
    final Intent captureIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    final PackageManager packageManager = ctx.getPackageManager();
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for (ResolveInfo res : listCam) {
        final String packageName = res.activityInfo.packageName;
        final Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, savingUri);
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, durationInSeconds);
        cameraIntents.add(intent);
    }

    // Filesystem.
    final Intent galleryIntent = new Intent();
    galleryIntent.setType("video/*");
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

    // Chooser of filesystem options.
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

    // Add the camera options.
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));

    return chooserIntent;
}
 
Example 19
/**
 * @param intent
 * @return
 */
protected boolean isIntentAvailable(Activity activity, Intent intent) {
    PackageManager packageManager = activity.getPackageManager();
    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}
 
Example 20
Source Project: onedrive-picker-android   File: Client.java    License: MIT License 2 votes vote down vote up
/**
 * Determines if the OneDrive application is installed and able to process
 * the specified {@link Intent}.
 * 
 * @param activity The activity that would start the picker experience
 * @param intent The intent to check availability
 * @return <b>true</b> if the OneDrive application can start and execute the
 *         file picking flow. <b>false</b> if the OneDrive application does
 *         not support this call, or if the application is not installed.
 */
public static boolean isAvailable(final Activity activity, final Intent intent) {
	final PackageManager pm = activity.getPackageManager();
    return pm.queryIntentActivities(intent, 0).size() != 0;
}