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:de.lespace.apprtc.activity.ConnectActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_connect);

    // Get setting keys.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    keyprefFrom = getString(R.string.pref_from_key);
    keyprefVideoCallEnabled = getString(R.string.pref_videocall_key);
    keyprefResolution = getString(R.string.pref_resolution_key);
    keyprefFps = getString(R.string.pref_fps_key);
    keyprefCaptureQualitySlider = getString(R.string.pref_capturequalityslider_key);
    keyprefVideoBitrateType = getString(R.string.pref_startvideobitrate_key);
    keyprefVideoBitrateValue = getString(R.string.pref_startvideobitratevalue_key);
    keyprefVideoCodec = getString(R.string.pref_videocodec_key);
    keyprefHwCodecAcceleration = getString(R.string.pref_hwcodec_key);
    keyprefCaptureToTexture = getString(R.string.pref_capturetotexture_key);
    keyprefAudioBitrateType = getString(R.string.pref_startaudiobitrate_key);
    keyprefAudioBitrateValue = getString(R.string.pref_startaudiobitratevalue_key);
    keyprefAudioCodec = getString(R.string.pref_audiocodec_key);
    keyprefNoAudioProcessingPipeline = getString(R.string.pref_noaudioprocessing_key);
    keyprefAecDump = getString(R.string.pref_aecdump_key);
    keyprefOpenSLES = getString(R.string.pref_opensles_key);
    keyprefDisplayHud = getString(R.string.pref_displayhud_key);
    keyprefTracing = getString(R.string.pref_tracing_key);
    keyprefRoomServerUrl = getString(R.string.pref_room_server_url_key);
    keyprefRoomList = getString(R.string.pref_room_list_key);

    // Video call enabled flag.
    boolean videoCallEnabled = sharedPref.getBoolean(keyprefVideoCallEnabled,
            Boolean.valueOf(getString(R.string.pref_videocall_default)));

    String wssUrl = sharedPref.getString(keyprefRoomServerUrl,
            getString(R.string.pref_room_server_url_default));
    from = sharedPref.getString(keyprefFrom, getString(R.string.pref_from_default));
    // Get default codecs.
    String videoCodec = sharedPref.getString(keyprefVideoCodec, getString(R.string.pref_videocodec_default));
    String audioCodec = sharedPref.getString(keyprefAudioCodec, getString(R.string.pref_audiocodec_default));

    // Check HW codec flag.
    boolean hwCodec = sharedPref.getBoolean(keyprefHwCodecAcceleration,
            Boolean.valueOf(getString(R.string.pref_hwcodec_default)));

    // Check Capture to texture.
    boolean captureToTexture = sharedPref.getBoolean(keyprefCaptureToTexture,
            Boolean.valueOf(getString(R.string.pref_capturetotexture_default)));

    // Check Disable Audio Processing flag.
    boolean noAudioProcessing = sharedPref.getBoolean(keyprefNoAudioProcessingPipeline,
            Boolean.valueOf(getString(R.string.pref_noaudioprocessing_default)));

    // Check Disable Audio Processing flag.
    boolean aecDump = sharedPref.getBoolean(keyprefAecDump,
            Boolean.valueOf(getString(R.string.pref_aecdump_default)));

    // Check OpenSL ES enabled flag.
    boolean useOpenSLES = sharedPref.getBoolean(keyprefOpenSLES,
            Boolean.valueOf(getString(R.string.pref_opensles_default)));

    // Check for mandatory permissions.
    missingPermissions = new ArrayList();

    for (String permission : MANDATORY_PERMISSIONS) {
        if (checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(permission);
        }/*  ww  w  .j  a  v a2 s.  c  o  m*/
    }
    requestPermission();

    networkchangeBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getFlags() == 0) {
                SignalingService.appRTCClient.resetWebsocket();
            }
            if (intent.getFlags() == 1) {
                SignalingService.appRTCClient.reconnect();
                Toast.makeText(context, "network is online:" + intent.getFlags(), Toast.LENGTH_LONG).show();
            }
        }
    };

    // Registering BroadcastReceiver
    registerNetworkChangeReceiver();

    // Get video resolution from settings.
    int videoWidth = 0;
    int videoHeight = 0;
    String resolution = sharedPref.getString(keyprefResolution, getString(R.string.pref_resolution_default));
    String[] dimensions = resolution.split("[ x]+");
    if (dimensions.length == 2) {
        try {
            videoWidth = Integer.parseInt(dimensions[0]);
            videoHeight = Integer.parseInt(dimensions[1]);
        } catch (NumberFormatException e) {
            videoWidth = 0;
            videoHeight = 0;
            Log.e(TAG, "Wrong video resolution setting: " + resolution);
        }
    }

    // Get camera fps from settings.
    int cameraFps = 0;
    String fps = sharedPref.getString(keyprefFps, getString(R.string.pref_fps_default));
    String[] fpsValues = fps.split("[ x]+");
    if (fpsValues.length == 2) {
        try {
            cameraFps = Integer.parseInt(fpsValues[0]);
        } catch (NumberFormatException e) {
            Log.e(TAG, "Wrong camera fps setting: " + fps);
        }
    }

    // Check capture quality slider flag.
    boolean captureQualitySlider = sharedPref.getBoolean(keyprefCaptureQualitySlider,
            Boolean.valueOf(getString(R.string.pref_capturequalityslider_default)));

    // Get video and audio start bitrate.
    int videoStartBitrate = 0;
    String bitrateTypeDefault = getString(R.string.pref_startvideobitrate_default);
    String bitrateType = sharedPref.getString(keyprefVideoBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefVideoBitrateValue,
                getString(R.string.pref_startvideobitratevalue_default));
        videoStartBitrate = Integer.parseInt(bitrateValue);
    }
    int audioStartBitrate = 0;
    bitrateTypeDefault = getString(R.string.pref_startaudiobitrate_default);
    bitrateType = sharedPref.getString(keyprefAudioBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefAudioBitrateValue,
                getString(R.string.pref_startaudiobitratevalue_default));
        audioStartBitrate = Integer.parseInt(bitrateValue);
    }

    // Check statistics display option.
    boolean displayHud = sharedPref.getBoolean(keyprefDisplayHud,
            Boolean.valueOf(getString(R.string.pref_displayhud_default)));

    boolean tracing = sharedPref.getBoolean(keyprefTracing,
            Boolean.valueOf(getString(R.string.pref_tracing_default)));

    // Log.d(TAG, "Connecting from " + from + " at URL " + wssUrl);

    if (validateUrl(wssUrl)) {
        Uri uri = Uri.parse(wssUrl);
        intent = new Intent(this, ConnectActivity.class);
        intent.setData(uri);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CALL, videoCallEnabled);
        intent.putExtra(CallActivity.EXTRA_VIDEO_WIDTH, videoWidth);
        intent.putExtra(CallActivity.EXTRA_VIDEO_HEIGHT, videoHeight);
        intent.putExtra(CallActivity.EXTRA_VIDEO_FPS, cameraFps);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CAPTUREQUALITYSLIDER_ENABLED, captureQualitySlider);
        intent.putExtra(CallActivity.EXTRA_VIDEO_BITRATE, videoStartBitrate);
        intent.putExtra(CallActivity.EXTRA_VIDEOCODEC, videoCodec);
        intent.putExtra(CallActivity.EXTRA_HWCODEC_ENABLED, hwCodec);
        intent.putExtra(CallActivity.EXTRA_CAPTURETOTEXTURE_ENABLED, captureToTexture);
        intent.putExtra(CallActivity.EXTRA_NOAUDIOPROCESSING_ENABLED, noAudioProcessing);
        intent.putExtra(CallActivity.EXTRA_AECDUMP_ENABLED, aecDump);
        intent.putExtra(CallActivity.EXTRA_OPENSLES_ENABLED, useOpenSLES);
        intent.putExtra(CallActivity.EXTRA_AUDIO_BITRATE, audioStartBitrate);
        intent.putExtra(CallActivity.EXTRA_AUDIOCODEC, audioCodec);
        intent.putExtra(CallActivity.EXTRA_DISPLAY_HUD, displayHud);
        intent.putExtra(CallActivity.EXTRA_TRACING, tracing);
        intent.putExtra(CallActivity.EXTRA_RUNTIME, runTimeMs);
    }

    roomListView = (ListView) findViewById(R.id.room_listview);
    roomListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    connectButton = (ImageButton) findViewById(R.id.connect_button);
    connectButton.setOnClickListener(connectListener);

    // If an implicit VIEW intent is launching the app, go directly to that URL.
    //final Intent intent = getIntent();
    Uri wsurl = Uri.parse(wssUrl);
    //intent.getData();
    // Log.d(TAG, "connecting to:" + wsurl.toString());
    if (wsurl == null) {
        logAndToast(getString(R.string.missing_wsurl));
        Log.e(TAG, "Didn't get any URL in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    if (from == null || from.length() == 0) {
        logAndToast(getString(R.string.missing_from));
        Log.e(TAG, "Incorrect from in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    peerConnectionParameters = new PeerConnectionClient.PeerConnectionParameters(videoCallEnabled, tracing,
            videoWidth, videoHeight, cameraFps, videoStartBitrate, videoCodec, hwCodec, captureToTexture,
            audioStartBitrate, audioCodec, noAudioProcessing, aecDump, useOpenSLES);

    Intent intent = getIntent();
    Log.i(TAG, "created apprtc with uri:" + wsurl.toString() + " from:" + from);

    Log.i(TAG, "intent.EXTRA_TO:" + intent.getStringExtra(RTCConnection.EXTRA_TO));
    Log.i(TAG, "intent.EXTRA_FROM:" + intent.getStringExtra(RTCConnection.EXTRA_FROM));
    Log.i(TAG, "intent.EXTRA_INITIATOR:" + intent.getBooleanExtra(RTCConnection.EXTRA_INITIATOR, false));

    if (intent.getStringExtra(RTCConnection.EXTRA_TO) != null
            && !intent.getStringExtra(RTCConnection.EXTRA_TO).equals("")) {

        RTCConnection.to = intent.getStringExtra(RTCConnection.EXTRA_TO);
        RTCConnection.from = intent.getStringExtra(RTCConnection.EXTRA_FROM);
        RTCConnection.initiator = intent.getBooleanExtra(RTCConnection.EXTRA_INITIATOR, false);
        ;
        connectToUser();
    }

    /*  if(intent.getStringExtra(RTCConnection.EXTRA_TO)!=null
            && !intent.getStringExtra(RTCConnection.EXTRA_TO).equals("")){
            
          RTCConnection.to = intent.getStringExtra(RTCConnection.EXTRA_TO);
         // RTCConnection.from = intent.getStringExtra(RTCConnection.EXTRA_FROM);
          RTCConnection.initiator = intent.getBooleanExtra(RTCConnection.EXTRA_INITIATOR,false);;
            
      Intent serviceIntent = new Intent(this,SignalingService.class);
      serviceIntent.putExtra(RTCConnection.EXTRA_FROM, RTCConnection.to);
            
     //WebRTC-Signaling
     startService(intent);
    }*/

}

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

private boolean validited() {
    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;
    }/*www  .  j a  v  a2 s  . c  o  m*/
    return true;
}

From source file:au.com.domain.AccountsAutoCompleteTextView.java

/**
 * Clients would need to call this method because Android only calls back the host activity.
 *
 * @param requestCode/*ww w . j ava  2 s.  c  o  m*/
 * @param permissions
 * @param grantResults
 */
public void onPermissionResponse(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    boolean granted = REQUEST_CODE == requestCode && grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED;

    if (granted) {
        setAccountOptions();
        mAccountsAutocomplete.showDropDown();
    } else {

        if (mActivity == null && mFragment == null) {
            throw new IllegalStateException(
                    "No calling Activity or Fragment declared. Call either setParentActivity() or setParentFragment().");
        }

        boolean shouldShowRationale;
        // This will return TRUE if te user has previously denied a request
        // On subsequent times that we request the permission and the user chooses "Don't ask again", it will return FALSE
        if (mActivity != null) {
            shouldShowRationale = ActivityCompat.shouldShowRequestPermissionRationale(mActivity,
                    Manifest.permission.GET_ACCOUNTS);
        } else {
            shouldShowRationale = mFragment
                    .shouldShowRequestPermissionRationale(Manifest.permission.GET_ACCOUNTS);
        }

        if (!shouldShowRationale) {
            mAccountsAutocomplete.setAdapter(mAdapter = null);
        }
    }
}

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

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            donateViaWeChat();//from w  w w  .j  a va 2  s. co m
        } else {
            findViewById(R.id.wechat).setVisibility(View.GONE);
        }
    }
}

From source file:com.alivenet.dmvtaxi.Activity_ConfirmMybooking.java

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.custome_map);
    Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
    setSupportActionBar(toolbar);/*from  w  w  w. j ava  2s.c om*/
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    mPref = Activity_ConfirmMybooking.this.getSharedPreferences(MYPREF, Context.MODE_PRIVATE);
    mtvpickup_address = (TextView) findViewById(R.id.tv_pickup_address);
    mtvdrop_address = (TextView) findViewById(R.id.tv_drop_address);
    mtvestimateprice = (TextView) findViewById(R.id.tv_primerate);
    mconfirmbooking = (LinearLayout) findViewById(R.id.ll_confirmbooking);
    cinfirmbooking = (TextView) findViewById(R.id.cinfirmbooking);
    mivimagecar = (ImageView) findViewById(R.id.iv_carimage);
    Bundle b = getIntent().getExtras();
    Bundle b1 = getIntent().getExtras();
    latitude = b1.getDouble("currentlatitude");
    longitude = b1.getDouble("currentlongitude");
    lat = b.getDouble("distantionLat");
    lng = b.getDouble("distantionLng");

    prgDialog = new ProgressDialog(this);
    prgDialog.setMessage("Please wait...");
    prgDialog.setCancelable(false);

    pickup_address = getIntent().getStringExtra("pickup_address");
    drop_address = getIntent().getStringExtra("drop_address");
    cabId = getIntent().getStringExtra("cabId");
    paymentoption = getIntent().getStringExtra("paymentoption");
    passenger = getIntent().getStringExtra("passenger");
    userId = getIntent().getStringExtra("userId");

    cinfirmbooking.setText("CONFIRM BOOKING");

    mivimagecar.startAnimation(inFromRightAnimation());

    if (pickup_address != null) {
        mtvpickup_address.setText(pickup_address);
        mtvdrop_address.setText(drop_address);
    }

    if (getIntent() != null) {
        baseFare = Double.parseDouble(getIntent().getStringExtra("baseFare"));
        baseFareDistance = Double.parseDouble(getIntent().getStringExtra("baseFareDistance"));
        perKm = Double.parseDouble(getIntent().getStringExtra("perKm"));
        waitingCharge = Double.parseDouble(getIntent().getStringExtra("waitingCharge"));

        am_additioncharge = Double.parseDouble(getIntent().getStringExtra("madditioncharge"));
        am_telephone_dispatch = Double.parseDouble(getIntent().getStringExtra("mtelephone_dispatch"));
        am_passengerSurgcharge = Double.parseDouble(getIntent().getStringExtra("mpassengerSurgcharge"));
        am_luggagecharge = Double.parseDouble(getIntent().getStringExtra("mluggagecharge"));
        am_airportSurcharge = Double.parseDouble(getIntent().getStringExtra("mairportSurcharge"));
        am_additionHourcharge = Double.parseDouble(getIntent().getStringExtra("madditionHourcharge"));
        am_perpassengercharge = Double.parseDouble(getIntent().getStringExtra("mperpassengercharge"));
        am_snowcharge = Double.parseDouble(getIntent().getStringExtra("msnowcharge"));

        System.out.println("am_additioncharge==>>" + am_additioncharge);
        System.out.println("am_telephone_dispatch==>>" + am_telephone_dispatch);
        System.out.println("am_passengerSurgcharge==>>" + am_passengerSurgcharge);
        System.out.println("am_luggagecharge==>>" + am_luggagecharge);
        System.out.println("am_airportSurcharge==>>" + am_airportSurcharge);
        System.out.println("am_additionHourcharge==>>" + am_additionHourcharge);
        System.out.println("am_perpassengercharge==>>" + am_perpassengercharge);
        System.out.println("am_snowcharge==>>" + am_snowcharge);

    }
    googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapdirection)).getMap();

    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googleMap.setMyLocationEnabled(true);

    if (latitude != 0.0d && longitude != 0.0d) {
        Log.e("longitudeconfirm", "" + longitude);
        Log.e("latitudeconfirm", "" + latitude);

        drawMarker(new LatLng(longitude, longitude));
        MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("");
        marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude))
                .zoom(10).build();

        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        googleMap.addMarker(marker);
        if (ActivityCompat.checkSelfPermission(Activity_ConfirmMybooking.this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(Activity_ConfirmMybooking.this,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        }
        googleMap.setMyLocationEnabled(true);
    }

    if (lat != 0.0d && lng != 0.0d) {
        drawMarkerOnActivity(new LatLng(lat, lng));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)));
        // Setting the zoom level in the map on last position is clicked
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));
    }

    mconfirmbooking.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (userId != null && latitude != 0.0d && longitude != 0.0d && lat != 0.0d && lng != 0.0d
                    && cabId != null && paymentoption != null) {
                ride_trip_validate = new Ride_trip_validate();
                // ride_trip_validate.Ride_trip_validategetvalue(userId, String.valueOf(latitude), String.valueOf(longitude), String.valueOf(lat), String.valueOf(lng), cabId,paymentoption);
                ride_trip_validate.execute();
                //validateRide(userId, String.valueOf(latitude), String.valueOf(longitude), String.valueOf(lat), String.valueOf(lng), cabId,paymentoption);

            }
        }
    });

    cinfirmbooking.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (cinfirmbooking.getText().equals("Share Of The Fare")) {

                Intent in = new Intent(Activity_ConfirmMybooking.this, SplitAddFrnd.class);
                in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(in);
            } else {
                if (userId != null && latitude != 0.0d && longitude != 0.0d && lat != 0.0d && lng != 0.0d
                        && cabId != null && paymentoption != null)
                    ride_trip_validate = new Ride_trip_validate();
                ride_trip_validate.execute();

            }

        }
    });

    validateGET_TIME(latitude, longitude, lat, lng);

}

From source file:com.mycompany.myfirstindoorsapp.PagedActivity.java

private void requestPermissionsFromUser() {
    /**//from w  ww.j  a va2 s  .  c o m
     * Since API level 23 we need to request permissions for so called dangerous permissions from the user.
     *
     * You can see a full list of needed permissions in the Manifest File.
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int permissionCheckForLocation = ContextCompat.checkSelfPermission(PagedActivity.this,
                Manifest.permission.ACCESS_COARSE_LOCATION);

        if (permissionCheckForLocation != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                    REQUEST_CODE_PERMISSIONS);
        } else {
            //If permissions were already granted,
            // we can go on to check if Location Services are enabled.
            checkLocationIsEnabled();
        }
    } else {
        //Continue loading Indoors if we don't need user-settable-permissions.
        // In this case we are pre-Marshmallow.
        continueLoading();
    }
}

From source file:de.madvertise.android.sdk.MadUtil.java

/**
 * Try to update current location. Non blocking call.
 * //from   w w  w.  jav a 2 s .c  om
 * @param context
 *            application context
 */
protected static void refreshCoordinates(Context context) {
    if (PRINT_LOG)
        Log.d(LOG, "Trying to refresh location");

    if (context == null) {
        if (PRINT_LOG)
            Log.d(LOG, "Context not set - quit location refresh");
        return;
    }

    // check if we need a regular update
    if ((locationUpdateTimestamp + MadUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System.currentTimeMillis()) {
        if (PRINT_LOG)
            Log.d(LOG, "It's not time yet for refreshing the location");
        return;
    }

    synchronized (context) {
        // recheck, if location was updated by another thread while we paused
        if ((locationUpdateTimestamp + MadUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System
                .currentTimeMillis()) {
            if (PRINT_LOG)
                Log.d(LOG, "Another thread updated the loation already");
            return;
        }

        boolean permissionCoarseLocation = context.checkCallingOrSelfPermission(
                android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        boolean permissionFineLocation = context.checkCallingOrSelfPermission(
                android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;

        // return (null) if we do not have any permissions
        if (!permissionCoarseLocation && !permissionFineLocation) {
            if (PRINT_LOG)
                Log.d(LOG, "No permissions for requesting the location");
            return;
        }

        // return (null) if we can't get a location manager
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            if (PRINT_LOG)
                Log.d(LOG, "Unable to fetch a location manger");
            return;
        }

        String provider = null;
        Criteria criteria = new Criteria();
        criteria.setCostAllowed(false);

        // try to get coarse location first
        if (permissionCoarseLocation) {
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            provider = locationManager.getBestProvider(criteria, true);
        }

        // try to get gps location if coarse locatio did not work
        if (provider == null && permissionFineLocation) {
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            provider = locationManager.getBestProvider(criteria, true);
        }

        // still no provider, return (null)
        if (provider == null) {
            if (PRINT_LOG)
                Log.d(LOG, "Unable to fetch a location provider");
            return;
        }

        // create a finalized reference to the location manager, in order to
        // access it in the inner class
        final LocationManager finalizedLocationManager = locationManager;
        locationUpdateTimestamp = System.currentTimeMillis();
        locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
            public void onLocationChanged(Location location) {
                if (PRINT_LOG)
                    Log.d(LOG, "Refreshing location");
                currentLocation = location;
                locationUpdateTimestamp = System.currentTimeMillis();
                // stop draining battery life
                finalizedLocationManager.removeUpdates(this);
            }

            // not used yet
            public void onProviderDisabled(String provider) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
        }, context.getMainLooper());
    }
}

From source file:br.edu.ufabc.padm.cardioufabc.MainActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == WRITE_EXTERNAL_STORAGE_REQ_CODE) {
        // como as permisses so solicitadas individualmente, basta verificar apenas o primeiro
        if (grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                permissible.onPermissionGranted(permissions[0]);
            } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(this,
                        permissions[0]);
                // "never ask again" habilitado
                if (!showRationale) {
                    permissible.onNeverAskAgain(permissions[0]);
                }/*  w  w w  .j  a va2s.c  o m*/
            }
        }
    }
}

From source file:com.facebook.AuthorizationClient.java

boolean checkInternetPermission() {
    if (checkedInternetPermission) {
        return true;
    }/*from w w w  .ja  v a 2s  . c o m*/

    int permissionCheck = checkPermission(Manifest.permission.INTERNET);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        String errorType = context.getString(R.string.com_facebook_internet_permission_error_title);
        String errorDescription = context.getString(R.string.com_facebook_internet_permission_error_message);
        complete(Result.createErrorResult(pendingRequest, errorType, errorDescription));

        return false;
    }

    checkedInternetPermission = true;
    return true;
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_video, container, false);

    // configure the name
    nameView = (TextView) view.findViewById(R.id.video_name);
    nameView.setText(camera.name);// w  w w .  j a  va 2 s. c o m

    // initialize the message
    messageView = (TextView) view.findViewById(R.id.video_message);
    messageView.setTextColor(App.getClr(R.color.good_text));
    messageView.setText(R.string.initializing_video);

    // set the texture listener
    textureView = (ZoomPanTextureView) view.findViewById(R.id.video_surface);
    textureView.setSurfaceTextureListener(this);
    textureView.setZoomRange(MIN_ZOOM, MAX_ZOOM);
    textureView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent e) {
            switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                stopFadeOutTimer();
                break;
            case MotionEvent.ACTION_UP:
                if (e.getPointerCount() == 1) {
                    startFadeOutTimer(false);
                }
                break;
            }
            return false;
        }
    });

    // create the snapshot button
    snapshotButton = (Button) view.findViewById(R.id.video_snapshot);
    snapshotButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int check = ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (check != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(),
                        new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                        REQUEST_WRITE_EXTERNAL_STORAGE);
            } else {
                takeSnapshot();
            }
        }
    });

    // move the snapshot button over to account for the navigation bar
    if (fullScreen) {
        float scale = getContext().getResources().getDisplayMetrics().density;
        int margin = (int) (5 * scale + 0.5f);
        int extra = Utils.getNavigationBarHeight(getContext(), Configuration.ORIENTATION_LANDSCAPE);
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) snapshotButton.getLayoutParams();
        lp.setMargins(margin, margin, margin + extra, margin);
    }

    return view;
}