Example usage for android.content.pm PackageManager GET_ACTIVITIES

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

Introduction

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

Prototype

int GET_ACTIVITIES

To view the source code for android.content.pm PackageManager GET_ACTIVITIES.

Click Source Link

Document

PackageInfo flag: return information about activities in the package in PackageInfo#activities .

Usage

From source file:szjy.advtech.BuildInfo.java

/**
 * init//from   www.  j a  v a  2 s  .  co m
 * @param buildConfigClassName null or specified BuildConfig class name
 * @param callbackContext
 */
private void init(String buildConfigClassName, CallbackContext callbackContext) {
    // Cached check
    if (null != mBuildInfoCache) {
        callbackContext.success(mBuildInfoCache);
        return;
    }

    // Load PackageInfo
    Activity activity = cordova.getActivity();
    String packageName = activity.getPackageName();
    String basePackageName = packageName;
    CharSequence displayName = "";

    PackageManager pm = activity.getPackageManager();

    try {
        PackageInfo pi = pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);

        if (null != pi.applicationInfo) {
            displayName = pi.applicationInfo.loadLabel(pm);
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    // Load BuildConfig class
    Class c = null;

    if (null == buildConfigClassName) {
        buildConfigClassName = packageName + ".BuildConfig";
    }

    try {
        c = Class.forName(buildConfigClassName);
    } catch (ClassNotFoundException e) {
    }

    if (null == c) {
        basePackageName = activity.getClass().getPackage().getName();
        buildConfigClassName = basePackageName + ".BuildConfig";

        try {
            c = Class.forName(buildConfigClassName);
        } catch (ClassNotFoundException e) {
            callbackContext.error("BuildConfig ClassNotFoundException: " + e.getMessage());
            return;
        }
    }

    // Create result
    mBuildInfoCache = new JSONObject();
    try {
        boolean debug = getClassFieldBoolean(c, "DEBUG", false);

        mBuildInfoCache.put("packageName", packageName);
        mBuildInfoCache.put("basePackageName", basePackageName);
        mBuildInfoCache.put("displayName", displayName);
        mBuildInfoCache.put("name", displayName); // same as displayName
        mBuildInfoCache.put("version", getClassFieldString(c, "VERSION_NAME", ""));
        mBuildInfoCache.put("versionCode", getClassFieldInt(c, "VERSION_CODE", 0));
        mBuildInfoCache.put("debug", debug);
        mBuildInfoCache.put("buildType", getClassFieldString(c, "BUILD_TYPE", ""));
        mBuildInfoCache.put("flavor", getClassFieldString(c, "FLAVOR", ""));

        if (debug) {
            Log.d(TAG, "packageName    : \"" + mBuildInfoCache.getString("packageName") + "\"");
            Log.d(TAG, "basePackageName: \"" + mBuildInfoCache.getString("basePackageName") + "\"");
            Log.d(TAG, "displayName    : \"" + mBuildInfoCache.getString("displayName") + "\"");
            Log.d(TAG, "name           : \"" + mBuildInfoCache.getString("name") + "\"");
            Log.d(TAG, "version        : \"" + mBuildInfoCache.getString("version") + "\"");
            Log.d(TAG, "versionCode    : " + mBuildInfoCache.getInt("versionCode"));
            Log.d(TAG, "debug          : " + (mBuildInfoCache.getBoolean("debug") ? "true" : "false"));
            Log.d(TAG, "buildType      : \"" + mBuildInfoCache.getString("buildType") + "\"");
            Log.d(TAG, "flavor         : \"" + mBuildInfoCache.getString("flavor") + "\"");
        }
    } catch (JSONException e) {
        e.printStackTrace();
        callbackContext.error("JSONException: " + e.getMessage());
        return;
    }

    callbackContext.success(mBuildInfoCache);
}

From source file:com.open.file.manager.IconLoader.java

/**
 * Get icon from the apk file//w  ww. j av  a2  s .  com
 * @param current apk to load icon from
 * @return icon bitmap
 */
private Bitmap getApkIcon(File current) {
    try {
        Bitmap icon = null;
        PackageInfo packageInfo = mycont.getPackageManager().getPackageArchiveInfo(current.getAbsolutePath(),
                PackageManager.GET_ACTIVITIES);
        if (packageInfo != null) {
            ApplicationInfo appInfo = packageInfo.applicationInfo;
            if (Build.VERSION.SDK_INT >= 8) {
                appInfo.sourceDir = current.getAbsolutePath();
                appInfo.publicSourceDir = current.getAbsolutePath();
            }
            Drawable apkico = appInfo.loadIcon(mycont.getPackageManager());
            final float scale = mycont.getResources().getDisplayMetrics().density;
            final int targetHeight = Math.round(Consts.ICON_SIZE * scale);
            final int targetWidth = Math.round(Consts.ICON_SIZE * scale);
            icon = ((BitmapDrawable) apkico).getBitmap();
            icon = Bitmap.createScaledBitmap(icon, targetWidth, targetHeight, false);
        }
        return icon;
    } catch (Exception exc) {
        return null;
    }
}

From source file:com.github.michalbednarski.intentslab.AppComponentsFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPackageName = ((AppInfoHost) getActivity()).getViewedPackageName();

    final PackageManager packageManager = getActivity().getPackageManager();

    ArrayList<Integer> presentSections = new ArrayList<Integer>();

    try {/*from  www .  java 2 s  .com*/
        final PackageInfo packageInfo = packageManager.getPackageInfo(mPackageName,
                PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS | PackageManager.GET_SERVICES
                        | PackageManager.GET_PROVIDERS | PackageManager.GET_PERMISSIONS);

        // Scan activities and group them as exported and not exported
        {
            ArrayList<ActivityInfo> exportedActivities = new ArrayList<ActivityInfo>();
            ArrayList<ActivityInfo> notExportedActivities = new ArrayList<ActivityInfo>();

            if (packageInfo.activities != null && packageInfo.activities.length != 0) {
                for (ActivityInfo activity : packageInfo.activities) {
                    (activity.exported ? exportedActivities : notExportedActivities).add(activity);
                }
            }

            if (exportedActivities.size() != 0) {
                mActivities = exportedActivities.toArray(new ComponentInfo[exportedActivities.size()]);
                presentSections.add(SECTION_ACTIVITIES);
            }
            if (notExportedActivities.size() != 0) {
                mActivitiesNotExported = notExportedActivities
                        .toArray(new ComponentInfo[notExportedActivities.size()]);
                presentSections.add(SECTION_ACTIVITIES_NOT_EXPORTED);
            }
        }

        // Check receivers, services and providers
        if (packageInfo.receivers != null) {
            mReceivers = packageInfo.receivers;
            presentSections.add(SECTION_RECEIVERS);
        }
        if (packageInfo.services != null) {
            mServices = packageInfo.services;
            presentSections.add(SECTION_SERVICES);
        }
        if (packageInfo.providers != null) {
            mProviders = packageInfo.providers;
            presentSections.add(SECTION_PROVIDERS);
        }

        // Scan defined permissions
        if (packageInfo.permissions != null) {
            mDefinedPermissions = new String[packageInfo.permissions.length];
            for (int i = 0; i < packageInfo.permissions.length; i++) {
                mDefinedPermissions[i] = packageInfo.permissions[i].name;
            }
            presentSections.add(SECTION_DEFINED_PERMISSIONS);
        }

        // Scan requested permissions (granted and denied)
        HashSet<String> testedPermissions = new HashSet<String>();
        if (packageInfo.requestedPermissions != null) {
            ArrayList<String> grantedPermissions = new ArrayList<String>();
            ArrayList<String> deniedPermissions = new ArrayList<String>();
            for (String permission : packageInfo.requestedPermissions) {
                if (packageManager.checkPermission(permission,
                        mPackageName) == PackageManager.PERMISSION_GRANTED) {
                    grantedPermissions.add(permission);
                } else {
                    deniedPermissions.add(permission);
                }
                testedPermissions.add(permission);
            }
            if (grantedPermissions.size() != 0) {
                mGrantedPermissions = grantedPermissions.toArray(new String[grantedPermissions.size()]);
                presentSections.add(SECTION_GRANTED_PERMISSIONS);
            }
            if (deniedPermissions.size() != 0) {
                mDeniedPermissions = deniedPermissions.toArray(new String[deniedPermissions.size()]);
                presentSections.add(SECTION_DENIED_PERMISSIONS);
            }

        }

        // Scan shared user packages for permissions (implicitly granted)
        {
            ArrayList<String> implicitlyGrantedPermissions = new ArrayList<String>();
            for (String sharedUidPackageName : packageManager
                    .getPackagesForUid(packageInfo.applicationInfo.uid)) {
                if (mPackageName.equals(sharedUidPackageName)) {
                    continue;
                }
                final PackageInfo sharedUidPackageInfo = packageManager.getPackageInfo(sharedUidPackageName,
                        PackageManager.GET_PERMISSIONS);
                if (sharedUidPackageInfo.requestedPermissions == null) {
                    continue;
                }
                for (String permission : sharedUidPackageInfo.requestedPermissions) {
                    if (!testedPermissions.contains(permission)) {
                        testedPermissions.add(permission);
                        if (packageManager.checkPermission(permission,
                                mPackageName) == PackageManager.PERMISSION_GRANTED) {
                            implicitlyGrantedPermissions.add(permission);
                        }
                    }
                }
            }
            if (implicitlyGrantedPermissions.size() != 0) {
                mImplicitlyGrantedPermissions = implicitlyGrantedPermissions
                        .toArray(new String[implicitlyGrantedPermissions.size()]);
                presentSections.add(SECTION_IMPLICITLY_GRANTED_PERMISSIONS);
            }
        }

        // Save present sections list as array
        mPresentSections = new int[presentSections.size()];
        for (int i = 0; i < presentSections.size(); i++) {
            mPresentSections[i] = presentSections.get(i);
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(e);
    }

}

From source file:tw.com.sti.store.api.android.AndroidApiService.java

private AndroidApiService(Context context, Configuration config) {
    this.config = config;
    this.apiUrl = new ApiUrl(config);
    if (Logger.DEBUG)
        L.d("new ApiService()");

    sdkVer = Build.VERSION.SDK;/*from   ww  w  . java2s.  c o  m*/
    sdkRel = Build.VERSION.RELEASE;
    try {
        PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_ACTIVITIES);
        storeId = pi.packageName;
        clientVer = "" + pi.versionCode;
    } catch (NameNotFoundException e) {
    }
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    deviceId = tm.getDeviceId() == null ? "0" : tm.getDeviceId();
    macAddress = NetworkUtils.getDeviceMacAddress(context);
    subscriberId = tm.getSubscriberId() == null ? "0" : tm.getSubscriberId();
    simSerialNumber = tm.getSimSerialNumber() == null ? "0" : tm.getSimSerialNumber();

    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    try {
        Class<Display> cls = Display.class;
        Method method = cls.getMethod("getRotation");
        Object retobj = method.invoke(display);
        int rotation = Integer.parseInt(retobj.toString());
        if (Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation) {
            wpx = "" + display.getWidth();
            hpx = "" + display.getHeight();
        } else {
            wpx = "" + display.getHeight();
            hpx = "" + display.getWidth();
        }
    } catch (Exception e) {
        if (display.getOrientation() == 1) {
            wpx = "" + display.getHeight();
            hpx = "" + display.getWidth();
        } else {
            wpx = "" + display.getWidth();
            hpx = "" + display.getHeight();
        }
    }

    SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    //      token = pref.getString(PREF_KEY_TOKEN, "");
    //      uid = pref.getString(PREF_KEY_UID, "");
    //      userId = pref.getString(PREF_KEY_USER_ID, "");
    appFilter = pref.getInt(PREF_KEY_APP_FILTER, 0);
    // ipLoginEnable = pref.getBoolean(PREF_KEY_IP_LOGIN_ENABLE, true);

    // ??SIM?
    String pref_subscriberId = pref.getString(PREF_KEY_SUBSCRIBER_ID, "0");
    String pref_simSerialNumber = pref.getString(PREF_KEY_SIM_SERIAL_NUMBER, "0");
    if (!subscriberId.equals(pref_subscriberId) || !simSerialNumber.equals(pref_simSerialNumber)) {
        if (Logger.DEBUG)
            L.d("Change SIM card.");
        cleanCredential(context);
    }
    this.getCredential(context);
}

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncGetGooglePlayMusicMetadataTask.java

@Override
protected String doInBackground(String... params) {

    //Check if any music is playing and fade it out.
    am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    if (mApp.isServiceRunning()) {

        if (mApp.getService().isPlayingMusic()) {
            targetVolume = 0;/* w  w w  .  j a v  a  2  s .  co m*/
            currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
            while (currentVolume > targetVolume) {
                am.setStreamVolume(AudioManager.STREAM_MUSIC, (currentVolume - stepDownValue), 0);
                currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);

            }

            mContext.stopService(new Intent(mContext, AudioPlaybackService.class));

        }

    }

    //Check if the Google Play Music app is installed.
    PackageManager pm = mContext.getPackageManager();
    boolean installed = false;
    try {
        pm.getPackageInfo("com.google.android.music", PackageManager.GET_ACTIVITIES);
        installed = true;
    } catch (NameNotFoundException e1) {
        //The app isn't installed.
        installed = false;
    }

    String result = "GENERIC_EXCEPTION";
    if (installed == false) {
        //Can't do anything here anymore. Quit.
        mApp.getSharedPreferences().edit().putBoolean("GOOGLE_PLAY_MUSIC_ENABLED", false).commit();
        return null;
    } else {
        //Grab music metadata from Google Play Music's public content mApp.
        result = getMetadataFromGooglePlayMusicApp();
    }
    return result;
}

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncPinSongsTask.java

@Override
protected Boolean doInBackground(String... params) {

    //Iterate through the cursor and download/cache the requested songs.
    boolean getAllPinnedTracks = false;
    if (mApp.getPinnedSongsCursor() == null) {
        //The user asked to get all pinned songs from the official GMusic app.
        getAllPinnedTracks = true;//w w  w  .  j av a2s .  c  o  m

        //Check to make sure that the official GMusic app exists.
        PackageManager pm = mContext.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo("com.google.android.music", PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (NameNotFoundException e1) {
            //The app isn't installed.
            installed = false;
        }

        if (installed == false) {
            //The app isn't installed. Notify the user.
            publishProgress(new Integer[] { 2 });
            return false;
        }

        //Query GMusic's content mApp for pinned songs.
        Uri googlePlayMusicContentProviderUri = Uri
                .parse("content://com.google.android.music.MusicContent/audio");
        String[] projection = { "title", "TrackType AS track_type", "LocalCopyPath AS local_copy_path",
                "SourceType AS source_type", "SourceId" };

        /* source_type values:
         * 0: Local file (not used).
         * 1: Unknown.
         * 2: Personal, free GMusic library (used).
         * 3: All Access (not used).
         */
        String selection = "source_type=2 AND track_type=0 AND local_copy_path<>''";
        mApp.setPinnedSongsCursor(mContext.getContentResolver().query(googlePlayMusicContentProviderUri,
                projection, selection, null, null));

    }

    /* Load the cursor data into a temp ArrayList. If the app is closed, the cursor 
     * will also be closed, so we need to preserve it.
     */
    mApp.getPinnedSongsCursor().moveToPosition(-1);
    while (mApp.getPinnedSongsCursor().moveToNext()) {
        //Download the song only if it's from GMusic.
        if (getAllPinnedTracks || mApp.getPinnedSongsCursor()
                .getString(mApp.getPinnedSongsCursor().getColumnIndex(DBAccessHelper.SONG_SOURCE))
                .equals(DBAccessHelper.GMUSIC)) {

            //Retrieve the song ID of current song and set it as the file name.
            String songID = "";
            String songTitle = "";
            if (mApp.getPinnedSongsCursor().getColumnIndex("SourceId") != -1) {
                songID = mApp.getPinnedSongsCursor()
                        .getString(mApp.getPinnedSongsCursor().getColumnIndex("SourceId"));

                songTitle = mApp.getPinnedSongsCursor()
                        .getString(mApp.getPinnedSongsCursor().getColumnIndex("title"));
            } else {
                songID = mApp.getPinnedSongsCursor()
                        .getString(mApp.getPinnedSongsCursor().getColumnIndex(DBAccessHelper.SONG_ID));

                songTitle = mApp.getPinnedSongsCursor()
                        .getString(mApp.getPinnedSongsCursor().getColumnIndex(DBAccessHelper.SONG_TITLE));
            }

            songIdsList.add(songID);
            songTitlesList.add(songTitle);
        }

    }

    //Clear out Common's cursor.
    if (mApp.getPinnedSongsCursor() != null) {
        mApp.getPinnedSongsCursor().close();
        mApp.setPinnedSongsCursor(null);
    }

    //Iterate through the songs and download them.
    for (i = 0; i < songIdsList.size(); i++) {
        downloadSong(songIdsList.get(i));
    }

    return true;
}

From source file:me.zhang.bingo.Utility.java

public static boolean isMuzeiInstalled(Context context) {
    PackageManager pm = context.getPackageManager();
    try {//from   w w  w  . j a va2 s.co m
        pm.getPackageInfo(context.getString(R.string.muzei_package), PackageManager.GET_ACTIVITIES);
        Utility.setMuzeiInstallationStatus(context, MUZEI_INSTALLED);
        return true;
    } catch (PackageManager.NameNotFoundException ignored) {
    }
    Utility.setMuzeiInstallationStatus(context, MUZEI_NOT_INSTALLED);
    return false;
}

From source file:net.sf.xfd.provider.PublicProvider.java

private static @Nullable Intent authActivityIntent(Context c) {
    if (authActivity == null) {
        synchronized (PublicProvider.class) {
            if (authActivity == null) {
                final PackageManager pm = c.getPackageManager();

                final String packageName = c.getPackageName();

                try {
                    final PackageInfo pi = pm.getPackageInfo(packageName,
                            PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA);

                    for (ActivityInfo activity : pi.activities) {
                        final Bundle metadata = activity.metaData;

                        if (metadata != null) {
                            boolean isSuitable = metadata.getBoolean(META_IS_PERMISSION_DELEGATE);

                            if (isSuitable) {
                                authActivity = new Intent(ACTION_PERMISSION_REQUEST)
                                        .setComponent(createRelative(packageName, activity.name))
                                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                break;
                            }/*  w  ww .  j av  a 2 s.  c om*/
                        }
                    }
                } catch (Exception e) {
                    return null;
                }
            }
        }
    }

    return authActivity;
}

From source file:com.afreire.plugins.video.VideoPlayer.java

private boolean isYouTubeInstalled() {
    PackageManager pm = this.cordova.getActivity().getPackageManager();
    try {//from   ww w  . j a  va 2  s.c o m
        pm.getPackageInfo("com.google.android.youtube", PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}

From source file:com.felkertech.n.ActivityUtils.java

/**
 * Opens the correct intent to start editing the channel.
 *
 * @param activity The activity you're calling this from.
 * @param channelUrl The channel's media url.m
 *///from www  .  j  a v a 2  s .c  o m
public static void editChannel(final Activity activity, final String channelUrl) {
    ChannelDatabase cdn = ChannelDatabase.getInstance(activity);
    final JsonChannel jsonChannel = cdn.findChannelByMediaUrl(channelUrl);
    if (channelUrl == null || jsonChannel == null) {
        try {
            Toast.makeText(activity, R.string.toast_error_channel_invalid, Toast.LENGTH_SHORT).show();
        } catch (RuntimeException e) {
            Log.e(TAG, activity.getString(R.string.toast_error_channel_invalid));
        }
        return;
    }
    if (jsonChannel.getPluginSource() != null) {
        // Search through all plugins for one of a given source
        PackageManager pm = activity.getPackageManager();

        try {
            pm.getPackageInfo(jsonChannel.getPluginSource().getPackageName(), PackageManager.GET_ACTIVITIES);
            // Open up this particular activity
            Intent intent = new Intent();
            intent.setComponent(jsonChannel.getPluginSource());
            intent.putExtra(CumulusTvPlugin.INTENT_EXTRA_ACTION, CumulusTvPlugin.INTENT_EDIT);
            Log.d(TAG, "Editing channel " + jsonChannel.toString());
            intent.putExtra(CumulusTvPlugin.INTENT_EXTRA_JSON, jsonChannel.toString());
            activity.startActivity(intent);
        } catch (PackageManager.NameNotFoundException e) {
            new MaterialDialog.Builder(activity)
                    .title(activity.getString(R.string.plugin_not_installed_title,
                            jsonChannel.getPluginSource().getPackageName()))
                    .content(R.string.plugin_not_installed_question).positiveText(R.string.download_app)
                    .negativeText(R.string.open_in_another_plugin)
                    .callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            super.onPositive(dialog);
                            Intent i = new Intent(Intent.ACTION_VIEW);
                            i.setData(Uri.parse("http://play.google.com/store/apps/details?id="
                                    + jsonChannel.getPluginSource().getPackageName()));
                            activity.startActivity(i);
                        }

                        @Override
                        public void onNegative(MaterialDialog dialog) {
                            super.onNegative(dialog);
                            openPluginPicker(false, channelUrl, activity);
                        }
                    }).show();
            Toast.makeText(activity, activity.getString(R.string.toast_msg_pack_not_installed,
                    jsonChannel.getPluginSource().getPackageName()), Toast.LENGTH_SHORT).show();
            openPluginPicker(false, channelUrl, activity);
        }
    } else {
        if (DEBUG) {
            Log.d(TAG, "No specified source");
        }
        openPluginPicker(false, channelUrl, activity);
    }
}