请求运行时权限

时间:2018-06-30 12:32:26

标签: java android android-permissions

我正在尝试将此calendar agenda app更新为最新的SDK。因此,我需要请求运行时权限。

我已经确定需要READ_CALENDAR权限的类是CalendarUtilities.java,特别是这种方法:

public Set<org.reber.agenda.AndroidCalendar> getAvailableCalendars() {
        ContentResolver contentResolver = context.getContentResolver();

        Uri calendarsURI = CalendarContract.Calendars.CONTENT_URI;
        Cursor cursor = contentResolver.query(calendarsURI,
                new String[]{ CalendarContract.Calendars._ID, CalendarContract.Calendars.CALENDAR_COLOR,
                        CalendarContract.Calendars.CALENDAR_DISPLAY_NAME },
                null, null, null);
        // Get all the enabled calendars in the database
        while (cursor != null && cursor.moveToNext()) {
            AndroidCalendar current = new AndroidCalendar(cursor.getString(0),
                    getColorHex(cursor.getString(1)), cursor.getString(2));
            if (!calendars.contains(current)) {
                calendars.add(current);
            }
        }
        if (cursor != null) {
            cursor.close();
        }

        return calendars;
    }

我尝试过:

public Set<org.reber.agenda.AndroidCalendar> getAvailableCalendars() {
        askForPermission(Manifest.permission.READ_CALENDAR, 1);
        return calendars;
    }

    private void askForPermission(String permission, Integer requestCode) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted
                    ContentResolver contentResolver = context.getContentResolver();

                    Uri calendarsURI = CalendarContract.Calendars.CONTENT_URI;
                    Cursor cursor = contentResolver.query(calendarsURI,
                            new String[]{ CalendarContract.Calendars._ID, CalendarContract.Calendars.CALENDAR_COLOR,
                                    CalendarContract.Calendars.CALENDAR_DISPLAY_NAME },
                            null, null, null);
                    // Get all the enabled calendars in the database
                    while (cursor != null && cursor.moveToNext()) {
                        AndroidCalendar current = new AndroidCalendar(cursor.getString(0),
                                getColorHex(cursor.getString(1)), cursor.getString(2));
                        if (!calendars.contains(current)) {
                            calendars.add(current);
                        }
                    }
                    if (cursor != null) {
                        cursor.close();
                    }

                    //return calendars;
                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

但是,应用程序崩溃并显示以下崩溃日志:

java.lang.RuntimeException: Unable to start activity ComponentInfo{/org.reber.agenda.AgendaActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2793)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
                                                                          at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                          at android.os.Looper.loop(Looper.java:156)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6523)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
                                                                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
                                                                          at android.content.ContextWrapper.checkPermission(ContextWrapper.java:669)
                                                                          at android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:439)

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您似乎正在从字段初始值设定项或构造函数中调用checkSelfPermission()。在调用checkSelfPermission()之前,最好在调用onCreate()之后,才调用super.onCreate()