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:eu.codeplumbers.cosi.services.CosiCallService.java

/**
 * Read phone call log and update app database
 *///www .ja  va2s.c  o  m
private void readCallLog() {
    //Fetches the complete call log in descending order. i.e recent calls appears first.
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED) {
        Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null,
                CallLog.Calls.DATE + " DESC");

        int totalCalls = c.getCount();

        EventBus.getDefault()
                .post(new CallSyncEvent(SYNC_MESSAGE, "Reading phone log: " + c.getCount() + " calls..."));

        if (c.moveToFirst()) {
            for (int i = 0; i < totalCalls; i++) {
                EventBus.getDefault()
                        .post(new CallSyncEvent(SYNC_MESSAGE, "Local call " + i + "/" + totalCalls + "..."));
                String callerID = c.getString(c.getColumnIndex(CallLog.Calls._ID));
                String callerNumber = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));
                long callDateandTime = c.getLong(c.getColumnIndex(CallLog.Calls.DATE));
                long callDuration = c.getLong(c.getColumnIndex(CallLog.Calls.DURATION));
                int callType = c.getInt(c.getColumnIndex(CallLog.Calls.TYPE));

                Call call = Call.getByIdNumberDate(callerID, callerNumber, callDateandTime);

                if (call == null) {
                    call = new Call();
                }

                call.setRemoteId(
                        (call.getRemoteId() != "" && call.getRemoteId() != null) ? call.getRemoteId() : "");
                call.setCallerId(callerID);
                call.setCallerNumber(callerNumber);
                call.setDateAndTime(DateUtils.formatDate(callDateandTime));
                call.setType(callType);
                call.setDuration(callDuration);

                boolean hasDevice = call.getDeviceId() != "" && call.getDeviceId() != null;

                call.setDeviceId(hasDevice ? call.getDeviceId() : Device.registeredDevice().getLogin());
                call.save();

                allCalls.add(call);

                c.moveToNext();
            }
        }
        c.close();
    } else {
        EventBus.getDefault()
                .post(new CallSyncEvent(SERVICE_ERROR, getString(R.string.permission_denied_call_log)));
    }
}

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

private void readSmsDatabase() {
    //Fetches the complete call log in descending order. i.e recent calls appears first.
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
        Uri message = Uri.parse("content://sms/");
        ContentResolver cr = getContentResolver();

        Cursor c = cr.query(message, null, null, null, null);
        int totalSMS = c.getCount();

        if (c.moveToFirst()) {
            for (int i = 0; i < totalSMS; i++) {
                mBuilder.setProgress(totalSMS, i, false);
                mNotifyManager.notify(notification_id, mBuilder.build());
                EventBus.getDefault()//from   w  w  w .j  a v a  2 s .  c om
                        .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
                String systemId = c.getString(c.getColumnIndexOrThrow("_id"));
                String address = c.getString(c.getColumnIndexOrThrow("address"));
                String body = c.getString(c.getColumnIndexOrThrow("body"));
                String readState = c.getString(c.getColumnIndex("read"));
                String dateAndTime = c.getString(c.getColumnIndexOrThrow("date"));
                String type = c.getString(c.getColumnIndexOrThrow("type"));

                Sms sms = Sms.getBySystemId(systemId);

                if (sms == null) {
                    sms = new Sms();
                    sms.setRemoteId("");
                }

                sms.setBody(body);
                sms.setAddress(address.replace(" ", "").replace("-", ""));
                sms.setDateAndTime(DateUtils.formatDate(dateAndTime));
                sms.setSystemId(systemId);
                sms.setType(Integer.valueOf(type));
                sms.setReadState(Boolean.parseBoolean(readState));
                sms.setDeviceId(
                        sms.getRemoteId() != "" ? sms.getDeviceId() : Device.registeredDevice().getLogin());
                sms.save();

                allSms.add(sms);

                c.moveToNext();
            }
        }
        // else {
        // throw new RuntimeException("You have no SMS");
        // }
        c.close();
    } else {
        EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, getString(R.string.permission_denied_sms)));
        stopSelf();
    }
}

From source file:com.platform.GeoLocationManager.java

public void stopGeoSocket() {
    final MainActivity app = MainActivity.app;
    if (app == null)
        return;//from  w ww .  j av  a 2 s .  c o  m
    final LocationManager locationManager = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE);

    app.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (ActivityCompat.checkSelfPermission(app,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(app,
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "stopGeoSocket, can't happen");
                RuntimeException ex = new RuntimeException("stopGeoSocket, can't happen");
                FirebaseCrash.report(ex);
                throw ex;
            }
            locationManager.removeUpdates(socketLocationListener);

        }
    });
}

From source file:com.newventuresoftware.waveformdemo.MainActivity.java

private void startAudioRecordingSafe() {
    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
        mRecordingThread.startRecording();
    } else {//  ww w.  j  a v a 2s  .  c o  m
        requestMicrophonePermission();
    }
}

From source file:arun.com.chameleonskinforkwlp.activities.CameraCapturerActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
    case REQUEST_CAMERA_PERMISSION: {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            checkPermissionAndLaunchCamera();
        } else {/*from  ww  w  .j a v  a2s  . c  om*/
            onUserDeniedPermission();
        }
    }
    }
}

From source file:me.kartikarora.transfersh.activities.DownloadActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == FileGridAdapter.PERM_REQUEST_CODE && grantResults.length > 0) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            beginDownload(name, type, url);
    }/*from   w  w w  .j a  va2 s.c o  m*/
}

From source file:io.v.syncslides.SignInActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
    case REQUEST_CODE_ASK_PERMISSIONS:
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            pickAccount();/*from  ww  w .  ja  va2 s  . c  o m*/
            return;
        } else {
            Toast.makeText(this, "Access to contacts required to pick account", Toast.LENGTH_LONG).show();
            requestPermissions(new String[] { Manifest.permission.READ_CONTACTS },
                    REQUEST_CODE_ASK_PERMISSIONS);
            return;
        }
    default:
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

From source file:com.platform.middlewares.plugins.GeoLocationPlugin.java

@Override
public boolean handle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) {//www . j  a  v  a 2 s.co  m
    if (target.startsWith("/_permissions/geo")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        MainActivity app = MainActivity.app;
        if (app == null) {
            Log.e(TAG, "handle: context is null: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(500, "context is null", baseRequest, response);
        }
        switch (request.getMethod()) {
        // GET /_permissions/geo
        //
        // Call this method to retrieve the current permission status for geolocation.
        // The returned JSON dictionary contains the following keys:
        //
        // "status" = "denied" | "restricted | "undetermined" | "inuse" | "always"
        // "user_queried" = true | false
        // "location_enabled" = true | false
        //
        // The status correspond to those found in the apple CLLocation documentation: http://apple.co/1O0lHFv
        //
        // "user_queried" indicates whether or not the user has already been asked for geolocation
        // "location_enabled" indicates whether or not the user has geo location enabled on their phone
        case "GET":
            JSONObject jsonResult = new JSONObject();
            String status;
            boolean enabled;
            boolean permRequested = SharedPreferencesManager.getGeoPermissionsRequested(app);
            int permissionCheck = ContextCompat.checkSelfPermission(app,
                    Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                status = "always";
                enabled = true;
            } else {
                Log.e(TAG, "handle: sending permission denied: " + target + " " + baseRequest.getMethod());
                status = permRequested ? "denied" : "undetermined";
                enabled = false;
            }
            try {
                jsonResult.put("status", status);
                jsonResult.put("user_queried", permRequested);
                jsonResult.put("location_enabled", enabled);
                return BRHTTPHelper.handleSuccess(200, jsonResult.toString().getBytes(), baseRequest, response,
                        null);
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e(TAG,
                        "handle: failed to send permission status: " + target + " " + baseRequest.getMethod());
                return BRHTTPHelper.handleError(500, null, baseRequest, response);
            }
            // POST /_permissions/geo
            //
            // Call this method to request the geo permission from the user.
            // The request body should be a JSON dictionary containing a single key, "style"
            // the value of which should be either "inuse" or "always" - these correspond to the
            // two ways the user can authorize geo access to the app. "inuse" will request
            // geo availability to the app when the app is foregrounded, and "always" will request
            // full time geo availability to the app
        case "POST":
            if (ContextCompat.checkSelfPermission(app,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "handle: requesting permissions: " + target + " " + baseRequest.getMethod());
                ActivityCompat.requestPermissions(app,
                        new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, BRConstants.GEO_REQUEST_ID);
            }
            SharedPreferencesManager.putGeoPermissionsRequested(app, true);
            continuation = ContinuationSupport.getContinuation(request);
            continuation.suspend(response);
            globalBaseRequest = baseRequest;
            return true;

        }
    } else if (target.startsWith("/_geo") && !target.startsWith("/_geosocket")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        // GET /_geo
        //
        // Calling this method will query CoreLocation for a location object. The returned value may not be returned
        // very quick (sometimes getting a geo lock takes some time) so be sure to display to the user some status
        // while waiting for a response.
        //
        // Response Object:
        //
        // "coordinates" = { "latitude": double, "longitude": double }
        // "altitude" = double
        // "description" = "a string representation of this object"
        // "timestamp" = "ISO-8601 timestamp of when this location was generated"
        // "horizontal_accuracy" = double
        MainActivity app = MainActivity.app;
        if (app == null) {
            Log.e(TAG, "handle: context is null: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(500, "context is null", baseRequest, response);
        }

        if (request.getMethod().equalsIgnoreCase("GET")) {
            JSONObject obj = getAuthorizationError(app);
            if (obj != null) {
                Log.e(TAG, "handle: error getting location: " + obj.toString() + ", " + target + " "
                        + baseRequest.getMethod());
                return BRHTTPHelper.handleError(500, obj.toString(), baseRequest, response);
            }

            continuation = ContinuationSupport.getContinuation(request);
            continuation.suspend(response);
            GeoLocationManager.getInstance().getOneTimeGeoLocation(continuation, baseRequest);
            return true;
        }
    } else if (target.startsWith("/_geosocket")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        // GET /_geosocket
        //
        // This opens up a websocket to the location manager. It will return a new location every so often (but with no
        // predetermined interval) with the same exact structure that is sent via the GET /_geo call.
        //
        // It will start the location manager when there is at least one client connected and stop the location manager
        // when the last client disconnects.

        return true;
    }

    return false;
}

From source file:io.v.android.apps.syncslides.SignInActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, String permission[], int[] grantResults) {
    switch (requestCode) {
    case REQUEST_CODE_READ_CONTACTS: {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            requestContactsDone();//from w  w w .j  av a2s  .  c  o m
            return;
        }
        Log.e(TAG, "User didn't approve read contacts");
        fetchUserProfile();
    }
    }
}

From source file:com.wiyun.engine.network.Network.java

static boolean isWifiConnected() {
    Context context = Director.getInstance().getContext();
    if (context.checkCallingOrSelfPermission(
            android.Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wm != null) {
            WifiInfo info = wm.getConnectionInfo();
            return info != null && info.getSupplicantState() == SupplicantState.COMPLETED;
        } else {//from w w  w  .ja v a 2  s . c o  m
            return false;
        }
    } else {
        Log.w("libwiengine", "you need add ACCESS_WIFI_STATE permission");
        return false;
    }
}