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:co.taqat.call.LinphoneActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    //This must be done before calling super.onCreate().
    super.onCreate(savedInstanceState);

    if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }//  ww w  .  j  a  va  2  s  .co  m

    boolean useFirstLoginActivity = getResources().getBoolean(R.bool.display_account_assistant_at_first_start);
    if (LinphonePreferences.instance().isProvisioningLoginViewEnabled()) {
        Intent wizard = new Intent();
        wizard.setClass(this, RemoteProvisioningLoginActivity.class);
        wizard.putExtra("Domain", LinphoneManager.getInstance().wizardLoginViewDomain);
        startActivity(wizard);
        finish();
        return;
    } else if (savedInstanceState == null
            && (useFirstLoginActivity && LinphonePreferences.instance().isFirstLaunch())) {
        if (LinphonePreferences.instance().getAccountCount() > 0) {
            LinphonePreferences.instance().firstLaunchSuccessful();
        } else {
            startActivity(new Intent().setClass(this, AssistantActivity.class));
            finish();
            return;
        }
    }

    if (getIntent() != null && getIntent().getExtras() != null) {
        newProxyConfig = getIntent().getExtras().getBoolean("isNewProxyConfig");
    }

    if (getResources().getBoolean(R.bool.use_linphone_tag)) {
        if (getPackageManager().checkPermission(Manifest.permission.WRITE_SYNC_SETTINGS,
                getPackageName()) != PackageManager.PERMISSION_GRANTED) {
            checkSyncPermission();
        } else {
            ContactsManager.getInstance().initializeSyncAccount(getApplicationContext(), getContentResolver());
        }
    } else {
        ContactsManager.getInstance().initializeContactManager(getApplicationContext(), getContentResolver());
    }

    setContentView(R.layout.main);
    instance = this;
    fragmentsHistory = new ArrayList<FragmentsAvailable>();
    pendingFragmentTransaction = FragmentsAvailable.UNKNOW;

    initButtons();
    initSideMenu();

    currentFragment = FragmentsAvailable.EMPTY;
    if (savedInstanceState == null) {
        changeCurrentFragment(FragmentsAvailable.DIALER, getIntent().getExtras());
    } else {
        currentFragment = (FragmentsAvailable) savedInstanceState.getSerializable("currentFragment");
    }

    mListener = new LinphoneCoreListenerBase() {
        @Override
        public void messageReceived(LinphoneCore lc, LinphoneChatRoom cr, LinphoneChatMessage message) {
            displayMissedChats(getUnreadMessageCount());
        }

        @Override
        public void registrationState(LinphoneCore lc, LinphoneProxyConfig proxy,
                LinphoneCore.RegistrationState state, String smessage) {
            if (state.equals(RegistrationState.RegistrationCleared)) {
                if (lc != null) {
                    LinphoneAuthInfo authInfo = lc.findAuthInfo(proxy.getIdentity(), proxy.getRealm(),
                            proxy.getDomain());
                    if (authInfo != null)
                        lc.removeAuthInfo(authInfo);
                }
            }

            refreshAccounts();

            if (getResources().getBoolean(R.bool.use_phone_number_validation)) {
                if (state.equals(RegistrationState.RegistrationOk)) {
                    LinphoneManager.getInstance().isAccountWithAlias();
                }
            }

            if (state.equals(RegistrationState.RegistrationFailed) && newProxyConfig) {
                newProxyConfig = false;
                if (proxy.getError() == Reason.BadCredentials) {
                    //displayCustomToast(getString(R.string.error_bad_credentials), Toast.LENGTH_LONG);
                }
                if (proxy.getError() == Reason.Unauthorized) {
                    displayCustomToast(getString(R.string.error_unauthorized), Toast.LENGTH_LONG);
                }
                if (proxy.getError() == Reason.IOError) {
                    displayCustomToast(getString(R.string.error_io_error), Toast.LENGTH_LONG);
                }
            }
        }

        @Override
        public void callState(LinphoneCore lc, LinphoneCall call, LinphoneCall.State state, String message) {
            if (state == State.IncomingReceived) {
                startActivity(new Intent(LinphoneActivity.instance(), CallIncomingActivity.class));
            } else if (state == State.OutgoingInit || state == State.OutgoingProgress) {
                startActivity(new Intent(LinphoneActivity.instance(), CallOutgoingActivity.class));
            } else if (state == State.CallEnd || state == State.Error || state == State.CallReleased) {
                resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
            }

            int missedCalls = LinphoneManager.getLc().getMissedCallsCount();
            displayMissedCalls(missedCalls);
        }
    };

    int missedCalls = LinphoneManager.getLc().getMissedCallsCount();
    displayMissedCalls(missedCalls);

    int rotation = getWindowManager().getDefaultDisplay().getRotation();
    switch (rotation) {
    case Surface.ROTATION_0:
        rotation = 0;
        break;
    case Surface.ROTATION_90:
        rotation = 90;
        break;
    case Surface.ROTATION_180:
        rotation = 180;
        break;
    case Surface.ROTATION_270:
        rotation = 270;
        break;
    }

    LinphoneManager.getLc().setDeviceRotation(rotation);
    mAlwaysChangingPhoneAngle = rotation;
}

From source file:app.axe.imooc.zxing.app.CaptureActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == MY_PERMISSIONS_REQUEST_CAMERA) {
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //?//from  w  w  w .ja v a2 s  . c o  m
        } else {
            initCamera(surfaceHolder);
        }
    } else if (requestCode == MY_PERMISSIONS_REQUEST_XIANGCE) {
        if (ContextCompat.checkSelfPermission(CaptureActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        } else {
            // 
            Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
            innerIntent.setType("image/*");
            Intent wrapperIntent = Intent.createChooser(innerIntent, "?");
            startActivityForResult(wrapperIntent, REQUEST_CODE);
        }
    }
}

From source file:com.mobantica.DriverItRide.activities.ActivityLogin.java

private boolean valid() {
    if (edt_login_username.getText().toString().equals("")) {
        Toast.makeText(getApplicationContext(), getResources().getString(R.string.please_enter_username),
                Toast.LENGTH_SHORT).show();
        return false;
    }//from   www  . j  a v  a  2s  .c  om

    if (edt_login_password.getText().toString().equals("")) {
        Toast.makeText(getApplicationContext(), getResources().getString(R.string.please_enter_password),
                Toast.LENGTH_SHORT).show();
        return false;
    }

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, getResources().getString(R.string.need_location_permission_in_app_setting),
                Toast.LENGTH_SHORT).show();
        return false;
    }

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, getResources().getString(R.string.need_phone_permission_in_app_setting),
                Toast.LENGTH_SHORT).show();
        return false;
    }

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this,
                getResources().getString(R.string.need_write_external_storage_permissionin_app_setting),
                Toast.LENGTH_SHORT).show();
        return false;
    }

    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        Toast.makeText(getApplicationContext(), getResources().getString(R.string.please_enable_location),
                Toast.LENGTH_SHORT).show();
        return false;
    }

    return true;
}

From source file:android.melbournehistorymap.MapsActivity.java

/**
 * Manipulates the map once available.//from  w w w . j a va 2s.c om
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    spinner = (ProgressBar) findViewById(R.id.prograssSpinner);
    //check if permission has been granted
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Permission has already been granted
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(false);

    double lat;
    double lng;
    final int radius;
    int zoom;

    lat = Double.parseDouble(CurrLat);
    lng = Double.parseDouble(CurrLong);

    //build current location
    LatLng currentLocation = new LatLng(lat, lng);
    final LatLng realLocation = currentLocation;

    if (MELBOURNE.contains(currentLocation)) {
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        zoom = 17;
    } else {
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        lat = -37.81161508043379;
        lng = 144.9647320434451;
        zoom = 15;
        currentLocation = new LatLng(lat, lng);
    }

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 13));

    CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation) // Sets the center of the map to location user
            .zoom(zoom) // Sets the zoom
            .bearing(0) // Sets the orientation of the camera to east
            .tilt(25) // Sets the tilt of the camera to 30 degrees
            .build(); // Creates a CameraPosition from the builder

    //Animate user to map location, if in Melbourne or outside of Melbourne bounds
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
            new GoogleMap.CancelableCallback() {
                @Override
                public void onFinish() {
                    updateMap();
                }

                @Override
                public void onCancel() {

                }
            });

    final TextView placeTitle = (TextView) findViewById(R.id.placeTitle);
    final TextView placeVic = (TextView) findViewById(R.id.placeVic);
    final TextView expPlaceTitle = (TextView) findViewById(R.id.expPlaceTitle);
    final TextView expPlaceVic = (TextView) findViewById(R.id.expPlaceVic);
    final TextView expPlaceDescription = (TextView) findViewById(R.id.placeDescription);
    final TextView wikiLicense = (TextView) findViewById(R.id.wikiLicense);
    final TextView expPlaceDistance = (TextView) findViewById(R.id.expPlaceDistance);
    final RelativeLayout tile = (RelativeLayout) findViewById(R.id.tile);
    final TextView fab = (TextView) findViewById(R.id.fab);
    final RelativeLayout distanceCont = (RelativeLayout) findViewById(R.id.distanceContainer);

    //        String license = "Text is available under the <a rel=\"license\" href=\"//en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\">Creative Commons Attribution-ShareAlike License</a><a rel=\"license\" href=\"//creativecommons.org/licenses/by-sa/3.0/\" style=\"display:none;\"></a>;\n" +
    //                "additional terms may apply.";
    //        wikiLicense.setText(Html.fromHtml(license));
    //        wikiLicense.setMovementMethod(LinkMovementMethod.getInstance());
    //Marker click
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(Marker marker) {
            String title = marker.getTitle();
            mMap.setPadding(0, 0, 0, 620);
            //set clicked marker to full opacity
            marker.setAlpha(1f);
            //set previous marker back to partial opac (if there is a prevMarker
            if (dirtyMarker == 1) {
                prevMarker.setAlpha(0.6f);
            }
            prevMarker = marker;
            dirtyMarker = 1;

            //Set DB helper
            DBHelper myDBHelper = new DBHelper(MapsActivity.this, WikiAPI.DB_NAME, null, WikiAPI.VERSION);

            //Only search for Wiki API requests if no place article returned.
            // **
            //Open DB as readable only.
            SQLiteDatabase db = myDBHelper.getReadableDatabase();
            //Set the query
            String dbFriendlyName = title.replace("\'", "\'\'");
            //Limit by 1 rows
            Cursor cursor = db.query(DBHelper.TABLE_NAME, null, "PLACE_NAME = '" + dbFriendlyName + "'", null,
                    null, null, null, "1");

            //move through each row returned in the query results
            while (cursor.moveToNext()) {

                String place_ID = cursor.getString(cursor.getColumnIndex("PLACE_ID"));
                String placeName = cursor.getString(cursor.getColumnIndex("PLACE_NAME"));
                String placeLoc = cursor.getString(cursor.getColumnIndex("PLACE_LOCATION"));
                String placeArticle = cursor.getString(cursor.getColumnIndex("ARTICLE"));
                String placeLat = cursor.getString(cursor.getColumnIndex("LAT"));
                String placeLng = cursor.getString(cursor.getColumnIndex("LNG"));

                //Get Google Place photos
                //Source: https://developers.google.com/places/android-api/photos
                final String placeId = place_ID;
                Places.GeoDataApi.getPlacePhotos(mGoogleApiClient, placeId)
                        .setResultCallback(new ResultCallback<PlacePhotoMetadataResult>() {
                            @Override
                            public void onResult(PlacePhotoMetadataResult photos) {
                                if (!photos.getStatus().isSuccess()) {
                                    return;
                                }
                                ImageView mImageView = (ImageView) findViewById(R.id.imageView);
                                ImageView mImageViewExpanded = (ImageView) findViewById(R.id.headerImage);
                                TextView txtAttribute = (TextView) findViewById(R.id.photoAttribute);
                                TextView expTxtAttribute = (TextView) findViewById(R.id.expPhotoAttribute);
                                PlacePhotoMetadataBuffer photoMetadataBuffer = photos.getPhotoMetadata();
                                if (photoMetadataBuffer.getCount() > 0) {
                                    // Display the first bitmap in an ImageView in the size of the view
                                    photoMetadataBuffer.get(0).getScaledPhoto(mGoogleApiClient, 600, 200)
                                            .setResultCallback(mDisplayPhotoResultCallback);
                                    //get photo attributions
                                    PlacePhotoMetadata photo = photoMetadataBuffer.get(0);
                                    CharSequence attribution = photo.getAttributions();
                                    if (attribution != null) {
                                        txtAttribute.setText(Html.fromHtml(String.valueOf(attribution)));
                                        expTxtAttribute.setText(Html.fromHtml(String.valueOf(attribution)));
                                        //http://stackoverflow.com/questions/4303160/how-can-i-make-links-in-fromhtml-clickable-android
                                        txtAttribute.setMovementMethod(LinkMovementMethod.getInstance());
                                        expTxtAttribute.setMovementMethod(LinkMovementMethod.getInstance());
                                    } else {
                                        txtAttribute.setText(" ");
                                        expTxtAttribute.setText(" ");
                                    }
                                } else {
                                    //Reset image view as no photo was identified
                                    mImageView.setImageResource(android.R.color.transparent);
                                    mImageViewExpanded.setImageResource(android.R.color.transparent);
                                    txtAttribute.setText(R.string.no_photos);
                                    expTxtAttribute.setText(R.string.no_photos);
                                }
                                photoMetadataBuffer.release();
                            }
                        });

                LatLng destLocation = new LatLng(Double.parseDouble(placeLat), Double.parseDouble(placeLng));
                //Work out distance between current location and place location
                //Source Library: https://github.com/googlemaps/android-maps-utils
                double distance = SphericalUtil.computeDistanceBetween(realLocation, destLocation);
                distance = Math.round(distance);
                distance = distance * 0.001;
                String strDistance = String.valueOf(distance);
                String[] arrDistance = strDistance.split("\\.");
                String unit = "km";
                if (arrDistance[0] == "0") {
                    unit = "m";
                    strDistance = arrDistance[1];
                } else {
                    strDistance = arrDistance[0] + "." + arrDistance[1].substring(0, 1);
                }

                placeArticle = placeArticle
                        .replaceAll("(<div class=\"thumb t).*\\s.*\\s.*\\s.*\\s.*\\s<\\/div>\\s<\\/div>", " ");

                Spannable noUnderlineMessage = new SpannableString(Html.fromHtml(placeArticle));

                //http://stackoverflow.com/questions/4096851/remove-underline-from-links-in-textview-android
                for (URLSpan u : noUnderlineMessage.getSpans(0, noUnderlineMessage.length(), URLSpan.class)) {
                    noUnderlineMessage.setSpan(new UnderlineSpan() {
                        public void updateDrawState(TextPaint tp) {
                            tp.setUnderlineText(false);
                        }
                    }, noUnderlineMessage.getSpanStart(u), noUnderlineMessage.getSpanEnd(u), 0);
                }

                placeArticle = String.valueOf(noUnderlineMessage);
                placeArticle = placeArticle.replaceAll("(\\[\\d\\])", " ");

                placeTitle.setText(placeName);
                expPlaceTitle.setText(placeName);
                placeVic.setText(placeLoc);
                expPlaceVic.setText(placeLoc);
                expPlaceDescription.setText(placeArticle);
                if (MELBOURNE.contains(realLocation)) {
                    expPlaceDistance.setText("Distance: " + strDistance + unit);
                    distanceCont.setVisibility(View.VISIBLE);
                }
            }

            tile.setVisibility(View.VISIBLE);
            fab.setVisibility(View.VISIBLE);
            //Set to true to not show default behaviour.
            return false;
        }
    });

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            int viewStatus = tile.getVisibility();
            if (viewStatus == View.VISIBLE) {
                tile.setVisibility(View.INVISIBLE);
                fab.setVisibility(View.INVISIBLE);
                //set previous marker back to partial opac (if there is a prevMarker
                if (dirtyMarker == 1) {
                    prevMarker.setAlpha(0.6f);
                }
            }

            mMap.setPadding(0, 0, 0, 0);
        }
    });

    FloatingActionButton shareIcon = (FloatingActionButton) findViewById(R.id.shareIcon);
    shareIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //https://www.google.com.au/maps/place/Federation+Square/@-37.8179789,144.9668635,15z

            //Build implicit intent by triggering a SENDTO action, which will capture applications that allow for messages
            //that allow for messages to be sent to a specific user with data
            //http://developer.android.com/reference/android/content/Intent.html#ACTION_SENDTO
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            //Build SMS
            String encodedPlace = "empty";
            try {
                encodedPlace = URLEncoder.encode(String.valueOf(expPlaceTitle.getText()), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(expPlaceTitle.getText())
                    + " \n\nhttps://www.google.com.au/maps/place/" + encodedPlace);
            Intent sms = Intent.createChooser(intent, null);
            startActivity(sms);
        }
    });

    TextView fullArticle = (TextView) findViewById(R.id.fullArticle);
    fullArticle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String wikiPlace = WikiPlace.getName(String.valueOf(expPlaceTitle.getText()));
            String url = "https://en.wikipedia.org/wiki/" + wikiPlace;

            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(browserIntent);
        }
    });
}

From source file:br.com.appvis.appvis.barcode.BarcodeCaptureActivity.java

/**
 * Callback for the result from requesting permissions. This method
 * is invoked for every call on {@link #requestPermissions(String[], int)}.
 * <p>/*from w w  w.j  ava2s  .c o m*/
 * <strong>Note:</strong> It is possible that the permissions request interaction
 * with the user is interrupted. In this case you will receive empty permissions
 * and results arrays which should be treated as a cancellation.
 * </p>
 *
 * @param requestCode  The request code passed in {@link #requestPermissions(String[], int)}.
 * @param permissions  The requested permissions. Never null.
 * @param grantResults The grant results for the corresponding permissions
 *                     which is either {@link PackageManager#PERMISSION_GRANTED}
 *                     or {@link PackageManager#PERMISSION_DENIED}. Never null.
 * @see #requestPermissions(String[], int)
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    if (requestCode != RC_HANDLE_CAMERA_PERM) {
        Log.d(TAG, "Got unexpected permission result: " + requestCode);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        return;
    }

    if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "Camera permission granted - initialize the camera source");
        // we have permission, so create the camerasource
        boolean autoFocus = true;
        boolean useFlash = false;
        createCameraSource(autoFocus, useFlash);
        return;
    }

    Log.e(TAG, "Permission not granted: results len = " + grantResults.length + " Result code = "
            + (grantResults.length > 0 ? grantResults[0] : "(empty)"));

    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            finish();
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Multitracker sample").setMessage(R.string.no_camera_permission)
            .setPositiveButton(R.string.ok, listener).show();
}

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

public void RefreshLinks() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        refreshLayout.setRefreshing(true);
        final GetLinks g = new GetLinks();
        RefreshLinks2(g);//from   w w  w . j a  v  a  2 s .  c om
        refreshLayout.setRefreshing(false);
    } else {
        if (checkSelfPermission(
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            refreshLayout.setRefreshing(true);
            final GetLinks g = new GetLinks();
            RefreshLinks2(g);
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    1);
        }
    }
}

From source file:cc.echonet.coolmicapp.MainActivity.java

private boolean checkPermission() {
    return ContextCompat.checkSelfPermission(this,
            Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this,
                    Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
}

From source file:android_network.hetnet.vpn_service.Util.java

public static boolean hasPhoneStatePermission(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        return (context.checkSelfPermission(
                Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED);
    else//from w  w w  .  j  a  v a2  s.c  om
        return true;
}

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

private void supportLibPermissionsOnConnected() {
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        getLocation();/* w  w w .ja v a2s  .c om*/
    } else {
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Explain to the user why we need to read the contacts
            Toast.makeText(this, R.string.permission_rationale, Toast.LENGTH_LONG).show();
        }

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

From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningActivity.java

/**
 * Check the device- and app location permissions and show location settings dialogs if needed
 *///from ww  w .j av  a2s  .c  o m
private void checkLocationPermissions() {

    // create a settingsrequest to get the device location setting
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    // disable to show 'NEVER' option in case we need to request device location permission using a dialog
    builder.setAlwaysShow(true);

    // fire the request to get the setting and act on the result
    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
            .checkLocationSettings(mGoogleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
            final Status status = locationSettingsResult.getStatus();
            switch (status.getStatusCode()) {

            // device settings are not satisfied, but this can be fixed by showing the user a settings dialog
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                try {
                    status.startResolutionForResult(DagvergunningActivity.this, DEVICE_LOCATION_SETTING);
                } catch (IntentSender.SendIntentException e) {
                }
                break;

            // device location settings are satisfied, so we check the app permission
            case LocationSettingsStatusCodes.SUCCESS:

                // check if the app itself has location permission
                if (ContextCompat.checkSelfPermission(getApplicationContext(),
                        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                    // if we refused app permission to the location before we show a dialog
                    // with an explanation first
                    if (ActivityCompat.shouldShowRequestPermissionRationale(DagvergunningActivity.this,
                            Manifest.permission.ACCESS_FINE_LOCATION)) {

                        // show a alert dialog containing an explanation, and on close click
                        // ask for the app location permission
                        new AlertDialog.Builder(DagvergunningActivity.this).setIcon(R.drawable.mm_orange)
                                .setTitle(getString(R.string.title_dagvergunning_app_location_refused))
                                .setMessage(getString(R.string.notice_dagvergunning_app_location_refused))
                                .setCancelable(false)
                                .setPositiveButton(
                                        getString(R.string.notice_dagvergunning_app_location_refused_ok),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {

                                                // ask for app location permission
                                                ActivityCompat.requestPermissions(DagvergunningActivity.this,
                                                        new String[] {
                                                                Manifest.permission.ACCESS_FINE_LOCATION },
                                                        APP_LOCATION_SETTING);
                                            }
                                        })
                                .show();
                    } else {

                        // ask for app location permission
                        ActivityCompat.requestPermissions(DagvergunningActivity.this,
                                new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                                APP_LOCATION_SETTING);
                    }
                }
                break;

            // device settings are not satisfied. however, we have no way to fix the settings so we won't show the dialog
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                break;
            }
        }
    });
}