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:me.piebridge.prevent.ui.UserGuideActivity.java

private boolean hasPermission() {
    return ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
            || !ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
}

From source file:cn.xcom.helper.activity.AuthorizedActivity.java

private void showPickDialog() {
    new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)
            .setNegativeButton("", new DialogInterface.OnClickListener() {
                @Override//from w  ww  .  j ava2 s  .c  om
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent albumIntent = new Intent();
                    albumIntent.setType("image/*");
                    albumIntent.setAction(Intent.ACTION_PICK);
                    startActivityForResult(albumIntent, PHOTO_REQUEST_ALBUM);
                }
            }).setPositiveButton("?", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    int permissionCheck = ContextCompat.checkSelfPermission(mContext,
                            Manifest.permission.CAMERA);
                    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        String state = Environment.getExternalStorageState();
                        if (state.equals(Environment.MEDIA_MOUNTED)) {
                            File path = Environment
                                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                            File file = new File(path, "51helper.jpg");
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                        }
                        startActivityForResult(cameraIntent, PHOTO_REQUEST_CAMERA);
                    } else if (permissionCheck == PackageManager.PERMISSION_DENIED) {
                        // Should we show an explanation?
                        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) mContext,
                                Manifest.permission.CAMERA)) {

                            // 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.

                            ActivityCompat.requestPermissions((Activity) mContext,
                                    new String[] { Manifest.permission.CAMERA },
                                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

                            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                            // app-defined int constant. The callback method gets the
                            // result of the request.
                        }
                    }

                }
            }).show();
}

From source file:com.esri.cordova.geolocation.AdvancedGeolocation.java

/**
 * Cordova callback when querying for permissions
 * Overrides in CordovaPlugin//  w  ww.  j a v  a2  s  . c  om
 * FYI: you can verify device permissions using:
 * <code>adb shell pm list permissions -d -g</code>
 * Reference: http://stackoverflow.com/questions/30719047/android-m-check-runtime-permission-how-to-determine-if-the-user-checked-nev
 * @param requestCode The request code we assign - it's basically a token
 * @param permissions The requested permissions - never null
 * @param grantResults <code>PERMISSION_GRANTED</code> or <code>PERMISSION_DENIED</code> - never null
 * @throws JSONException
 */
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults)
        throws JSONException {
    // 1st Try - ALLOW or DENY. There is no don't ask again check box.
    // If ALLOW the proceed and all is good
    // If DENY then retry with NEVER ASK AGAIN prompt
    // If ALLOW then proceed and all is good
    // If DENY again with never ask again checked, then lock down the app and don't ask again
    // If DENY again without checking never ask again, then recheck on next app launch
    // have to remember to manually reactivate
    //
    // IMPORTANT! When this event completes the onResume event will fire!

    // TEST CASES
    // Start -> Allow -> minimize -> open app
    // Start -> Allow -> minimize -> Change perms to deny geo -> open app
    // Start -> Deny -> Deny -> minimize -> open app
    // Start -> Deny -> Deny -> minimize -> Change perms to allow geo -> open app
    // Start -> Deny -> Deny and check no ask -> minimize -> open app
    // Start -> Deny -> Deny and check no ask -> minimize -> Change perms to allow geo -> open app
    // Repeat test cases except shut off device geo permissions
    //
    // Reference for Permission Denied Workflow: https://material.google.com/patterns/permissions.html#permissions-denied-permissions

    if (requestCode == REQUEST_LOCATION_PERMS_CODE && grantResults.length > 1) {

        // If permission was granted then go ahead
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "GEO PERMISSIONS GRANTED.");
            _permissionsController.handleOnRequestAllowed();
        }
        // If permission was denied then we can't run geolocation - permission DISABLED
        else {
            Log.w(TAG, "GEO PERMISSIONS DENIED.");
            _permissionsController.handleOnRequestDenied();

            // User doesn't want to see any more preference-related dialog boxes
            if (_permissionsController.getShowRationale() == _permissionsController.DENIED_NOASK) {
                Log.w(TAG, "requestPermissions() Callback: "
                        + ErrorMessages.LOCATION_SERVICES_DENIED_NOASK().message);
                setSharedPreferences(_permissionsController.SHARED_PREFS_LOCATION_KEY,
                        _permissionsController.SHARED_PREFS_GEO_DENIED_NOASK);
            }
        }
    }
}

From source file:com.a3did.partner.recosample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_reco);
    mLayout = findViewById(R.id.mainLayout);

    View includedLayout = (View) findViewById(R.id.reco_settings_values);
    TextView mRecoOnlyText = (TextView) includedLayout.findViewById(R.id.recoRecoonlySetting);
    if (SCAN_RECO_ONLY) {
        mRecoOnlyText.setText(R.string.settings_result_true);
    } else {/*from  w  ww.  ja  va  2  s.  co m*/
        mRecoOnlyText.setText(R.string.settings_result_false);
    }

    TextView mDiscontinuousText = (TextView) includedLayout.findViewById(R.id.recoDiscontinouosSetting);
    if (DISCONTINUOUS_SCAN) {
        mDiscontinuousText.setText(R.string.settings_result_true);
    } else {
        mDiscontinuousText.setText(R.string.settings_result_false);
    }

    TextView mBackgroundRangingTimeoutText = (TextView) includedLayout
            .findViewById(R.id.recoBackgroundtimeoutSetting);
    if (ENABLE_BACKGROUND_RANGING_TIMEOUT) {
        mBackgroundRangingTimeoutText.setText(R.string.settings_result_true);
    } else {
        mBackgroundRangingTimeoutText.setText(R.string.settings_result_false);
    }

    //If a user device turns off bluetooth, request to turn it on.
    //?  ?? .
    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = mBluetoothManager.getAdapter();

    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
    }

    /**
     * In order to use RECO SDK for Android API 23 (Marshmallow) or higher,
     * the location permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) is required.
     * Please refer to the following permission guide and sample code provided by Google.
     *
     * ? API 23 ()?? , ?? RECO SDK  
     *   (ACCESS_COARSE_LOCATION ? ACCESS_FINE_LOCATION)?  .
     *  ? , ?  ?  ?.
     *
     * http://www.google.com/design/spec/patterns/permissions.html
     * https://github.com/googlesamples/android-RuntimePermissions
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.i("MainActivity",
                    "The location permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) is not granted.");
            this.requestLocationPermission();
        } else {
            Log.i("MainActivity",
                    "The location permission (ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION) is already granted.");
        }
    }
}

From source file:com.kaixin.connect.Kaixin.java

/**
 * access_token(User-Agent Flow)//  www  . j  ava  2  s  .c o m
 * 
 * @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);
                        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:com.justinbull.ichnaeachecker.MainActivity.java

public void setCellInfo() {
    int tmPermCheck = ContextCompat.checkSelfPermission(MainActivity.this,
            android.Manifest.permission.ACCESS_COARSE_LOCATION);
    if (tmPermCheck == PackageManager.PERMISSION_GRANTED) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1
                && tm.getAllCellInfo() != null) {
            mVisibleCells = GeneralCellInfoFactory.getInstances(tm.getAllCellInfo());
            // Sort cells by strength
            Collections.sort(mVisibleCells, new Comparator<GeneralCellInfo>() {
                @Override/*from   w  w  w .  j  a v  a  2 s . c o  m*/
                public int compare(GeneralCellInfo lhs, GeneralCellInfo rhs) {
                    int lhsDbm = lhs.getAsuStrength();
                    int rhsDbm = rhs.getAsuStrength();
                    if (lhsDbm == rhsDbm) {
                        return 0;
                    }
                    return lhsDbm > rhsDbm ? -1 : 1;
                }
            });
            mRegisteredCells.clear();
            if (mVisibleCells.size() == 0) {
                Log.w(TAG, "setCellInfo: No visible cells (primary or neighbours), unable to do anything");
            }
            for (GeneralCellInfo cell : mVisibleCells) {
                Log.i(TAG, "Device aware of " + cell.toString());
                if (cell.isRegistered()) {
                    mRegisteredCells.add(cell);
                }
            }
            if (mRegisteredCells.isEmpty()) {
                Log.w(TAG, "setCellInfo: No registered cells, nothing to select.");
                mSelectedCell = null;
            } else {
                Log.i(TAG, "setCellInfo: Preselected strongest registered cell: " + mRegisteredCells.get(0));
                mSelectedCell = mRegisteredCells.get(0);
            }
        } else {
            Log.e(TAG,
                    "setCellInfo: Android device too old to use getAllCellInfo(), need to implement getCellLocation() fallback!");
        }
        mCellListAdapter = new ArrayAdapter<GeneralCellInfo>(this, android.R.layout.simple_list_item_1,
                mVisibleCells);
    } else if (tmPermCheck == PackageManager.PERMISSION_DENIED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
            Toast.makeText(MainActivity.this, "Dude we need permissions", Toast.LENGTH_LONG).show();
        }
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
                Consts.REQUEST_COARSE_LOCATION);
    } else {
        Log.wtf(TAG, "setCellInfo: Received unknown int from ContextCompat.checkSelfPermission()");
    }
}

From source file:me.piebridge.prevent.ui.UserGuideActivity.java

private boolean checkPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }/*  ww  w . ja v a2  s  .c o m*/
    if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    }
    return false;
}

From source file:com.ds.kaixin.Kaixin.java

/**
 * access_token(User-Agent Flow)// w w  w .  j  av a  2s  . c om
 * 
 * @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() {

            public int onPageBegin(String url) {
                return KaixinDialogListener.DIALOG_PROCCESS;
            }

            public void onPageFinished(String url) {
            }

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

            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);
                        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:br.com.anteros.vendas.gui.AnexoCadastroActivity.java

/**
 * Evento quando um item do menu foi clicado
 * @param item/*from  ww w  .  j  a va2 s.co m*/
 * @return
 */
@Override
public boolean onOptionsItemSelected(android.view.MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        /**
         * Volta para tela anterior. Se estiver editando pergunta
         * ao usurio se deseja cancelar.
         */
        new QuestionAlert(this, getResources().getString(R.string.app_name), "Cancelar anexo ?",
                new QuestionAlert.QuestionListener() {

                    public void onPositiveClick() {
                        cancelaEdicaoAnexo();
                    }

                    public void onNegativeClick() {

                    }
                }).show();

        break;

    case R.id.cliente_cadastro_action_upload:
        /**
         * Chama o mtodo para anexar arquivos.
         */
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                    1);
        } else {
            anexarArquivos();
        }
        break;

    case R.id.cliente_cadastro_action_camera:
        /**
         * Verifica se App possu permisso para usar a cmera e gravar arquivos. Se no tiver
         * requisita permisso.
         */
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
        } else {
            /**
             * Se j tem permisso inicia a cmera.
             */
            iniciaCamera();
        }
        break;

    case R.id.cliente_cadastro_action_salvar:
        /**
         * Pergunta ao usurio se deseja salvar o anexo.
         */
        new QuestionAlert(this, getResources().getString(R.string.app_name), "Salvar Anexo ?",
                new QuestionAlert.QuestionListener() {

                    public void onPositiveClick() {
                        salvarAnexo();
                    }

                    public void onNegativeClick() {

                    }
                }).show();
        break;
    }
    return true;
}

From source file:android.example.com.visualizerpreferences.VisualizerActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
        @NonNull int[] grantResults) {
    switch (requestCode) {
    case MY_PERMISSION_RECORD_AUDIO_REQUEST_CODE: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // The permission was granted! Start up the visualizer!
            mAudioInputReader = new AudioInputReader(mVisualizerView, this);

        } else {// w w  w.  j av a  2  s.c o m
            Toast.makeText(this, "Permission for audio not granted. Visualizer can't run.", Toast.LENGTH_LONG)
                    .show();
            finish();
            // The permission was denied, so we can show a message why we can't run the app
            // and then close the app.
        }
    }
    // Other permissions could go down here

    }
}