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

public void exportChat() {
    int permissionCheck = ContextCompat.checkSelfPermission(context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (ContextCompat.checkSelfPermission(context,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    } else {/* w  ww .ja  v  a2s . c  o m*/
        String filename = "FListLog-" + chatroomManager.getActiveChat().getName() + "-"
                + System.currentTimeMillis() + ".txt";
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File file = new File(path, filename);

        try {
            path.mkdirs();

            OutputStream os = new FileOutputStream(file);
            os.write(Exporter.exportText(this, chatroomManager.getActiveChat()));
            os.close();

            ChatEntry entry = entryFactory.getNotation(charManager.findCharacter(CharacterManager.USER_SYSTEM),
                    R.string.exported, new Object[] { filename });
            chatroomManager.addMessage(chatroomManager.getActiveChat(), entry);

            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {

                        }
                    });
        } catch (IOException e) {
            Ln.w("ExternalStorage", "Error writing " + file, e);
            ChatEntry entry = entryFactory.getError(charManager.findCharacter(CharacterManager.USER_SYSTEM),
                    R.string.export_failed);
            chatroomManager.addMessage(chatroomManager.getActiveChat(), entry);
        }
    }

}

From source file:ca.ualberta.cs.drivr.MainActivity.java

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.i(TAG, "permissions check");
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG, "permissions failed");
        /*// w  ww .  j ava  2s .  c om
        TODO: Consider calling
           ActivityCompat#requestPermissions
        here to request the missing permissions, and then overriding
          public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                             int[] grantResults)
        to handle the case where the user grants the permission. See the documentation
        for ActivityCompat#requestPermissions for more details.
        */
        String[] permissions = { Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE };
        ActivityCompat.requestPermissions(this, permissions, 1);
    }
    final LocationRequest locationRequest = new LocationRequest();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest,
            new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                    autocompleteFragment.setBoundsBias(new LatLngBounds(latLng, latLng));
                    Log.i(TAG, "updated the location bounds in listener" + latLng.toString());
                }
            });
}

From source file:bupt.tiantian.callrecorder.callrecorder.MainActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
    case 0x01: { // validateRequestPermissionsRequestCode in FragmentActivity requires requestCode to be of 8 bits, meaning the range is from 0 to 255.
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0) { // we only asked for one permission
            permissionReadContacts = grantResults[0] == PackageManager.PERMISSION_GRANTED;
        }//from  w w  w .j  a  v a  2s . co  m
        break;
    }
    case 0x02: { // validateRequestPermissionsRequestCode in FragmentActivity requires requestCode to be of 8 bits, meaning the range is from 0 to 255.
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0) { // we only asked for one permission
            permissionWriteExternal = grantResults[0] == PackageManager.PERMISSION_GRANTED;
        }
        break;
    }
    }
}

From source file:com.adflake.AdFlakeManager.java

/**
 * Gets the current location./*from w  ww  .  j  av  a  2 s.  c  o m*/
 * 
 * @note If location is not enabled, this method will return null
 * @return the current location or null if location access is not enabled or
 *         granted by the user.
 */
public Location getCurrentLocation() {
    if (_contextReference == null) {
        return null;
    }

    Context context = _contextReference.get();
    if (context == null) {
        return null;
    }

    Location location = null;

    if (context.checkCallingOrSelfPermission(
            android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    } else if (context.checkCallingOrSelfPermission(
            android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }
    return location;
}

From source file:ac.robinson.bettertogether.ConnectionSetupActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
        @NonNull int[] grantResults) {
    switch (requestCode) {
    case CAMERA_PERMISSION_RESULT:
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            restartCaptureManager();//  w  ww  .ja va 2  s.co  m
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(ConnectionSetupActivity.this);
            builder.setTitle(R.string.title_camera_access);
            builder.setMessage(R.string.hint_enable_camera_access);
            builder.setPositiveButton(R.string.hint_edit_permissions, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(
                            Uri.fromParts("package", ConnectionSetupActivity.this.getPackageName(), null));
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        // we've tried everything by this point!
                        Log.d(TAG,
                                "Camera permission denied and request failed - will not be able to scan codes");
                        Toast.makeText(ConnectionSetupActivity.this, R.string.error_accessing_camera,
                                Toast.LENGTH_LONG).show();
                    }
                    restartCaptureManager();
                }
            });
            builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(ConnectionSetupActivity.this, R.string.error_accessing_location,
                            Toast.LENGTH_LONG).show();
                    restartCaptureManager(); // reset capture UI and try again
                }
            });
            builder.show();
        }
        break;

    case COARSE_LOCATION_PERMISSION_RESULT:
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            createClient();
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(ConnectionSetupActivity.this);
            builder.setTitle(R.string.title_coarse_location_access);
            builder.setMessage(R.string.hint_enable_coarse_location_access);
            builder.setPositiveButton(R.string.hint_edit_permissions, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(
                            Uri.fromParts("package", ConnectionSetupActivity.this.getPackageName(), null));
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        // we've tried everything by this point!
                        Log.d(TAG,
                                "Coarse location permission denied and request failed - will not be able to connect");
                        Toast.makeText(ConnectionSetupActivity.this, R.string.error_accessing_location,
                                Toast.LENGTH_LONG).show();
                    }
                    restartCaptureManager();
                }
            });
            builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(ConnectionSetupActivity.this, R.string.error_accessing_location,
                            Toast.LENGTH_LONG).show();
                    restartCaptureManager(); // reset capture UI and try again
                }
            });
            builder.show();
        }
        break;

    default:
        if (mCaptureManager != null && requestCode == CaptureManager.getCameraPermissionReqCode()) {
            // ignored - CaptureManager's default is to exit on permission denial, so we handle permissions ourselves
            // mCaptureManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        break;
    }
}

From source file:com.seatgeek.placesautocompletedemo.MainFragment.java

@Override
public void onMapReady(GoogleMap googleMap) {

    if (ActivityCompat.checkSelfPermission(mapActivity,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(mapActivity,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;/*  ww w .  jav  a  2  s  .  c o m*/
    }

    try {
        // Customise the styling of the base map using a JSON object defined
        // in a raw resource file.
        boolean success = googleMap
                .setMapStyle(MapStyleOptions.loadRawResourceStyle(getContext(), R.raw.style_json));

        mMap = googleMap;
        mMap.setOnMarkerClickListener(this);

        mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addApi(Places.GEO_DATA_API)
                .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();

        setUpMapIfNeeded();

        mIsMapReady = true;

        prepareATMlist();

        if (!success) {
            Log.e("", "Style parsing failed.");
        }
    } catch (Resources.NotFoundException e) {
        Log.e("", "Can't find style. Error: ", e);
    }
    // Position the map's camera near Sydney, Australia.
    //        googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(-34, 151)));
}

From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.AnalyzeMyDriving.java

public void getLocation(final View view) {
    final FragmentActivity activity = getActivity();
    if (activity == null) {
        return;//  w  w  w . j av a 2s  .  c  o  m
    }
    if (ActivityCompat.checkSelfPermission(activity.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(activity.getApplicationContext(),
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    final Location location = locationManager.getLastKnownLocation(provider);
    onLocationChanged(location);
}

From source file:camera2basic.Camera2BasicFragment.java

/**
 * Opens the camera specified by {@link Camera2BasicFragment#mCameraId}.
 *//*from w w w .j a v a  2  s .c om*/
private void openCamera(int width, int height) {
    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        requestCameraPermission();
        return;
    }
    setUpCameraOutputs(width, height);
    configureTransform(width, height);
    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    }
}

From source file:com.aengbee.android.leanback.ui.VideoDetailsFragment.java

public void start(String company, String number, String duration) {
    if (ActivityCompat.checkSelfPermission(getActivity(),
            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.READ_EXTERNAL_STORAGE)
                || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            // Provide an additional rationale to the user if the permission was not granted
            // and the user would benefit from additional context for the use of the permission.
            // For example, if the request has been denied previously.

            Toast.makeText(getActivity(),
                    "we need read and write permission on external storage for downloading the videos and the mixing",
                    Toast.LENGTH_LONG).show();
        } else {/* ww  w.  j  av  a  2  s  .co m*/
            // Contact permissions have not been granted yet. Request them directly.
            ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE, 1);
        }

    } else {

        File tempaudio = new File(Environment.getExternalStorageDirectory().getPath() + "/"
                + Environment.DIRECTORY_MOVIES + "/temp.mp3");
        File templyrics = new File(Environment.getExternalStorageDirectory().getPath() + "/"
                + Environment.DIRECTORY_MOVIES + "/temp.ass");
        if (tempaudio.exists()) {
            tempaudio.delete();
        }

        if (templyrics.exists()) {
            templyrics.delete();
        }

        if (PreferenceManager.getDefaultSharedPreferences(getActivity())
                .getBoolean(getString(R.string.pref_key_USB), false) == true) {
            String storagePath = PreferenceManager.getDefaultSharedPreferences(getActivity())
                    .getString("USB_path", "null");
            File lyricsFrom = new File(
                    String.format(storagePath + "/%s/%s/%s.ass", company, number.substring(0, 2), number));
            File lyricsTo = new File(Environment.getExternalStorageDirectory().getPath() + "/"
                    + Environment.DIRECTORY_MOVIES + "/temp.ass");
            //Toast.makeText(getActivity(),lyricsFrom.toString()+lyricsFrom.exists(),Toast.LENGTH_LONG).show();
            File audioFrom = new File(
                    String.format(storagePath + "/%s/%s/%s.mp3", company, number.substring(0, 2), number));
            File audioTo = new File(Environment.getExternalStorageDirectory().getPath() + "/"
                    + Environment.DIRECTORY_MOVIES + "/temp.mp3");
            //Toast.makeText(getActivity(),audioFrom.toString()+lyricsFrom.exists(),Toast.LENGTH_LONG).show();
            try {
                Files.copy(lyricsFrom, lyricsTo);
                Files.copy(audioFrom, audioTo);
            } catch (IOException e) {
                e.printStackTrace();
            }
            File source = new File(Environment.getExternalStorageDirectory().getPath() + "/"
                    + Environment.DIRECTORY_MOVIES + "/source.mp4");
            if (!source.exists()) {
                File videoFrom = new File(String.format(storagePath + "/%s", "source.mp4"));
                File videoTo = new File(Environment.getExternalStorageDirectory().getPath() + "/"
                        + Environment.DIRECTORY_MOVIES + "/source.mp4");
                Toast.makeText(getActivity(), videoFrom.toString() + lyricsFrom.exists(), Toast.LENGTH_LONG)
                        .show();
                try {
                    Files.copy(videoFrom, videoTo);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } else {
            String downloadURL = String.format("http://fytoz.asuscomm.com/4TB/%s/%s/%s.mp3", company,
                    number.substring(0, 2), number);
            new DownloadTask(getActivity()).execute(
                    Environment.getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_MOVIES,
                    "temp.ass", downloadURL.replace(".mp3", ".ass"), "SearchFragment");
            new DownloadTask(getActivity()).execute(
                    Environment.getExternalStorageDirectory().getPath() + "/" + Environment.DIRECTORY_MOVIES,
                    "temp.mp3", downloadURL, "SearchFragment");

        }

        //Log.d("dxd", "start: "+downloadURL);

        String cmdFormat = "-i %s -i %s -c copy -map 0:v:0 -map 1:a:0 %s-y %s";
        //List<String> fileList = getListFiles(getExternalStoragePublicDirectory(DIRECTORY_MOVIES),"mp4");
        //List<String> fileList = getListFiles(new File(Environment.getExternalStorageDirectory().getPath()+"/"+Environment.DIRECTORY_MOVIES),"mp4");

        String filePath = chooseVideo(duration);
        int lengthofFile = filePath.contains("source.mp4") ? 900 : getDurationVideo(new File(filePath));

        //String joined = TextUtils.join(", ", fileList);
        //Toast.makeText(getActivity(), joined, Toast.LENGTH_SHORT).show();
        //Log.d("dxd", "start: "+duration+"|"+lengthofFile);
        String shortest = Integer.parseInt(duration) > lengthofFile ? "-shortest " : "-shortest ";
        //Toast.makeText(getActivity(), shortest+duration+"|"+lengthofFile, Toast.LENGTH_LONG).show();
        String audioPath = Environment.getExternalStorageDirectory().getPath() + "/"
                + Environment.DIRECTORY_MOVIES + "/temp.mp3";
        String cmd1 = String.format(cmdFormat, filePath, audioPath, shortest,
                Environment.getExternalStorageDirectory().getPath() + "/" + DIRECTORY_MOVIES + "/temp.mkv");

        String cmd2 = String.format(cmdFormat,
                PreferenceManager.getDefaultSharedPreferences(getActivity())
                        .getBoolean(getString(R.string.pref_key_USB), false)
                                ? Environment.getExternalStorageDirectory().getPath()
                                        + "/" + Environment.DIRECTORY_MOVIES + "/source.mp4"
                                : "http://fytoz.asuscomm.com/4TB/audio/source.mp4",
                audioPath, shortest,
                Environment.getExternalStorageDirectory().getPath() + "/" + DIRECTORY_MOVIES + "/temp.mkv");

        //Log.d("kkk:", Environment.getExternalStorageDirectory().getPath()+"/"+Environment.DIRECTORY_MOVIES);
        String[] command1 = cmd1.split(" ");
        String[] command2 = cmd2.split(" ");

        if (new File(filePath).exists() && tempaudio.exists() && templyrics.exists()) {
            //Toast.makeText(getActivity(), cmd1, Toast.LENGTH_LONG).show();
            ((VideoDetailsActivity) getActivity()).execFFmpegBinary(command1);
        } else {
            //Toast.makeText(getActivity(), cmd2, Toast.LENGTH_LONG).show();
            ((VideoDetailsActivity) getActivity()).execFFmpegBinary(command2);
        }
    }

}

From source file:co.carlosandresjimenez.android.gotit.BaseActivity.java

/**
 * Check if we have the GET_ACCOUNTS permission and request it if we do not.
 *
 * @return true if we have the permission, false if we do not.
 *//*  w  ww.  j a  va 2  s.  c o  m*/
private boolean checkAccountsPermission() {
    final String perm = Manifest.permission.GET_ACCOUNTS;
    int permissionCheck = ContextCompat.checkSelfPermission(this, perm);
    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
        // We have the permission
        return true;
    } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, perm)) {
        // Need to show permission rationale, display a snackbar and then request
        // the permission again when the snackbar is dismissed.
        Snackbar.make(findViewById(R.id.main_layout), R.string.contacts_permission_rationale,
                Snackbar.LENGTH_INDEFINITE).setAction(android.R.string.ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Request the permission again.
                        ActivityCompat.requestPermissions(BaseActivity.this, new String[] { perm },
                                RC_PERM_GET_ACCOUNTS);
                    }
                }).show();
        return false;
    } else {
        // No explanation needed, we can request the permission.
        ActivityCompat.requestPermissions(this, new String[] { perm }, RC_PERM_GET_ACCOUNTS);
        return false;
    }
}