Java Code Examples for android.support.v4.content.ContextCompat#checkSelfPermission()

The following examples show how to use android.support.v4.content.ContextCompat#checkSelfPermission() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DevicesActivity.java    From bridgefy-android-samples with MIT License 7 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_devices);
    ButterKnife.bind(this);

    // initialize the DevicesAdapter and the RecyclerView
    devicesAdapter = new DevicesAdapter();
    devicesRecyclerView.setAdapter(devicesAdapter);
    devicesRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    // check that we have Location permissions
    if (ContextCompat.checkSelfPermission(getApplicationContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        initializeBridgefy();
    } else {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
    }
}
 
Example 2
Source File: MainActivity.java    From Beginner-Level-Android-Studio-Apps with GNU General Public License v3.0 6 votes vote down vote up
public void makePhoneCall() {
    String number =num;
    if (number.trim().length() > 0) {

        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL);
        } else {
            String dial = "tel:" + number;
            startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(dial)));
        }

    } else {
        Toast.makeText(MainActivity.this, "Enter Phone Number", Toast.LENGTH_SHORT).show();
    }
}
 
Example 3
Source File: PhoneUtils.java    From Mobilyzer with Apache License 2.0 6 votes vote down vote up
private String getDeviceId() {
	String deviceId=null;
	if(ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)==PackageManager.PERMISSION_GRANTED){
		// This ID is permanent to a physical phone.
		deviceId = telephonyManager.getDeviceId();
	}



	// "generic" means the emulator.
	if (deviceId == null || Build.DEVICE.equals("generic")) {

		// This ID changes on OS reinstall/factory reset.
		deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
	}

	return deviceId;
}
 
Example 4
Source File: EasyPermissions.java    From AndroidBasicProject with MIT License 6 votes vote down vote up
/**
 * Check if the calling context has a set of permissions.
 *
 * @param context the calling context.
 * @param perms   one ore more permissions, such as {@code android.Manifest.permission.CAMERA}.
 * @return true if all permissions are already granted, false if at least one permission
 * is not yet granted.
 */
public static boolean hasPermissions(Context context, String... perms) {
    // Always return true for SDK < M, let the system deal with the permissions
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        Log.w(TAG, "hasPermissions: API version < M, returning true by default");
        return true;
    }

    for (String perm : perms) {
        boolean hasPerm = (ContextCompat.checkSelfPermission(context, perm) ==
                PackageManager.PERMISSION_GRANTED);
        if (!hasPerm) {
            return false;
        }
    }

    return true;
}
 
Example 5
Source File: IdenticonsSettings.java    From Identiconizer with Apache License 2.0 6 votes vote down vote up
private void checkPermissions() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_CONTACTS)) {
            new AlertDialog.Builder(this)
                    .setTitle("Permission required")
                    .setMessage("This app requires access to your contacts to function")
                    .setPositiveButton("Request permission", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(IdenticonsSettings.this,
                                    new String[]{Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS},
                                    PERMISSIONS_REQUEST_CODE);
                        }
                    })
                    .show();
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS},
                    PERMISSIONS_REQUEST_CODE);
        }
    }

}
 
Example 6
Source File: LibraryActivity.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	/* Hide 'home' icon on old themes */
	final ActionBar actionBar = getActionBar();
	if (actionBar != null) {
		actionBar.setDisplayShowHomeEnabled(false);
	}

	prefs = getPreferences(Context.MODE_PRIVATE);

	topDirectory = Environment.getExternalStorageDirectory();
	currentDirectory = new File(prefs.getString("currentDirectory", topDirectory.getAbsolutePath()));

	adapter = new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_1);
	setListAdapter(adapter);

	if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
		ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
 
Example 7
Source File: HelperPermission.java    From iGap-Android with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void getMicroPhonePermission(Context context, OnGetPermission onGetPermission) throws IOException {

        if (checkApi()) {
            if (onGetPermission != null) onGetPermission.Allow();
            return;
        }

        ResultRecordAudio = onGetPermission;

        int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            getPermission(context, new String[]{Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_RECORD_AUDIO, context.getResources().getString(R.string.permission_record_audio),
                    ResultRecordAudio);
        } else {
            if (onGetPermission != null) onGetPermission.Allow();
        }
    }
 
Example 8
Source File: PPermissionUtils.java    From YImagePicker with Apache License 2.0 5 votes vote down vote up
public static boolean hasCameraPermissions(Activity activity) {
    if (Build.VERSION.SDK_INT >= 23) {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            activity.requestPermissions(new String[]{Manifest.permission.CAMERA}, ImagePicker.REQ_CAMERA);
            return false;
        }
    }
    return true;
}
 
Example 9
Source File: ConnectionsActivity.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns {@code true} if the app was granted all the permissions. Otherwise, returns {@code
 * false}.
 */
public static boolean hasPermissions(Context context, String... permissions) {
  for (String permission : permissions) {
    if (ContextCompat.checkSelfPermission(context, permission)
        != PackageManager.PERMISSION_GRANTED) {
      return false;
    }
  }
  return true;
}
 
Example 10
Source File: GuitarTunerActivity.java    From Android-Guitar-Tuner with Apache License 2.0 5 votes vote down vote up
@Override
public void onResume() {
    super.onResume();

    // Check if we still have the correct permissions
    // If we don't we have to close this Activity and open the Permission Activity
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_DENIED) {
        startActivity(PermissionActivity.newIntent(this));
        finish();
    }
}
 
Example 11
Source File: MainActivity.java    From Woodmin with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mNavigationDrawerFragment = (NavigationDrawerFragment)getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));

    WoodminSyncAdapter.initializeSyncAdapter(getApplicationContext());
    //WoodminSyncAdapter.syncImmediately(getApplicationContext());

    //Search
    //Intent intentHeader= new Intent(getApplicationContext(), HeadInfoService.class);
    //intentHeader.putExtra("search","3339024328");
    //startService(intentHeader);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    Log.i("Woodmin", "Permission: " + permissionCheck);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Log.i("Woodmin", "Permission granted");
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    10);
        }
    }

    processIntent(getIntent());
}
 
Example 12
Source File: MainActivity.java    From sms-parsing with Apache License 2.0 5 votes vote down vote up
/**
 * Runtime permission shenanigans
 */
private boolean hasReadSmsPermission() {
    return ContextCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED;
}
 
Example 13
Source File: GankIoActivity.java    From styT with Apache License 2.0 5 votes vote down vote up
private void checkPermissionAndDonateWeixin() {
    //检测微信是否安装
    if (!hasInstalledWeiXinClient(this)) {
        Toast.makeText(this, "未安装微信客户端", Toast.LENGTH_SHORT).show();
        return;
    }
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        //已经有权限
        showDonateTipDialog();
    } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
    }
}
 
Example 14
Source File: AbsWeexActivity.java    From WeexOne with MIT License 5 votes vote down vote up
public void runWithPermissionsCheck(int requestCode, String permission, Runnable runnable) {
  if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
      Toast.makeText(this, "please give me the permission", Toast.LENGTH_SHORT).show();
    } else {
      ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
    }
  } else {
    if (runnable != null) {
      runnable.run();
    }
  }
}
 
Example 15
Source File: MainActivity.java    From pasm-yolov3-Android with GNU General Public License v3.0 5 votes vote down vote up
private void validateReadStoragePermission() {
    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG, "Permission is not granted");
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                MY_PERMISSIONS_REQUEST_STORAGE);
    }
}
 
Example 16
Source File: SearchPlaceOnMapActivity.java    From Airbnb-Android-Google-Map-View with MIT License 5 votes vote down vote up
private void enableMyLocation() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // Permission to access the location is missing.
        PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                Manifest.permission.ACCESS_FINE_LOCATION, true);
    } else if (mMap != null) {
        // Access to the location has been granted to the app.
        mMap.setMyLocationEnabled(true);
    }
}
 
Example 17
Source File: WelcomeActivity.java    From AndroidDemo with MIT License 5 votes vote down vote up
private void initPermission() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        checkSkip();
        return;
    }
    if (ContextCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(WelcomeActivity.this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                PERMISSON_REQUESTCODE);
    }else {
        checkSkip();
    }
}
 
Example 18
Source File: MainActivity.java    From OpenCircle with GNU General Public License v3.0 4 votes vote down vote up
public boolean askForContactPermission(final String manifestPermission){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,manifestPermission) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    manifestPermission)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Permission needed");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setMessage("please confirm permissions");//TODO put real question
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @TargetApi(Build.VERSION_CODES.M)
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        requestPermissions(
                                new String[]
                                        {manifestPermission}
                                , PERMISSION_REQUEST_CONTACT);
                    }
                });
                builder.show();
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this,
                        new String[]{manifestPermission},
                        PERMISSION_REQUEST_CONTACT);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }

            return true;
        }else{
          //  getContact();
            return false;
        }
    }
    else{
       // getContact();
        return false;
    }
}
 
Example 19
Source File: Compatibility.java    From Conversations with GNU General Public License v3.0 4 votes vote down vote up
public static boolean hasStoragePermission(Context context) {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
 
Example 20
Source File: SimpleSlide.java    From Puff-Android with MIT License 4 votes vote down vote up
private synchronized void updatePermissions(@Nullable String[] newPermissions) {
    if (newPermissions != null) {
        final List<String> permissionsNotGranted = new ArrayList<>();
        for (String permission : newPermissions) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsNotGranted.add(permission);
            }
        }

        if (permissionsNotGranted.size() > 0) {
            this.permissions = permissionsNotGranted.toArray(
                    new String[permissionsNotGranted.size()]);
            if (buttonGrantPermissions != null) {
                buttonGrantPermissions.setVisibility(View.VISIBLE);
                buttonGrantPermissions.setText(getResources().getQuantityText(
                        R.plurals.mi_label_grant_permission, permissionsNotGranted.size()));
                buttonGrantPermissions.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int permissionsRequestCode = getArguments() == null ? DEFAULT_PERMISSIONS_REQUEST_CODE :
                                getArguments().getInt(ARGUMENT_PERMISSIONS_REQUEST_CODE,
                                        DEFAULT_PERMISSIONS_REQUEST_CODE);
                        ActivityCompat.requestPermissions(getActivity(), permissions,
                                permissionsRequestCode);
                    }
                });
            }
        } else {
            this.permissions = null;
            if (buttonGrantPermissions != null) {
                buttonGrantPermissions.setVisibility(View.GONE);
            }
        }
    } else {
        this.permissions = null;
        if (buttonGrantPermissions != null) {
            buttonGrantPermissions.setVisibility(View.GONE);
        }
    }
}