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 then denies camera permission, the app enters into a loop and keeps displaying the alert dialog repeatedly.
- If the user denies camera permission initially, and then grants it by clicking "OK" in the alert dialog, the app closes unexpectedly.
What I have tried:
This is the 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)
}
}
}
This is the alert dialog:
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, our app needs camera access to detect obstacles ahead. We value your privacy and use the camera solely for this purpose. Please grant permission to enjoy our app's features, Thank you!")
.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()
}