Search code examples
javaandroid-studiointerfaceoverridingandroid-permissions

Can't override onRequestPermissionResult in AndroidStudio


I found the code below in this tutorial(-> Android Developer Guide). I copied the code and did some minor changes like picking the permission needed for my Application. The issue here is that I can't override onRequestPermissionResult as shown in the tutorial. Whenever I try to, the IDE states Method does not override method from its superclass.

Superclass?? As shown in the documentation the method onRequestPermissionResult is part of the interface ActivityCompat.OnRequestPermissionsResultCallback. Therefore I tried implementing the interface and the did the following change: public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback.

This didn't solve the problem ...

package com.example.test1;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity 
    implements  ActivityCompat.OnRequestPermissionsResultCallback{

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED){
            Log.d(TAG, "Permission not granted");

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.RECORD_AUDIO)){
                Log.d(TAG, "some explanation is required??? wut");
            } else {
                Log.d(TAG, "requests permission");
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.RECORD_AUDIO}, 1);
            }
        }
    }

    @Override
    public void onRequestPermissionResult (int requestCode,
                                          String[] permissions,
                                          int[] grantResults){
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Log.d(TAG, "permission was granted");
                } else {
                    Log.d(TAG, "permission was denied");
                }
            }
        }
    }
}



Solution

  • @Michael - Thanks for this, I was going in circles for 20 minutes, had the same problem, simply because I've copied & pasted the code from Android documentation.

    The typo is in the documentation so if you copy & paste the code from there. you will end up with this. :)