Example usage for android.content.pm PackageManager GET_PERMISSIONS

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

Introduction

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

Prototype

int GET_PERMISSIONS

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

Click Source Link

Document

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

Usage

From source file:com.microsoft.azure.engagement.shared.EngagementShared.java

@TargetApi(Build.VERSION_CODES.M)
public JSONObject requestPermissions(boolean _realtimeLocation, boolean _fineRealtimeLocation,
        boolean _lazyAreaLocation) {

    JSONArray permissions = new JSONArray();

    if (_fineRealtimeLocation)
        permissions.put("ACCESS_FINE_LOCATION");
    else if (_lazyAreaLocation || _realtimeLocation)
        permissions.put("ACCESS_COARSE_LOCATION");

    JSONObject ret = new JSONObject();
    JSONObject p = new JSONObject();
    String[] requestedPermissions = null;
    try {/*w  w w.j ava 2 s .c o m*/
        PackageInfo pi = androidActivity.getPackageManager().getPackageInfo(androidActivity.getPackageName(),
                PackageManager.GET_PERMISSIONS);
        requestedPermissions = pi.requestedPermissions;
        for (int i = 0; i < requestedPermissions.length; i++)
            Log.d(LOG_TAG, requestedPermissions[i]);

    } catch (PackageManager.NameNotFoundException e) {
        logE("Failed to load permissions, NameNotFound: " + e.getMessage());
    }

    logD("requestPermissions()");

    int l = permissions.length();
    for (int i = 0; i < l; i++) {
        try {
            String permission = permissions.getString(i);
            String androidPermission = "android.permission." + permission;

            int grant = androidActivity.checkCallingOrSelfPermission(androidPermission);
            try {
                p.put(permission, grant == PackageManager.PERMISSION_GRANTED);
            } catch (JSONException e) {
                logE("invalid permissions " + e.getMessage());
            }
            if (grant != PackageManager.PERMISSION_GRANTED) {

                if (!Arrays.asList(requestedPermissions).contains(androidPermission)) {
                    String errString = "requested permission " + androidPermission + " not set in Manifest";
                    Log.e(LOG_TAG, errString);
                    try {
                        ret.put("error", errString);
                    } catch (JSONException e) {
                        logE("invalid permissions " + e.getMessage());
                    }
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    // Trying to request the permission if running on AndroidM
                    logD("requesting runtime permission " + androidPermission);
                    androidActivity.requestPermissions(new String[] { androidPermission }, 0);
                }

            } else
                logD(permission + " OK");
        } catch (JSONException e) {
            logE("invalid permissions " + e.getMessage());
        }

    }

    try {
        ret.put("permissions", p);
    } catch (JSONException e) {
        logE("invalid permissions " + e.getMessage());
    }

    return ret;
}

From source file:dk.microting.softkeyboard.autoupdateapk.AutoUpdateApk.java

private static boolean haveInternetPermissions() {
    Set<String> required_perms = new HashSet<String>();
    required_perms.add("android.permission.INTERNET");
    required_perms.add("android.permission.ACCESS_WIFI_STATE");
    required_perms.add("android.permission.ACCESS_NETWORK_STATE");

    PackageManager pm = context.getPackageManager();
    String packageName = context.getPackageName();
    int flags = PackageManager.GET_PERMISSIONS;
    PackageInfo packageInfo = null;/* w w w. ja  v a2 s.c o m*/

    try {
        packageInfo = pm.getPackageInfo(packageName, flags);
        versionCode = packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    if (packageInfo.requestedPermissions != null) {
        for (String p : packageInfo.requestedPermissions) {
            //Log.v(TAG, "permission: " + p.toString());
            required_perms.remove(p);
        }
        if (required_perms.size() == 0) {
            return true; // permissions are in order
        }
        // something is missing
        for (String p : required_perms) {
            Log.e(TAG, "required permission missing: " + p);
        }
    }
    Log.e(TAG, "INTERNET/WIFI access required, but no permissions are found in Manifest.xml");
    return false;
}

From source file:com.landenlabs.all_devtool.ConsoleFragment.java

@SuppressLint("DefaultLocale")
private void updateConsole() {

    if (mSystemViews.isEmpty())
        return;/*w w  w .j  av a2 s  .c o m*/

    try {
        // ----- System -----
        int threadCount = Thread.activeCount();
        ApplicationInfo appInfo = getActivity().getApplicationInfo();

        mSystemViews.get(SYSTEM_PACKAGE).get(1).setText(appInfo.packageName);
        mSystemViews.get(SYSTEM_MODEL).get(1).setText(Build.MODEL);
        mSystemViews.get(SYSTEM_ANDROID).get(1).setText(Build.VERSION.RELEASE);

        if (Build.VERSION.SDK_INT >= 16) {
            int lines = 0;
            final StringBuilder permSb = new StringBuilder();
            try {
                PackageInfo pi = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(),
                        PackageManager.GET_PERMISSIONS);
                for (int i = 0; i < pi.requestedPermissions.length; i++) {
                    if ((pi.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0) {
                        permSb.append(pi.requestedPermissions[i]).append("\n");
                        lines++;
                    }
                }
            } catch (Exception e) {
            }
            final int lineCnt = lines;
            mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms [press]", lines));
            mSystemViews.get(SYSTEM_PERM).get(1).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() == null) {
                        String permStr = permSb.toString().replaceAll("android.permission.", "")
                                .replaceAll("\n[^\n]*permission", "");
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(lineCnt);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(lineCnt);
                    } else {
                        mSystemViews.get(SYSTEM_PERM).get(1).setText(String.format("%d perms", lineCnt));
                        mSystemViews.get(SYSTEM_PERM).get(0).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setLines(1);
                        mSystemViews.get(SYSTEM_PERM).get(1).setTag(null);
                    }
                }
            });

        } else {
            String permStr = "";
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Find Loc");
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                permStr += (" Coarse Loc");
            mSystemViews.get(SYSTEM_PERM).get(1).setText(permStr);
        }

        ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        int processCnt = actMgr.getRunningAppProcesses().size();
        mSystemViews.get(SYSTEM_PROCESSES).get(1).setText(String.format("%d", consoleState.processCnt));
        mSystemViews.get(SYSTEM_PROCESSES).get(2).setText(String.format("%d", processCnt));
        // mSystemViews.get(SYSTEM_BATTERY).get(1).setText(String.format("%d%%", consoleState.batteryLevel));
        mSystemViews.get(SYSTEM_BATTERY).get(2)
                .setText(String.format("%%%d", calculateBatteryLevel(getActivity())));
        // long cpuNano = Debug.threadCpuTimeNanos();
        // mSystemViews.get(SYSTEM_CPU).get(2).setText(String.format("%d%%", cpuNano));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        // ----- Network WiFi-----

        WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
            mNetworkViews.get(NETWORK_WIFI_IP).get(1).setText(Formatter.formatIpAddress(dhcpInfo.ipAddress));
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            mNetworkViews.get(NETWORK_WIFI_SPEED).get(1).setText(String.valueOf(wifiInfo.getLinkSpeed()));
            int numberOfLevels = 10;
            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
            mNetworkViews.get(NETWORK_WIFI_SIGNAL).get(1)
                    .setText(String.format("%%%d", 100 * level / numberOfLevels));
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
    try {
        // ----- Network Traffic-----
        // int uid = android.os.Process.myUid();
        mNetworkViews.get(NETWORK_RCV_BYTES).get(1).setText(String.format("%d", consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(1).setText(String.format("%d", consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(1).setText(String.format("%d", consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(1).setText(String.format("%d", consoleState.netTxPacks));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes()));
        mNetworkViews.get(NETWORK_RCV_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));
        mNetworkViews.get(NETWORK_SND_BYTES).get(2)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes()));
        mNetworkViews.get(NETWORK_SND_PACK).get(2)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets()));

        mNetworkViews.get(NETWORK_RCV_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxBytes() - consoleState.netRxBytes));
        mNetworkViews.get(NETWORK_RCV_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netRxPacks));
        mNetworkViews.get(NETWORK_SND_BYTES).get(3)
                .setText(String.format("%d", TrafficStats.getTotalTxBytes() - consoleState.netTxBytes));
        mNetworkViews.get(NETWORK_SND_PACK).get(3)
                .setText(String.format("%d", TrafficStats.getTotalRxPackets() - consoleState.netTxPacks));

    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // ----- Memory -----
    try {
        MemoryInfo mi = new MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getActivity()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        long heapUsing = Debug.getNativeHeapSize();

        Date now = new Date();
        long deltaMsec = now.getTime() - consoleState.lastFreeze.getTime();

        List<TextView> timeViews = mMemoryViews.get(MEMORY_TIME);
        timeViews.get(1).setText(TIMEFORMAT.format(consoleState.lastFreeze));
        timeViews.get(2).setText(TIMEFORMAT.format(now));
        timeViews.get(3).setText(
                DateUtils.getRelativeTimeSpanString(consoleState.lastFreeze.getTime(), now.getTime(), 0));
        // timeViews.get(3).setText( String.valueOf(deltaMsec));

        List<TextView> usingViews = mMemoryViews.get(MEMORY_USING);
        usingViews.get(1).setText(String.format("%d", consoleState.usingMemory));
        usingViews.get(2).setText(String.format("%d", heapUsing));
        usingViews.get(3).setText(String.format("%d", heapUsing - consoleState.usingMemory));

        List<TextView> freeViews = mMemoryViews.get(MEMORY_FREE);
        freeViews.get(1).setText(String.format("%d", consoleState.freeMemory));
        freeViews.get(2).setText(String.format("%d", mi.availMem));
        freeViews.get(3).setText(String.format("%d", mi.availMem - consoleState.freeMemory));

        List<TextView> totalViews = mMemoryViews.get(MEMORY_TOTAL);
        if (Build.VERSION.SDK_INT >= 16) {
            totalViews.get(1).setText(String.format("%d", consoleState.totalMemory));
            totalViews.get(2).setText(String.format("%d", mi.totalMem));
            totalViews.get(3).setText(String.format("%d", mi.totalMem - consoleState.totalMemory));
        } else {
            totalViews.get(0).setVisibility(View.GONE);
            totalViews.get(1).setVisibility(View.GONE);
            totalViews.get(2).setVisibility(View.GONE);
        }
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }
}

From source file:com.thinkthinkdo.pff_appsettings.PermissionDetailFragment.java

private void displayApps(LinearLayout permListView, String permName) {
    List<PackageInfo> packs = mPm.getInstalledPackages(0);
    SortedMap<String, MyPermissionInfo> usedPerms = new TreeMap<String, MyPermissionInfo>();
    for (int i = 0; i < packs.size(); i++) {
        PackageInfo p = packs.get(i);/*w  ww.  ja v a 2  s  .  c  o m*/
        PackageInfo pkgInfo;
        try {
            pkgInfo = mPm.getPackageInfo(p.packageName, PackageManager.GET_PERMISSIONS);
        } catch (NameNotFoundException e) {
            Log.w(TAG, "Couldn't retrieve permissions for package:" + p.packageName);
            continue;
        }
        // Extract all user permissions
        Set<MyPermissionInfo> permSet = new HashSet<MyPermissionInfo>();
        if ((pkgInfo.applicationInfo != null) && (pkgInfo.applicationInfo.uid != -1)) {
            if (localLOGV)
                Log.w(TAG, "getAllUsedPermissions package:" + p.packageName);
            getAllUsedPermissions(pkgInfo.applicationInfo.uid, permSet);
        }
        for (MyPermissionInfo tmpInfo : permSet) {
            if (localLOGV)
                Log.i(TAG, "tmpInfo package:" + p.packageName + ", tmpInfo.name=" + tmpInfo.name);
            if (tmpInfo.name.equalsIgnoreCase(permName)) {
                if (localLOGV)
                    Log.w(TAG, "Adding package:" + p.packageName);
                tmpInfo.packageName = p.packageName;
                usedPerms.put(tmpInfo.packageName, tmpInfo);
            }
        }
    }
    mUsedPerms = usedPerms;
    permListView.removeAllViews();
    /* add the All Entry                        */
    int spacing = (int) (8 * mContext.getResources().getDisplayMetrics().density);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    int j = 0;
    for (Map.Entry<String, MyPermissionInfo> entry : usedPerms.entrySet()) {
        MyPermissionInfo tmpPerm = entry.getValue();
        if (tmpPerm.packageName.compareToIgnoreCase("com.thinkthinkdo.pff_appsettings") != 0) {
            if (localLOGV)
                Log.w(TAG, "usedPacks containd package:" + tmpPerm.packageName);
            View view = getAppItemView(mContext, mInflater, tmpPerm);
            lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            if (j == 0) {
                lp.topMargin = spacing;
            }
            if (permListView.getChildCount() == 0) {
                lp.topMargin *= 2;
            }
            permListView.addView(view, lp);
            j++;
        }
    }
}

From source file:com.example.android.tflitecamerademo.Camera2BasicFragment.java

private String[] getRequiredPermissions() {
    Activity activity = getActivity();//from   w ww.j a v  a 2s . c  om
    try {
        PackageInfo info = activity.getPackageManager().getPackageInfo(activity.getPackageName(),
                PackageManager.GET_PERMISSIONS);
        String[] ps = info.requestedPermissions;
        if (ps != null && ps.length > 0) {
            return ps;
        } else {
            return new String[0];
        }
    } catch (Exception e) {
        return new String[0];
    }
}

From source file:com.dafeng.upgradeapp.util.AutoUpdateApk.java

private boolean haveInternetPermissions() {
    Set<String> required_perms = new HashSet<String>();
    required_perms.add("android.permission.INTERNET");
    required_perms.add("android.permission.ACCESS_WIFI_STATE");
    required_perms.add("android.permission.ACCESS_NETWORK_STATE");

    PackageManager pm = context.getPackageManager();
    String packageName = context.getPackageName();
    int flags = PackageManager.GET_PERMISSIONS;
    PackageInfo packageInfo = null;/*from w w  w. j  av  a  2  s. c om*/

    try {
        packageInfo = pm.getPackageInfo(packageName, flags);
        versionCode = packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        // e.printStackTrace();
        Log_e(TAG, e.getMessage());
    }
    if (packageInfo.requestedPermissions != null) {
        for (String p : packageInfo.requestedPermissions) {
            // Log_v(TAG, "permission: " + p.toString());
            required_perms.remove(p);
        }
        if (required_perms.size() == 0) {
            return true; // permissions are in order
        }
        // something is missing
        for (String p : required_perms) {
            Log_e(TAG, "required permission missing: " + p);
        }
    }
    Log_e(TAG, "INTERNET/WIFI access required, but no permissions are found in Manifest.xml");
    return false;
}

From source file:com.google.android.apps.dashclock.DashClockService.java

private void enforceCallingPermission(String permission) throws SecurityException {
    // We need to check that any of the packages of the caller has
    // the request permission
    final PackageManager pm = getPackageManager();
    try {//  w  ww  . j  ava2s .  c o m
        String[] packages = pm.getPackagesForUid(Binder.getCallingUid());
        if (packages != null) {
            for (String pkg : packages) {
                PackageInfo pi = pm.getPackageInfo(pkg, PackageManager.GET_PERMISSIONS);
                if (pi.requestedPermissions != null) {
                    for (String requestedPermission : pi.requestedPermissions) {
                        if (requestedPermission.equals(permission)) {
                            // The caller has the request permission
                            return;
                        }
                    }
                }
            }
        }
    } catch (PackageManager.NameNotFoundException ex) {
        // Ignore. Package wasn't found
    }
    throw new SecurityException("Caller doesn't have the request permission \"" + permission + "\"");
}

From source file:com.autoupdateapk.AutoUpdateApk.java

private boolean haveInternetPermissions() {
    Set<String> required_perms = new HashSet<String>();
    required_perms.add("android.permission.INTERNET");
    required_perms.add("android.permission.ACCESS_WIFI_STATE");
    required_perms.add("android.permission.ACCESS_NETWORK_STATE");

    PackageManager pm = context.getPackageManager();
    String packageName = context.getPackageName();
    int flags = PackageManager.GET_PERMISSIONS;
    PackageInfo packageInfo = null;/*from   ww  w  .  j a  v a 2 s .c o m*/

    try {
        packageInfo = pm.getPackageInfo(packageName, flags);
        versionCode = Integer.parseInt(packageInfo.versionName);
    } catch (NameNotFoundException e) {
        Log_e(TAG, e.getMessage());
    }

    if (packageInfo.requestedPermissions != null) {
        for (String p : packageInfo.requestedPermissions) {
            // Log_v(TAG, "permission: " + p.toString());
            required_perms.remove(p);
        }
        if (required_perms.size() == 0) {
            return true; // permissions are in order
        }
        // something is missing
        for (String p : required_perms) {
            Log_e(TAG, "required permission missing: " + p);
        }
    }
    Log_e(TAG, "INTERNET/WIFI access required, but no permissions are found in Manifest.xml");
    return false;
}

From source file:com.thinkthinkdo.pff_appsettings.PermissionDetailFragment.java

private void getPermissionsForPackage(String packageName, Set<MyPermissionInfo> permSet) {
    PackageInfo pkgInfo;/*w  w w.j a  v  a2s . co  m*/
    try {
        pkgInfo = mPm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
    } catch (NameNotFoundException e) {
        Log.w(TAG, "Couldn't retrieve permissions for package:" + packageName);
        return;
    }
    if ((pkgInfo != null) && (pkgInfo.requestedPermissions != null)) {
        extractPerms(pkgInfo, permSet, pkgInfo);
    }
}

From source file:com.android.packageinstaller.PackageInstallerActivity.java

private void processPackageUri(final Uri packageUri) {
    mPackageURI = packageUri;/*from w  ww . jav  a 2  s .com*/

    final String scheme = packageUri.getScheme();
    final PackageUtil.AppSnippet as;

    switch (scheme) {
    case SCHEME_PACKAGE: {
        try {
            mPkgInfo = mPm.getPackageInfo(packageUri.getSchemeSpecificPart(),
                    PackageManager.GET_PERMISSIONS | PackageManager.GET_UNINSTALLED_PACKAGES);
        } catch (NameNotFoundException e) {
        }
        if (mPkgInfo == null) {
            Log.w(TAG, "Requested package " + packageUri.getScheme()
                    + " not available. Discontinuing installation");
            showDialogInner(DLG_PACKAGE_ERROR);
            setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK);
            return;
        }
        as = new PackageUtil.AppSnippet(mPm.getApplicationLabel(mPkgInfo.applicationInfo),
                mPm.getApplicationIcon(mPkgInfo.applicationInfo));
    }
        break;

    case SCHEME_FILE: {
        File sourceFile = new File(packageUri.getPath());
        PackageParser.Package parsed = PackageUtil.getPackageInfo(sourceFile);

        // Check for parse errors
        if (parsed == null) {
            Log.w(TAG, "Parse error when parsing manifest. Discontinuing installation");
            showDialogInner(DLG_PACKAGE_ERROR);
            setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK);
            return;
        }
        mPkgInfo = PackageParser.generatePackageInfo(parsed, null, PackageManager.GET_PERMISSIONS, 0, 0, null,
                new PackageUserState());
        as = PackageUtil.getAppSnippet(this, mPkgInfo.applicationInfo, sourceFile);
    }
        break;

    case SCHEME_CONTENT: {
        mStagingAsynTask = new StagingAsyncTask();
        mStagingAsynTask.execute(packageUri);
        return;
    }

    default: {
        Log.w(TAG, "Unsupported scheme " + scheme);
        setPmResult(PackageManager.INSTALL_FAILED_INVALID_URI);
        clearCachedApkIfNeededAndFinish();
        return;
    }
    }

    PackageUtil.initSnippetForNewApp(this, as, R.id.app_snippet);

    initiateInstall();
}