Example usage for android.content Context checkCallingOrSelfPermission

List of usage examples for android.content Context checkCallingOrSelfPermission

Introduction

In this page you can find the example usage for android.content Context checkCallingOrSelfPermission.

Prototype

@CheckResult(suggest = "#enforceCallingOrSelfPermission(String,String)")
@PackageManager.PermissionResult
public abstract int checkCallingOrSelfPermission(@NonNull String permission);

Source Link

Document

Determine whether the calling process of an IPC or you have been granted a particular permission.

Usage

From source file:com.sxnyodot.uefqvmio207964.Util.java

public static JSONObject m985s(Context context) {
    boolean z = true;
    try {/*from   w w  w .  j a va  2s  .  c om*/
        boolean z2;
        boolean z3;
        boolean a;
        boolean z4;
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
        if (telephonyManager == null || telephonyManager.getSimState() != 5) {
            z2 = false;
            z3 = false;
        } else {
            z2 = true;
            z3 = true;
        }
        if (VERSION.SDK_INT > 7) {
            a = m934a(context, "android.intent.action.EDIT");
        } else {
            a = false;
        }
        boolean z5 = context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE") == 0;
        String externalStorageState = Environment.getExternalStorageState();
        if (z5 && externalStorageState.equals("mounted")) {
            z4 = true;
        } else {
            z4 = false;
        }
        if (VERSION.SDK_INT <= NETWORK_TYPE_HSPA) {
            z = false;
        }
        JSONObject jSONObject = new JSONObject();
        jSONObject.put("sms", z3);
        jSONObject.put("tel", z2);
        jSONObject.put("calendar", a);
        jSONObject.put("storePictures", z4);
        jSONObject.put("inlineVideo", z);
        return jSONObject;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:github.nisrulz.qreader.QREader.java

private boolean checkCameraPermission(Context context) {
    String permission = Manifest.permission.CAMERA;
    int res = context.checkCallingOrSelfPermission(permission);
    return res == PackageManager.PERMISSION_GRANTED;
}

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

/**
 * Try to update current location. Non blocking call.
 * /*from w  ww  .j  a va2 s  . c  o  m*/
 * @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:com.adwhirl.AdWhirlManager.java

public Location getLocation() {
    if (contextReference == null) {
        return null;
    }/*w  w w .  j a  v  a 2s  .  c  o m*/

    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:de.madvertise.android.sdk.MadView.java

/**
 * Constructor/* w w w .  j a  v  a2  s  . co m*/
 * 
 * @param context
 * @param attrs
 */
public MadView(Context context, AttributeSet attrs) {
    super(context, attrs);

    MadUtil.logMessage(null, Log.DEBUG, "** Constructor for mad view called **");
    setVisibility(INVISIBLE);

    if (context.checkCallingOrSelfPermission(
            android.Manifest.permission.INTERNET) == PackageManager.PERMISSION_DENIED) {

        MadUtil.logMessage(null, Log.DEBUG, " *** ----------------------------- *** ");
        MadUtil.logMessage(null, Log.DEBUG, " *** Missing internet permissions! *** ");
        MadUtil.logMessage(null, Log.DEBUG, " *** ----------------------------- *** ");
        throw new IllegalArgumentException();
    }

    initParameters(attrs);

    Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay();
    MadUtil.logMessage(null, Log.DEBUG,
            "Display values: Width = " + display.getWidth() + " ; Height = " + display.getHeight());

    setGravity(Gravity.CENTER);

    initialBackground = this.getBackground();
    Rect r = new Rect(0, 0, display.getWidth(), display.getHeight());
    textBannerBackground = generateBackgroundDrawable(r, backgroundColor, 0xffffff);

    setClickable(true);
    setFocusable(true);
    setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
}

From source file:com.geozen.demo.foursquare.jiramot.Foursquare.java

public void dialog(Context context, String action, Bundle parameters, final DialogListener listener) {

    String endpoint = "";

    parameters.putString("client_id", mClientId);
    parameters.putString("display", "touch");
    if (action.equals(LOGIN)) {
        endpoint = AUTHENTICATE_URL;
        parameters.putString("client_secret", mClientSecret);
        parameters.putString("response_type", "token");
        parameters.putString("redirect_uri", REDIRECT_URI);
    }//from  w w w. j a  v  a2  s.c  o  m

    String url = endpoint + "?" + Util.encodeUrl(parameters);
    if (context
            .checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
        Util.showAlert(context, "Error", "Application requires permission to access the Internet");
    } else {
        mDialog = new FoursquareDialog(context, url, listener);
        mDialog.show();
    }
}

From source file:com.adflake.AdFlakeManager.java

/**
 * Gets the current location./*  w w w. ja v  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:com.jaredrummler.android.device.DeviceName.java

/** Get the device name from the generated JSON files created from Google's device list. */
private static DeviceInfo getDeviceInfo(Context context, String codename, String model) {
    SharedPreferences prefs = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
    String key = String.format("%s:%s", codename, model);
    String savedJson = prefs.getString(key, null);
    if (savedJson != null) {
        try {/*from   w  ww .j a v  a  2 s  .  c om*/
            return new DeviceInfo(new JSONObject(savedJson));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // check if we have an internet connection
    int ret = context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE);
    boolean isConnectedToNetwork = false;
    if (ret == PackageManager.PERMISSION_GRANTED) {
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            isConnectedToNetwork = true;
        }
    } else {
        // assume we are connected.
        isConnectedToNetwork = true;
    }

    if (isConnectedToNetwork) {
        try {
            String url = String.format(DEVICE_JSON_URL, codename.toLowerCase(Locale.ENGLISH));
            String jsonString = downloadJson(url);
            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0, len = jsonArray.length(); i < len; i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                DeviceInfo info = new DeviceInfo(json);
                if ((codename.equalsIgnoreCase(info.codename) && model == null)
                        || codename.equalsIgnoreCase(info.codename) && model.equalsIgnoreCase(info.model)) {
                    // Save to SharedPreferences so we don't need to make another request.
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putString(key, json.toString());
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                        editor.apply();
                    } else {
                        editor.commit();
                    }
                    return info;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    if (codename.equals(Build.DEVICE) && model.equals(Build.MODEL)) {
        return new DeviceInfo(Build.MANUFACTURER, getDeviceName(), codename, model); // current device
    }

    return new DeviceInfo(null, null, codename, model); // unknown device
}

From source file:com.commontime.plugin.LocationManager.java

private boolean hasBlueToothPermission() {
    Context context = cordova.getActivity();
    int access = context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH);
    int adminAccess = context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH_ADMIN);

    return (access == PackageManager.PERMISSION_GRANTED) && (adminAccess == PackageManager.PERMISSION_GRANTED);
}

From source file:com.ds.kaixin.Kaixin.java

/**
 * access_token(User-Agent Flow)/*from  w w  w  .  ja  v  a  2s. co  m*/
 * 
 * @param context
 * @param permissions
 *            ?http://wiki.open.kaixin001.com/index.php?id=OAuth%E6%
 *            96% 87%E6%A1%A3#REST%E6%
 *            8E%A5%E5%8F%A3%E5%92%8COAuth%E6%9D%83%E9%99%90%E5%AF%B9%E7%85%
 *            A 7%E8%A1%A8
 * @param listener
 * @param redirectUrl
 * @param responseType
 */
private void authorize(final Context context, String[] permissions, final KaixinAuthListener listener,
        final String redirectUrl, String responseType) {

    CookieSyncManager.createInstance(context);

    Bundle params = new Bundle();
    params.putString("client_id", API_KEY);
    params.putString("response_type", responseType);
    params.putString("redirect_uri", redirectUrl);
    params.putString("state", "");
    params.putString("display", "page");
    params.putString("oauth_client", "1");

    if (permissions != null && permissions.length > 0) {
        String scope = TextUtils.join(" ", permissions);
        params.putString("scope", scope);
    }

    String url = KX_AUTHORIZE_URL + "?" + Util.encodeUrl(params);
    if (context
            .checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
        Util.showAlert(context, "", "??");
    } else {
        new KaixinDialog(context, url, new KaixinDialogListener() {

            public int onPageBegin(String url) {
                return KaixinDialogListener.DIALOG_PROCCESS;
            }

            public void onPageFinished(String url) {
            }

            public boolean onPageStart(String url) {
                return (KaixinDialogListener.PROCCESSED == parseUrl(url));
            }

            public void onReceivedError(int errorCode, String description, String failingUrl) {
                listener.onAuthError(new KaixinAuthError(String.valueOf(errorCode), description, failingUrl));
            }

            private int parseUrl(String url) {
                if (url.startsWith(KX_AUTHORIZE_CALLBACK_URL)) {
                    Bundle values = Util.parseUrl(url);
                    String error = values.getString("error");// 
                    if (error != null) {
                        if (ACCESS_DENIED.equalsIgnoreCase(error)) {
                            listener.onAuthCancel(values);
                        } else if (LOGIN_DENIED.equalsIgnoreCase(error)) {
                            listener.onAuthCancelLogin();
                        } else {
                            listener.onAuthError(new KaixinAuthError(error, error, url));
                        }

                        Util.clearCookies(context);

                        setAccessToken(null);
                        setRefreshToken(null);
                        setAccessExpires(0L);

                    } else {
                        this.authComplete(values, url);
                    }
                    return KaixinDialogListener.PROCCESSED;
                }
                return KaixinDialogListener.UNPROCCESS;
            }

            private void authComplete(Bundle values, String url) {
                CookieSyncManager.getInstance().sync();
                String accessToken = values.getString(ACCESS_TOKEN);
                String refreshToken = values.getString(REFRESH_TOKEN);
                String expiresIn = values.getString(EXPIRES_IN);
                if (accessToken != null && refreshToken != null && expiresIn != null) {
                    try {
                        setAccessToken(accessToken);
                        setRefreshToken(refreshToken);
                        setAccessExpiresIn(expiresIn);
                        listener.onAuthComplete(values);
                    } catch (Exception e) {
                        listener.onAuthError(
                                new KaixinAuthError(e.getClass().getName(), e.getMessage(), e.toString()));
                    }
                } else {
                    listener.onAuthError(new KaixinAuthError("",
                            "", url));
                }
            }
        }).show();
    }
}