0

I am currently working on an Android app that involves camera object detection. However, I have encountered some issues that need to be addressed:

  • The app displays a black screen after granting camera permission, requiring one or two app restarts to open the camera successfully. I also made an alert dialog to prompt the user if camera permission is not granted. However, the alert dialog has some bugs:
  • If the user clicks "OK" in the alert dialog and denies camera permission, the app enters into a loop and repeatedly displays the alert dialog.
  • If the user denies camera permission initially, and then grants it by clicking "OK" in the alert dialog, the app closes unexpectedly.

onCreate function:

if (ContextCompat.checkSelfPermission(
               this,
               android.Manifest.permission.CAMERA
           ) != PackageManager.PERMISSION_GRANTED
       )
           requestPermissions(arrayOf(android.Manifest.permission.CAMERA), 101)
       else
           detectObject()

Permission functions:

    fun getPermission() {
        if (ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        )
        {
            requestPermissions(arrayOf(android.Manifest.permission.CAMERA), 101)
        }
        else
        {
            detectObject()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray)
        {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 101 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            detectObject()
        }
        else
        {
            val alert = PermissionDialog()
            alert.show(supportFragmentManager, null)
        }
    }

Alert dialog class:

   import android.app.AlertDialog
   import android.app.Dialog
   import android.media.MediaPlayer
   import android.os.Bundle
   import android.widget.Toast
   import androidx.fragment.app.DialogFragment
   import com.example.sightfulkotlin.MainActivity
   import com.example.sightfulkotlin.R
   
   class PermissionDialog : DialogFragment() {
   
       private lateinit var mediaPlayer: MediaPlayer
   
       override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
           val builder = AlertDialog.Builder(activity)
           builder
               .setTitle("Camera Permission")
               .setIcon(android.R.drawable.ic_menu_camera)
               .setMessage("Camera permission denied")
               .setPositiveButton("Ok") { _, _ -> (activity as MainActivity).getPermission()}
               .setNegativeButton("Cancel") { _, _ ->
                   Toast.makeText(context, "Sorry, we can't make the app work without the camera permission.", Toast.LENGTH_LONG).show()
               }
               .setCancelable(false)
           return builder.create()
       }

1 Answers1

0

Below I have written a code for granting a runtime permissions for Camera, There is an Array of String in which you can give multiple requests granting as which is needed at runtime.

public class MainActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (checkPermission()) {
        //main logic or main code

       // . write your main code to execute, It will execute if the permission is already given.

        } else {
            requestPermission();
        }
    }

    private boolean checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted
            return false;
        }
        return true;
    }

    private void requestPermission() {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA},
                PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();

                    // main logic
                } else {
                    Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                                != PackageManager.PERMISSION_GRANTED) {
                            showMessageOKCancel("You need to allow access permissions",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                requestPermission();
                                            }
                                        }
                                    });
                        }
                    }
                }
                break;
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }
}