Example usage for android.content.pm PackageManager PERMISSION_DENIED

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

Introduction

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

Prototype

int PERMISSION_DENIED

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

Click Source Link

Document

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

Usage

From source file:com.microsoft.projectoxford.emotionsample.RecognizeActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    if (requestCode == REQUEST_CAMERA_PERMISSION) {
        if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            // close the app
            Toast.makeText(RecognizeActivity.this,
                    "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
            finish();//from  w  ww .j a  v  a2s .  co  m
        }
    }
}

From source file:opensource.zeocompanion.ZeoCompanionApplication.java

public static int checkExternalStorage() {
    // does App still have permission to write to external storage?
    int permissionCheck = ContextCompat.checkSelfPermission(mOurContext,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck == PackageManager.PERMISSION_DENIED) {
        return -2;
    } // nope/*from   w  w  w .  ja  v a  2s . c om*/

    // is external storage is available and read-write?
    String state = Environment.getExternalStorageState();
    if (!state.equals(Environment.MEDIA_MOUNTED)) {
        return -1;
    } // not mounted or is MEDIA_MOUNTED_READ_ONLY or is in some other non-usable condition
    return 0;
}

From source file:com.att.arocollector.AROCollectorActivity.java

private boolean checkWritePerm() {
    Context context = getApplicationContext();
    int permissionCheck = ContextCompat.checkSelfPermission(context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permissionCheck == PackageManager.PERMISSION_DENIED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
        permissionCheck = ContextCompat.checkSelfPermission(context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck == PackageManager.PERMISSION_DENIED) {
            return false;
        } else {/*from   ww w .  j  a  v a  2  s . c o  m*/
            return true;
        }
    } else {
        return true;
    }
}

From source file:org.awesomeapp.messenger.ui.ConversationDetailActivity.java

public void startAudioRecording() {
    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);

    if (permissionCheck == PackageManager.PERMISSION_DENIED) {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {

            // 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.
            Snackbar.make(mConvoView.getHistoryView(), R.string.grant_perms, Snackbar.LENGTH_LONG).show();
        } else {/*w ww . j a  v  a  2s .c om*/

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.RECORD_AUDIO },
                    MY_PERMISSIONS_REQUEST_AUDIO);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    } else {
        mMediaRecorder = new MediaRecorder();

        String fileName = UUID.randomUUID().toString().substring(0, 8) + ".m4a";
        mAudioFilePath = new File(getFilesDir(), fileName);

        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

        //maybe we can modify these in the future, or allow people to tweak them
        mMediaRecorder.setAudioChannels(1);
        mMediaRecorder.setAudioEncodingBitRate(22050);
        mMediaRecorder.setAudioSamplingRate(64000);
        mMediaRecorder.setOutputFile(mAudioFilePath.getAbsolutePath());

        try {
            mIsAudioRecording = true;
            mMediaRecorder.prepare();
            mMediaRecorder.start();
        } catch (Exception e) {
            Log.e(ImApp.LOG_TAG, "couldn't start audio", e);
        }
    }
}

From source file:com.just.agentweb.AgentWebUtils.java

public static boolean hasPermission(@NonNull Context context, @NonNull List<String> permissions) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }//w  w  w . j a  v  a  2  s  . c  o m
    for (String permission : permissions) {
        int result = ContextCompat.checkSelfPermission(context, permission);
        if (result == PackageManager.PERMISSION_DENIED) {
            return false;
        }

        String op = AppOpsManagerCompat.permissionToOp(permission);
        if (TextUtils.isEmpty(op)) {
            continue;
        }
        result = AppOpsManagerCompat.noteProxyOp(context, op, context.getPackageName());
        if (result != AppOpsManagerCompat.MODE_ALLOWED) {
            return false;
        }

    }
    return true;
}

From source file:cordova.plugins.Diagnostic.java

/**
 * Callback received when a runtime permissions request has been completed.
 * Retrieves the stateful Cordova context and permission statuses associated with the requestId,
 * then updates the list of status based on the grantResults before passing the result back via the context.
 *
 * @param requestCode - ID that was used when requesting permissions
 * @param permissions - list of permissions that were requested
 * @param grantResults - list of flags indicating if above permissions were granted or denied
 *///w ww .j av a 2s .  com
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults)
        throws JSONException {
    String sRequestId = String.valueOf(requestCode);
    Log.v(TAG, "Received result for permissions request id=" + sRequestId);
    try {

        if (!callbackContexts.containsKey(sRequestId)) {
            handleError("No context found for request id=" + sRequestId, requestCode);
            return;
        }

        CallbackContext context = callbackContexts.get(sRequestId);
        JSONObject statuses = permissionStatuses.get(sRequestId);

        for (int i = 0, len = permissions.length; i < len; i++) {
            String androidPermission = permissions[i];
            String permission = permissionsMap.get(androidPermission);
            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                boolean showRationale = shouldShowRequestPermissionRationale(this.cordova.getActivity(),
                        androidPermission);
                if (!showRationale) {
                    // EITHER: The app doesn't have a permission and the user has not been asked for the permission before
                    // OR: user denied WITH "never ask again"
                    statuses.put(permission, Diagnostic.STATUS_NOT_REQUESTED_OR_DENIED_ALWAYS);
                } else {
                    // user denied WITHOUT "never ask again"
                    statuses.put(permission, Diagnostic.STATUS_DENIED);
                }
            } else {
                // Permission granted
                statuses.put(permission, Diagnostic.STATUS_GRANTED);
            }
            Log.v(TAG, "Authorisation for " + permission + " is " + statuses.get(permission));
        }
        context.success(statuses);
        clearRequest(requestCode);
    } catch (Exception e) {
        handleError("Exception occurred onRequestPermissionsResult: ".concat(e.getMessage()), requestCode);
    }
}

From source file:com.tenforwardconsulting.cordova.BackgroundGeolocationPlugin.java

public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults)
        throws JSONException {
    for (int r : grantResults) {
        if (r == PackageManager.PERMISSION_DENIED) {
            log.info("Permission Denied!");
            actionStartCallbackContext.error(
                    JSONErrorFactory.getJSONError(PERMISSION_DENIED_ERROR_CODE, "Permission denied by user"));
            actionStartCallbackContext = null;
            return;
        }//from w ww  . j  a v a 2  s  .co  m
    }
    switch (requestCode) {
    case START_REQ_CODE:
        startAndBindBackgroundService();
        actionStartCallbackContext.success();
        actionStartCallbackContext = null;
        break;
    }
}

From source file:locationkitapp.locationkit.locationkitapp.MapsActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    if (requestCode == 100) {
        boolean granted = true;
        for (int i : grantResults) {
            if (i == PackageManager.PERMISSION_DENIED) {
                granted = false;//  w w  w .j  a v a  2s. co m
            }
        }
        if (!granted) {
            Snackbar.make(mLayout, "Location permission request was denied.", Snackbar.LENGTH_SHORT).show();
            Log.e(LOG_TAG, "Permission was denied");
        } else {
            mMap.setMyLocationEnabled(true);
        }
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults)
        throws JSONException {
    for (int r : grantResults) {
        if (r == PackageManager.PERMISSION_DENIED) {
            int errorCode = BackgroundGeolocationService.LOCATION_ERROR_DENIED;
            PluginResult result = new PluginResult(PluginResult.Status.ERROR, errorCode);
            if (requestCode == REQUEST_ACTION_START) {
                if (startCallback != null) {
                    startCallback.sendPluginResult(result);
                    startCallback = null;
                }/*from  w  ww . j  a  v a 2  s  . co  m*/
            } else if (requestCode == REQUEST_ACTION_GET_CURRENT_POSITION) {
                Bundle event = new Bundle();
                event.putString("name", BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION);
                event.putInt("code", errorCode);
                onLocationError(event);
            }
            return;
        }
    }
    switch (requestCode) {
    case REQUEST_ACTION_START:
        setEnabled(true);
        break;
    case REQUEST_ACTION_GET_CURRENT_POSITION:
        startService(requestCode);
        break;
    }
}

From source file:fi.vtt.moodtracker.ClimbTrackerActivity.java

/**
               * Once a user is logged in, take the mAuthData provided from Firebase and "use" it.
               *//*
                  private void setAuthenticatedUser(AuthData authData) {
                  this.mAuthData = authData;
                  }//from   ww w  .  ja v  a  2 s  . c  o m
                          
                  public void onConnectionFailed(ConnectionResult result) {
                  if (!mIntentInProgress && result.hasResolution()) {
                      try {
                          mIntentInProgress = true;
                          startIntentSenderForResult(result.getResolution().getIntentSender(), RC_SIGN_IN, null, 0, 0, 0);
                      } catch (IntentSender.SendIntentException e) {
                          // The intent was canceled before it was sent.  Return to the default
                          // state and attempt to connect to get an updated ConnectionResult.
                          mIntentInProgress = false;
                          mGoogleAuthApiClient.connect();
                      }
                  }
                  }
                          
                  protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
                  if (requestCode == RC_SIGN_IN) {
                      mIntentInProgress = false;
                      if (!mGoogleAuthApiClient.isConnecting()) {
                          mGoogleAuthApiClient.connect();
                      }
                  }
                  }
                          
                  private void getGoogleOAuthTokenAndLogin() {
                  */
/* Get OAuth token in Background *//*
                                   AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
                                   String errorMessage = null;
                                           
                                   @Override
                                   protected String doInBackground(Void... params) {
                                   String token = null;
                                           
                                   try {
                                   String scope = String.format("oauth2:%s", Scopes.PROFILE);
                                   token = GoogleAuthUtil.getToken(ClimbTrackerActivity.this, Plus.AccountApi.getAccountName(mGoogleAuthApiClient), scope);
                                   } catch (IOException transientEx) {
                                   *//* Network or server error *//*
                                                                   Log.e(LOG_TAG, "Error authenticating with Google: " + transientEx);
                                                                   errorMessage = "Network error: " + transientEx.getMessage();
                                                                   } catch (UserRecoverableAuthException e) {
                                                                   Log.w(LOG_TAG, "Recoverable Google OAuth error: " + e.toString());
                                                                   *//* We probably need to ask for permissions, so start the intent if there is none pending *//*
                                                                                                                                                                 mGoogleAuthApiClient.connect();
                                                                                                                                                                 } catch (GoogleAuthException authEx) {
                                                                                                                                                                 *//* The call is not ever expected to succeed assuming you have already verified that
                                                                                                                                                                    * Google Play services is installed. *//*
                                                                                                                                                                                                            Log.e(LOG_TAG, "Error authenticating with Google: " + authEx.getMessage(), authEx);
                                                                                                                                                                                                            errorMessage = "Error authenticating with Google: " + authEx.getMessage();
                                                                                                                                                                                                            }
                                                                                                                                                                                                                    
                                                                                                                                                                                                            return token;
                                                                                                                                                                                                            }
                                                                                                                                                                                                                    
                                                                                                                                                                                                            @Override
                                                                                                                                                                                                            protected void onPostExecute(String token) {
                                                                                                                                                                                                            // Authenticate
                                                                                                                                                                                                            // see https://www.firebase.com/docs/android/guide/login/google.html
                                                                                                                                                                                                            mFirebaseRef.authWithOAuthToken("google", token, new Firebase.AuthResultHandler() {
                                                                                                                                                                                                            @Override
                                                                                                                                                                                                            public void onAuthenticated(AuthData authData) {
                                                                                                                                                                                                            // the Google user is now authenticated with Firebase
                                                                                                                                                                                                            setAuthenticatedUser(authData);
                                                                                                                                                                                                            }
                                                                                                                                                                                                                    
                                                                                                                                                                                                            @Override
                                                                                                                                                                                                            public void onAuthenticationError(FirebaseError firebaseError) {
                                                                                                                                                                                                            Toast.makeText(ClimbTrackerActivity.this, firebaseError.getMessage(), Toast.LENGTH_LONG).show();
                                                                                                                                                                                                            }
                                                                                                                                                                                                            });
                                                                                                                                                                                                            }
                                                                                                                                                                                                            };
                                                                                                                                                                                                            task.execute();
                                                                                                                                                                                                            }
                                                                                                                                                                                                                    
                                                                                                                                                                                                            public void onConnected(Bundle connectionHint) {
                                                                                                                                                                                                            getGoogleOAuthTokenAndLogin();
                                                                                                                                                                                                            }
                                                                                                                                                                                                                    
                                                                                                                                                                                                            public void onConnectionSuspended(int cause) {
                                                                                                                                                                                                            mGoogleAuthApiClient.connect();
                                                                                                                                                                                                            }*/

/*    /**
     * Callback method from {@link ClimbSessionListFragment.Callbacks}
     * indicating that the item was selected.
     */
/*    @Override
    public void onItemSelected(ClimbSession session) {
if (mTwoPane) {
    // In two-pane mode, show the detail view in this activity by
    // adding or replacing the detail fragment using a
    // fragment transaction.
    Bundle arguments = new Bundle();
    arguments.putLong(ClimbSessionDetailFragment.ARG_FIRST_CLIMB_TIME, session.getFirstClimbDate().getTime());
    arguments.putLong(ClimbSessionDetailFragment.ARG_LAST_CLIMB_TIME, session.getLastClimbDate().getTime());
    ClimbSessionDetailFragment fragment = new ClimbSessionDetailFragment();
    fragment.setArguments(arguments);
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.climbsession_detail_container, fragment)
            .commit();
        
} else {
    // In single-pane mode, simply start the detail activity
    // for the selected item ID.
    Intent detailIntent = new Intent(this, ClimbSessionDetailActivity.class);
    detailIntent.putExtra(ClimbSessionDetailFragment.ARG_FIRST_CLIMB_TIME, session.getFirstClimbDate().getTime());
    detailIntent.putExtra(ClimbSessionDetailFragment.ARG_LAST_CLIMB_TIME, session.getLastClimbDate().getTime());
    startActivity(detailIntent);
}
    }*/

/*    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(Path.PREF_GRAD_SYSTEM_TYPE)) {
*//*            mTracker.send(new HitBuilders.EventBuilder()
               .setCategory("settings")
               .setAction("changed-system")
               .build());*//*
                                    
                            String gradeSystemTypePref = sharedPreferences.getString(Path.PREF_GRAD_SYSTEM_TYPE, GradeList.SYSTEM_DEFAULT);
                            sendGradeSystemToWear(gradeSystemTypePref);
                            }
                            }*/

/*    @Override
    public void onGradeSelected(String grade) {
*//*        mTracker.send(new HitBuilders.EventBuilder()
           .setCategory("action")
           .setAction("save-climb")
           .build());*//*
                                
                        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
                        String gradeSystemType = sharedPref.getString(Path.PREF_GRAD_SYSTEM_TYPE, GradeList.SYSTEM_DEFAULT);
                                
                        double latitude = 0;
                        double longitude = 0;
                                
                        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                        if(lastLocation != null) {
                        latitude = lastLocation.getLatitude();
                        longitude = lastLocation.getLongitude();
                        }
                        }
                                
                        Climb newClimb = new Climb(new Date(), grade, gradeSystemType, latitude, longitude);
                        mNewClimbRef = mFirebaseRef.child("users")
                        .child(mAuthData.getUid())
                        .child("climbs")
                        .push();
                        mNewClimbRef.setValue(newClimb);
                                
                        final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.mainLayout);
                        Snackbar.make(coordinatorLayout, R.string.climb_confirmation, Snackbar.LENGTH_LONG).setAction(R.string.climb_save_undo, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        mNewClimbRef.removeValue();
                        }
                        }).show();
                        }*/

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
    case PERMISSION_UPFRONT_REQUEST: {
        // first check if we can login
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) {

            // if we can, check if we can see the location, if not, display a message.
            for (int i = 0; i < grantResults.length; i++) {
                if (permissions[i].equals(Manifest.permission.ACCESS_COARSE_LOCATION)
                        && grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    // no problem, just say we are not going to store location
                    final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(
                            R.id.mainLayout);
                    Snackbar.make(coordinatorLayout, R.string.location_permission_denied, Snackbar.LENGTH_LONG)
                            .show();
                }
            }
            //                    mGoogleAuthApiClient.connect();
        } else {
            // We need this permission to log in, explain and ask again
            final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.mainLayout);
            Snackbar.make(coordinatorLayout, R.string.account_permission_denied, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // Request the permission again.
                            ActivityCompat.requestPermissions(ClimbTrackerActivity.this,
                                    new String[] { Manifest.permission.GET_ACCOUNTS },
                                    PERMISSION_UPFRONT_REQUEST);
                        }
                    }).show();
        }
    }

    }
}