Android Calendar Check Permission

早过忘川 提交于 2019-12-25 04:27:40

问题


I'm currently implementing the calendar provider however i've stumbled upon a minor error that i'd like to prevent.

ContentResolver contentResolver = getContentResolver();
ContentValues contentValues = new ContentValues();

....

Uri uri = contentResolver.insert(CalendarContract.Events.CONTENT_URI, contentValues); // Error pops here

"Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential `SecurityException"

What is the best method to prevent this error?

Any help will be appreciated.


回答1:


Handle android permission first , check if they are available , if not you can request them as shown below

proceed with your functionality only if permissions are available

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED 
    && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);}else if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) == PackageManager.PERMISSION_GRANTED 
        && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED){

ContentResolver contentResolver = getContentResolver();
ContentValues contentValues = new ContentValues();
Uri uri = contentResolver.insert(CalendarContract.Events.CONTENT_URI, contentValues);}



回答2:


You can always add throws SecurityException to the method and take care of the caught exception further upstream. Furthermore, I would recommend using this library https://github.com/tbruyelle/RxPermissions if you interested in using reactivex methodology to deal with permissioning.




回答3:


Your targetSdkVersion is 23 or higher, just reduce it



来源:https://stackoverflow.com/questions/40236169/android-calendar-check-permission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!