Bhavesh
Bhavesh

Reputation: 1071

Android continue after checking and requesting permission

I know there are many questions answered regarding checking and requesting permission and handling their response and I am clear on that. But what I bit confuse about is if we are checking for same permission for two different things, how do we continue task after permission is granted?

For example,I have recycleView and in my adapter I have code for two buttons, one would save file and another one would save and open activity to share that file with other app.

MyRecycleAdapter {

Context context:

save.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
           if(checkPermission()) {
               have permission
               save file to disk
          } else {
              requestPermission
               save file to disk
           }  
     }
});
share.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
           if(checkPermission()) {
               have permission
               save file to disk
               open share activity using (context)
          } else {
              requestPermission
               save file to disk
              open share activity using (context)
           }  
     }
});

}

Upvotes: 2

Views: 1725

Answers (2)

Ika
Ika

Reputation: 1738

Just for the sake of completion. Requesting permissions has been simplified lately in the API. Here's how I check for a permission before doing some action:

private lateinit var requestPermissionLauncher: ActivityResultLauncher<String>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // Permission callback
    val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
        if (isGranted) {
            // Yay, permission was granted
            doSomething()
        }
        else {
            // Boo, permission was refused
            Snackbar.make(root,"Wut ?! We need your permission!", Snackbar.LENGTH_LONG).show()
        }
    }
}

private fun checkLocationPermissionAndDoSomething() {

    // Do we have the permission ?
    if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        // Permission is not granted. Should we show an explanation?
        if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Explanation is needed. Show dialog
            val builder = AlertDialog.Builder(requireContext())
            builder.setTitle("Please")
            builder.setMessage("We need to use your location because bla blah bla.")
            builder.setPositiveButton(android.R.string.ok) { _, _ ->
                requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
            }
            builder.show()
        }
        else {

            // No explanation needed, we can request the permission.
            requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
        }
    } else {

        // Permission has already been granted
        doSomething()
    }
}

When multiple permissions are needed just use ActivityResultContracts.RequestMultiplePermissions and use an array of permissions

Upvotes: 3

lwilber
lwilber

Reputation: 159

Use different request codes to control what happens after permission is granted:

final int SAVE = 1;
final int SAVE_AND_SHARE = 2;

if (ActivityCompat.checkSelfPermission(this,
  Manifest.permission.WRITE_EXTERNAL_STORAGE)
  != PackageManager.PERMISSION_GRANTED
) {
  ActivityCompat.requestPermissions(
    this,
    new String[]{
      android.Manifest.permission.WRITE_EXTERNAL_STORAGE
    },
    [either SAVE or SAVE_AND_SHARE]);
} else {
  //permission is already granted, continue
}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] 
  grantResults) {
  if (requestCode == SAVE) {
    if (grantResults.length > 0
      && grantResults[0] == PackageManager.PERMISSION_GRANTED
    ) {
      //save
    } else {
      //permission was denied
    }
  } else if (requestCode == SAVE_AND_SHARE) {
    if (grantResults.length > 0
      && grantResults[0] == PackageManager.PERMISSION_GRANTED
    ) {
      //save and share
    } else {
      //permission was denied
    }
  }
}

Upvotes: 4

Related Questions