Example usage for android.content.pm PackageManager PERMISSION_GRANTED

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

Introduction

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

Prototype

int PERMISSION_GRANTED

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

Click Source Link

Document

Permission check result: this is returned by #checkPermission if the permission has been granted to the given package.

Usage

From source file:com.appnexus.opensdk.AdRequest.java

private AdRequest(AdRequester adRequester, int httpRetriesLeft, int blankRetriesLeft) {
    owner = adRequester.getOwner();/*from   w  w w .  ja va  2 s.c o  m*/
    this.requester = adRequester;
    this.httpRetriesLeft = httpRetriesLeft;
    this.blankRetriesLeft = blankRetriesLeft;
    this.placementId = owner.getPlacementID();
    context = owner.getContext();
    String aid = android.provider.Settings.Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

    // Do we have access to location?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_FINE_LOCATION") == PackageManager.PERMISSION_GRANTED
            || context.checkCallingOrSelfPermission(
                    "android.permission.ACCESS_COARSE_LOCATION") == PackageManager.PERMISSION_GRANTED) {
        // Get lat, long from any GPS information that might be currently
        // available
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location lastLocation = lm.getLastKnownLocation(lm.getBestProvider(new Criteria(), false));
        if (lastLocation != null) {
            lat = "" + lastLocation.getLatitude();
            lon = "" + lastLocation.getLongitude();
            locDataAge = "" + (System.currentTimeMillis() - lastLocation.getTime());
            locDataPrecision = "" + lastLocation.getAccuracy();
        }
    } else {
        Clog.w(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_location));
    }

    // Do we have permission ACCESS_NETWORK_STATE?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_NETWORK_STATE") != PackageManager.PERMISSION_GRANTED) {
        Clog.e(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_network_state));
        fail();
        this.cancel(true);
        return;
    }

    // Get orientation, the current rotation of the device
    orientation = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
            ? "h"
            : "v";
    // Get hidmd5, hidsha1, the device ID hashed
    if (Settings.getSettings().hidmd5 == null) {
        Settings.getSettings().hidmd5 = HashingFunctions.md5(aid);
    }
    hidmd5 = Settings.getSettings().hidmd5;
    if (Settings.getSettings().hidsha1 == null) {
        Settings.getSettings().hidsha1 = HashingFunctions.sha1(aid);
    }
    hidsha1 = Settings.getSettings().hidsha1;
    // Get devMake, devModel, the Make and Model of the current device
    devMake = Settings.getSettings().deviceMake;
    devModel = Settings.getSettings().deviceModel;
    // Get carrier
    if (Settings.getSettings().carrierName == null) {
        Settings.getSettings().carrierName = ((TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperatorName();
    }
    carrier = Settings.getSettings().carrierName;
    // Get firstlaunch and convert it to a string
    firstlaunch = Settings.getSettings().first_launch;
    // Get ua, the user agent...
    ua = Settings.getSettings().ua;
    // Get wxh

    if (owner.isBanner()) {
        this.width = ((BannerAdView) owner).getAdWidth();
        this.height = ((BannerAdView) owner).getAdHeight();
    }

    maxHeight = owner.getContainerHeight();
    maxWidth = owner.getContainerWidth();

    if (Settings.getSettings().mcc == null || Settings.getSettings().mnc == null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String networkOperator = tm.getNetworkOperator();
        if (networkOperator != null && networkOperator.length() >= 6) {
            Settings.getSettings().mcc = networkOperator.substring(0, 3);
            Settings.getSettings().mnc = networkOperator.substring(3);
        }
    }
    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    connection_type = wifi.isConnected() ? "wifi" : "wan";
    dev_time = "" + System.currentTimeMillis();

    if (owner instanceof InterstitialAdView) {
        // Make string for allowed_sizes
        allowedSizes = "";
        ArrayList<Size> sizes = ((InterstitialAdView) owner).getAllowedSizes();
        for (Size s : sizes) {
            allowedSizes += "" + s.width() + "x" + s.height();
            // If not last size, add a comma
            if (sizes.indexOf(s) != sizes.size() - 1)
                allowedSizes += ",";
        }
    }

    nativeBrowser = owner.getOpensNativeBrowser() ? "1" : "0";

    //Reserve price
    reserve = owner.getReserve();
    if (reserve <= 0) {
        this.psa = owner.shouldServePSAs ? "1" : "0";
    } else {
        this.psa = "0";
    }

    age = owner.getAge();
    if (owner.getGender() != null) {
        if (owner.getGender() == AdView.GENDER.MALE) {
            gender = "m";
        } else if (owner.getGender() == AdView.GENDER.FEMALE) {
            gender = "f";
        } else {
            gender = null;
        }
    }
    customKeywords = owner.getCustomKeywords();

    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;
    language = Settings.getSettings().language;
}

From source file:com.adam.aslfms.SettingsActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    try {//from  www  .  j  a v a 2  s.  co  m
        if (requestCode == REQUEST_READ_STORAGE) {

            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //PERMISSION GRANTED
            } else {
                //PERMISSION DENIED permission denied
                Toast.makeText(SettingsActivity.this, "App will not function correctly.", Toast.LENGTH_LONG)
                        .show(); //TODO string
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    } catch (Exception e) {
        Log.e(TAG, "READ_EXTERNAL_STORAGE. " + e);
    }
}

From source file:com.ztspeech.weibo.sdk.kaixin.Kaixin.java

/**
 * access_token(User-Agent Flow)//from   w ww .  j a  va  2  s .com
 * 
 * @param context
 * @param permissions
 *            http://wiki.open.kaixin001.com/index.php?id=OAuth%E6%96
 *            % 87%E6%A1%A3#REST%E6%
 *            8E%A5%E5%8F%A3%E5%92%8COAuth%E6%9D%83%E9%99%90%E5%AF%B9%E7%85%
 *            A 7%E8%A1%A8
 * @param listener
 * @param redirectUrl
 * @param responseType
 */
private void authorize(final Context context, String[] permissions, final KaixinAuthListener listener,
        final String redirectUrl, String responseType) {

    CookieSyncManager.createInstance(context);

    Bundle params = new Bundle();
    params.putString("client_id", API_KEY);
    params.putString("response_type", responseType);
    params.putString("redirect_uri", redirectUrl);
    params.putString("state", "");
    params.putString("display", "page");
    params.putString("oauth_client", "1");

    if (permissions != null && permissions.length > 0) {
        String scope = TextUtils.join(" ", permissions);
        params.putString("scope", scope);
    }

    String url = KX_AUTHORIZE_URL + "?" + Util.encodeUrl(params);
    if (context
            .checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
        Util.showAlert(context, "", "");
    } else {
        new KaixinDialog(context, url, new KaixinDialogListener() {
            @Override
            public int onPageBegin(String url) {
                return KaixinDialogListener.DIALOG_PROCCESS;
            }

            @Override
            public void onPageFinished(String url) {
            }

            @Override
            public boolean onPageStart(String url) {
                return (KaixinDialogListener.PROCCESSED == parseUrl(url));
            }

            @Override
            public void onReceivedError(int errorCode, String description, String failingUrl) {
                listener.onAuthError(new KaixinAuthError(String.valueOf(errorCode), description, failingUrl));
            }

            private int parseUrl(String url) {
                if (url.startsWith(KX_AUTHORIZE_CALLBACK_URL)) {
                    Bundle values = Util.parseUrl(url);
                    String error = values.getString("error");// 
                    if (error != null) {
                        if (ACCESS_DENIED.equalsIgnoreCase(error)) {
                            listener.onAuthCancel(values);
                        } else if (LOGIN_DENIED.equalsIgnoreCase(error)) {
                            listener.onAuthCancelLogin();
                        } else {
                            listener.onAuthError(new KaixinAuthError(error, error, url));
                        }

                        Util.clearCookies(context);

                        setAccessToken(null);
                        setRefreshToken(null);
                        setAccessExpires(0L);

                    } else {
                        this.authComplete(values, url);
                    }
                    return KaixinDialogListener.PROCCESSED;
                }
                return KaixinDialogListener.UNPROCCESS;
            }

            private void authComplete(Bundle values, String url) {
                CookieSyncManager.getInstance().sync();
                String accessToken = values.getString(ACCESS_TOKEN);
                String refreshToken = values.getString(REFRESH_TOKEN);
                String expiresIn = values.getString(EXPIRES_IN);
                if (accessToken != null && refreshToken != null && expiresIn != null) {
                    try {
                        setAccessToken(accessToken);
                        setRefreshToken(refreshToken);
                        setAccessExpiresIn(expiresIn);
                        updateStorage(context);
                        listener.onAuthComplete(values);
                    } catch (Exception e) {
                        listener.onAuthError(
                                new KaixinAuthError(e.getClass().getName(), e.getMessage(), e.toString()));
                    }
                } else {
                    listener.onAuthError(new KaixinAuthError("", "", url));
                }
            }
        }).show();
    }
}

From source file:me.kartikarora.transfersh.adapters.FileGridAdapter.java

private void checkForDownload(final String name, final String type, final String url, View view) {
    this.permissionRequestResult = new PermissionRequestResult() {
        @Override//from w  w  w .  ja  v a  2  s .co  m
        public void onPermitted() {
            beginDownload(name, type, url);
        }
    };
    if (ActivityCompat.checkSelfPermission(context,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        beginDownload(name, type, url);
    else {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE))
            showRationale(view);
        else {
            showPermissionDialog();
        }
    }
}

From source file:com.nextgis.woody.activity.MainActivity.java

private boolean isGrantResultsOk(int[] grantResults) {
    if (grantResults.length == 4) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED)
                return false;
        }/*from   w  w w . j a  v a 2 s. c o  m*/

        return true;
    }
    return false;
}

From source file:com.aero2.android.DefaultActivities.SmogMapActivity.java

@Override
public void onMapReady(GoogleMap map) {

    //smoothly fade away splash screen
    fadeSplashScreen();/*from   www.  j a  va2 s  .  com*/

    // Override the default content description on the view, for accessibility mode.
    // Ideally this string would be localised.
    map.setContentDescription("Google Map with polygons.");
    map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
    map.getUiSettings().setTiltGesturesEnabled(false);
    googleMap = map;
    //Moving camera to last known location
    restorePreviousMapState();

    //if the user hasn't granted location permissions to the app
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            removeSplashScreen();
            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {
            // No explanation needed, we can request the permission.
            removeSplashScreen();
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    MY_PERMISSIONS_REQUEST);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
        return;
    }
    map.setMyLocationEnabled(true);
    map.getUiSettings().setMyLocationButtonEnabled(false);
    currentLocationButton = (FloatingActionButton) findViewById(R.id.myLocation);
    currentLocationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Add code for showing legend dialog here
            moveCameraToMyLocation();
        }
    });
    //add heat map to the instance of google map
    addHeatMap(map);

}

From source file:com.elkriefy.android.apps.permissionmigrationguide.MainActivity.java

@TargetApi(Build.VERSION_CODES.M)
private void marshmallowPermissionsFlowOnConnected() {
    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        getLocation();// w w w. j  a  v a 2 s.co  m
    } else {
        // Should we show an explanation?
        if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Explain to the user why we need to read the contacts
            Toast.makeText(this, R.string.permission_rationale, Toast.LENGTH_LONG).show();
        }

        requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    }
}

From source file:abanoubm.dayra.main.Main.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (Utility.getArabicLang(getApplicationContext()) == 1) {
        Utility.setArabicLang(getApplicationContext(), 2);

        Locale myLocale = new Locale("ar");
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;/*from w ww . j  ava  2 s  . com*/
        res.updateConfiguration(conf, dm);

        finish();
        startActivity(new Intent(getIntent()));
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_main);
    ((TextView) findViewById(R.id.subhead1)).setText(R.string.app_name);
    ((TextView) findViewById(R.id.subhead2)).setText(BuildConfig.VERSION_NAME);
    findViewById(R.id.nav_back).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            finish();

        }
    });
    ((TextView) findViewById(R.id.footer)).setText("dayra " + BuildConfig.VERSION_NAME + " @"
            + new SimpleDateFormat("yyyy", Locale.getDefault()).format(new Date()) + " Abanoub M.");

    if (!Utility.getDayraName(getApplicationContext()).equals("")) {
        startActivity(new Intent(getApplicationContext(), Home.class));
        finish();
    }

    ListView lv = (ListView) findViewById(R.id.home_list);

    mMenuItemAdapter = new MenuItemAdapter(getApplicationContext(),
            new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sign_menu))), 1);
    lv.setAdapter(mMenuItemAdapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 0:
                sign();
                break;
            case 1:
                register();
                break;
            case 2:
                if (Build.VERSION.SDK_INT < 23 || ContextCompat.checkSelfPermission(Main.this,
                        Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    importDB();
                } else {
                    ActivityCompat.requestPermissions(Main.this,
                            new String[] { android.Manifest.permission.READ_EXTERNAL_STORAGE }, IMPORT_REQUEST);
                }
                break;
            case 3:
                startActivity(new Intent(Intent.ACTION_VIEW).setData(
                        Uri.parse("https://drive.google.com/file/d/0B1rNCm5K9cvwVXJTTzNqSFdrVk0/view")));
                break;
            case 4:
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(
                        "https://drive.google.com/open?id=1flSRdoiIT_hNd96Kxz3Ww3EhXDLZ45FhwFJ2hF9vl7g")));
                break;
            case 5: {

                AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
                builder.setTitle(R.string.label_choose_language);
                builder.setItems(getResources().getStringArray(R.array.language_menu),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String temp;
                                if (which == 1) {
                                    temp = "en";
                                    Utility.setArabicLang(getApplicationContext(), 0);
                                } else {
                                    temp = "ar";
                                    Utility.setArabicLang(getApplicationContext(), 2);
                                }
                                Locale myLocale = new Locale(temp);
                                Resources res = getResources();
                                DisplayMetrics dm = res.getDisplayMetrics();
                                Configuration conf = res.getConfiguration();
                                conf.locale = myLocale;
                                res.updateConfiguration(conf, dm);

                                finish();
                                startActivity(new Intent(getIntent()));
                            }

                        });
                builder.create().show();

            }
                break;
            case 6:
                try {
                    getPackageManager().getPackageInfo("com.facebook.katana", 0);
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/453595434816965"))
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/dayraapp"))
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                }
                break;

            case 7:

                try {
                    getPackageManager().getPackageInfo("com.facebook.katana", 0);
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/1363784786"))
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                } catch (Exception e) {
                    startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/EngineeroBono"))
                                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                }
                break;
            case 8:
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
                Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                try {
                    startActivity(goToMarket);
                } catch (Exception e) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
                }
                break;
            case 9:
                if (Build.VERSION.SDK_INT < 23 || ContextCompat.checkSelfPermission(Main.this,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(Intent.ACTION_VIEW).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    intent.setDataAndType(Uri.fromFile(new File(Utility.getDayraFolder())), "*/*");
                    startActivity(
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
                } else {
                    ActivityCompat.requestPermissions(Main.this,
                            new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE },
                            FOLDER_REQUEST);
                }
                break;
            case 10:
                LayoutInflater li = LayoutInflater.from(getApplicationContext());
                final View aboutView = li.inflate(R.layout.dialogue_about, null, false);
                final AlertDialog ad = new AlertDialog.Builder(Main.this).setCancelable(true).create();
                ad.setView(aboutView, 0, 0, 0, 0);
                ad.show();
                ((TextView) aboutView.findViewById(R.id.about))
                        .setText(String.format(getResources().getString(R.string.copyright),
                                Calendar.getInstance().get(Calendar.YEAR)));

                ((TextView) aboutView.findViewById(R.id.notice)).setText(GoogleApiAvailability.getInstance()
                        .getOpenSourceSoftwareLicenseInfo(getApplicationContext()));
                aboutView.findViewById(R.id.btn).setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        ad.cancel();
                    }
                });
                break;
            }
        }
    });

}

From source file:ch.fhnw.comgr.GLES3Activity.java

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
    case 1: {/*from  w  ww. jav a 2 s.  com*/
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, String.format("onRequestPermissionsResult: CAMERA permission granted."));
            cameraPermissionGranted = true;
        } else {
            Log.i(TAG, String.format("onRequestPermissionsResult: CAMERA permission refused."));
            cameraPermissionGranted = false;
        }
        return;
    }
    }
}

From source file:cc.metapro.openct.myclass.ClassActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.refresh_classes) {
        LocalUser user = LocalHelper.getCmsStuInfo(this);
        if (user.isEmpty()) {
            Toast.makeText(this, R.string.please_fill_cms_info, Toast.LENGTH_LONG).show();
            startActivity(new Intent(this, SettingsActivity.class));
        } else {/*from  w  ww  . jav  a2 s  .co  m*/
            mPresenter.loadOnlineInfo(getSupportFragmentManager());
        }
        return true;
    } else if (id == R.id.edit_classes) {
        startActivity(new Intent(this, AllClassesActivity.class));
    } else if (id == R.id.set_background) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasPermission = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                        REQUEST_WRITE_STORAGE);
            } else {
                showFilerChooser();
            }
        } else {
            showFilerChooser();
        }
    }
    return super.onOptionsItemSelected(item);
}