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.andfchat.frontend.activities.ChatScreen.java

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
    case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Snackbar.make(this.findViewById(android.R.id.content), R.string.export_perm_granted,
                    Snackbar.LENGTH_LONG).show();

        } else {//  www  .java  2  s  .  com
            Snackbar.make(this.findViewById(android.R.id.content), R.string.export_perm_denied,
                    Snackbar.LENGTH_LONG).show();
        }
        return;
    }
    }
}

From source file:github.popeen.dsub.activity.SubsonicActivity.java

@Override
protected void onCreate(Bundle bundle) {

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL);

    UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE);
    if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) {
        // tv = true;
    }// w  w  w.  ja  v  a2  s.c o m
    PackageManager pm = getPackageManager();
    if (!pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)) {
        touchscreen = false;
    }

    setUncaughtExceptionHandler();
    applyTheme();
    applyFullscreen();
    super.onCreate(bundle);
    startService(new Intent(this, DownloadService.class));
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    if (getIntent().hasExtra(Constants.FRAGMENT_POSITION)) {
        lastSelectedPosition = getIntent().getIntExtra(Constants.FRAGMENT_POSITION, 0);
    }

    if (preferencesListener == null) {
        preferencesListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                // When changing drawer settings change visibility
                switch (key) {
                case Constants.PREFERENCES_KEY_PODCASTS_ENABLED:
                    setDrawerItemVisible(R.id.drawer_podcasts, false);
                    break;
                case Constants.PREFERENCES_KEY_BOOKMARKS_ENABLED:
                    setDrawerItemVisible(R.id.drawer_bookmarks, false);
                    break;
                case Constants.PREFERENCES_KEY_INTERNET_RADIO_ENABLED:
                    setDrawerItemVisible(R.id.drawer_internet_radio_stations, false);
                    break;
                case Constants.PREFERENCES_KEY_SHARED_ENABLED:
                    setDrawerItemVisible(R.id.drawer_shares, false);
                    break;
                case Constants.PREFERENCES_KEY_CHAT_ENABLED:
                    setDrawerItemVisible(R.id.drawer_chat, false);
                    break;
                case Constants.PREFERENCES_KEY_ADMIN_ENABLED:
                    setDrawerItemVisible(R.id.drawer_admin, false);
                    break;
                }
            }
        };
        Util.getPreferences(this).registerOnSharedPreferenceChangeListener(preferencesListener);
    }

    if (ContextCompat.checkSelfPermission(this,
            permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { permission.WRITE_EXTERNAL_STORAGE },
                PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    }
}

From source file:br.com.anteros.vendas.gui.ManutencaoTabelasActivity.java

private void importarBancoDeDados() {
    new QuestionAlert(this, "Manuteno Tabelas", "Importar banco de dados ?",
            new QuestionAlert.QuestionListener() {

                public void onPositiveClick() {

                    if (ActivityCompat.checkSelfPermission(ManutencaoTabelasActivity.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                            || ActivityCompat.checkSelfPermission(ManutencaoTabelasActivity.this,
                                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat/*from  w  w  w . j a  v a 2 s  .  co  m*/
                                .requestPermissions(ManutencaoTabelasActivity.this,
                                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                Manifest.permission.READ_EXTERNAL_STORAGE },
                                        REQUEST_PERMISSION_IMPORT);
                    } else {
                        executarImportacaoBancoDados();
                    }
                }

                public void onNegativeClick() {
                }
            }).show();
}

From source file:br.com.anteros.vendas.gui.AnexoCadastroActivity.java

/**
 * Evento long click para iniciar captura de imagem da cmera. No foi usado onClick pois j foi
 * usado na imagem de visualizar para ver o anexo.
 * @param v View/*w  w w.j  a  v a2 s .c  o  m*/
 * @return True se executou
 */
@Override
public boolean onLongClick(View v) {
    /**
     * 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();
    }
    return false;
}

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

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
    case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            // permission was granted, yay! Do the
            // contacts-related task you need to do.

        } else {/*from w ww  .  j  a  v  a2  s. c o  m*/

            // permission denied, boo! Disable the
            // functionality that depends on this permission.
        }
        return;
    }

    // other 'case' lines to check for other
    // permissions this app might request
    }
}

From source file:com.android.browser.BrowserActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
    case PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
        // If request is cancelled, the result array is empty
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            DownloadHandler.checkPendingDownloads(this);
        } else {/*w w  w  .j  a v a2s.com*/
            new AlertDialog.Builder(this).setTitle(R.string.permission_not_granted_dialog_title)
                    .setMessage(R.string.permission_not_granted_dialog_message)
                    .setPositiveButton(android.R.string.ok, null).show();
        }
        break;
    }
}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

public void loadInitialUnitUsage() {
    final SQLiteDatabase db = getWritableDatabase();
    // load the initial table in
    final ContentValues cv = new ContentValues();

    Log.d(TAG, "init all weights hash");
    final HashMap<String, Integer> allUnitWeights = new HashMap<String, Integer>(Unit.table.keySet().size());
    Log.d(TAG, "adding all known weights...");
    for (final String unitName : Unit.table.keySet()) {
        // don't add all uppercase names
        if (!unitName.toUpperCase().equals(unitName)) {
            allUnitWeights.put(unitName, 0);
        }/*from w  w w .  j a v a  2  s . c o m*/
    }
    Log.d(TAG, "adding all known functions...");
    for (final String functionName : BuiltInFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    //      for (final String functionName: TabularFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    //      for (final String functionName: ComputedFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    for (final String functionName : DefinedFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    Log.d(TAG, "adding common weights");
    addAll(loadInitialWeights(R.raw.common_weights), allUnitWeights);
    Log.d(TAG, "adding regional weights");
    addAll(loadInitialWeights(R.raw.regional_weights), allUnitWeights);

    // This is so that things of common weight end up in non-random order
    // without having to do an SQL order-by.
    final ArrayList<String> sortedUnits = new ArrayList<String>(allUnitWeights.keySet());
    Log.d(TAG, "Sorting units...");
    Collections.sort(sortedUnits);
    Log.d(TAG, "Adding all sorted units...");

    final HashMap<String, String> fingerprints = loadFingerprints();

    db.beginTransaction();
    for (final String unitName : sortedUnits) {
        cv.put(UsageEntry._UNIT, unitName);
        cv.put(UsageEntry._USE_COUNT, allUnitWeights.get(unitName));

        final String fpr = fingerprints.containsKey(unitName) ? fingerprints.get(unitName)
                : getFingerprint(unitName);

        fingerprints.put(unitName, fpr);
        cv.put(UsageEntry._FACTOR_FPRINT, fpr);
        db.insert(DB_USAGE_TABLE, null, cv);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();

    context.getContentResolver().notifyChange(UsageEntry.CONTENT_URI, null);

    // If we have the right permissons, save the fingerprints file to a JSON file
    // which can then be imported into the app to speed up initial fingerpint loading.
    if (context.checkCallingOrSelfPermission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        final File externalStorage = Environment.getExternalStorageDirectory();
        final File fprintsOutput = new File(externalStorage, "units_fingerprints.json");
        final JSONObject jo = new JSONObject(fingerprints);
        try {
            final FileWriter fw = new FileWriter(fprintsOutput);
            fw.write(jo.toString(1));
            fw.close();
            Log.i(TAG, "fingerprints written to: " + fprintsOutput.getCanonicalPath());

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    Log.d(TAG, "done!");
}

From source file:com.almunt.jgcaap.systemupdater.MainActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        refreshLayout.setRefreshing(true);
        final GetLinks g = new GetLinks();
        RefreshLinks2(g);/*from   w w w  . jav  a  2  s  .c  o m*/
        refreshLayout.setRefreshing(false);
    } else {
        AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
        builder1.setTitle("This app needs the storage permission to download and view jgcaap rom updates");
        builder1.setMessage(
                "Tap \"Request Permission\" to try requesting the permission again or close the app");
        builder1.setCancelable(false);
        builder1.setPositiveButton("Request Permission", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
            }
        });
        builder1.setNegativeButton("Close App", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                finish();
            }
        });
        AlertDialog alert11 = builder1.create();
        alert11.show();
    }
}

From source file:ca.frozen.rpicameraviewer.activities.VideoFragment.java

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if (requestCode == REQUEST_WRITE_EXTERNAL_STORAGE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            takeSnapshot();//from   www.j a  va 2s .  c  o  m
        }
    }
}

From source file:com.affectiva.affdexme.MainActivity.java

private void checkForStoragePermissions() {
    storagePermissionsAvailable = ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;

    if (!storagePermissionsAvailable) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            // Show an explanation 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.
            showPermissionExplanationDialog(EXTERNAL_STORAGE_PERMISSIONS_REQUEST);
        } else {//  ww  w.  j  a  v a2  s.  co m
            // No explanation needed, we can request the permission.
            requestStoragePermissions();
        }
    } else {
        takeScreenshot(screenshotButton);
    }
}