I'm trying to migrate my project to the new activi...
# android
s
I'm trying to migrate my project to the new activity result API. I have a
PermissionUtils
that takes care of checking/requesting permissions:
Copy code
object PermissionUtils {
    fun checkPermissions(context: Context, permissions: List<String>, listener: PermissionListener) {
        // uses a library that checks for permissions and calls listener.onPermissionsGranted() or listener.onPermissionsDenied()
    }
}
Now, to use the new activity result API, I'd have to register the contracts in each activity, which doesn't sound good because I have many activities and all of them would look like this:
Copy code
class MyActivity : AppCompatActivity {
    val imageFromGallery = registerForActivityResult(RequestMultiplePermissions()) { 
        ...
    }

    val takePicture = registerForActivityResult(RequestMultiplePermissions()) { 
        ...
    }

    val shareImage = registerForActivityResult(RequestMultiplePermissions()) { 
        ...
    }
}
Is it possible to incorporate this logic into the
checkPermissions()
function itself?
i
Is there a reason you aren't encapsulating all of that logic into a separate class like the guide goes through? https://developer.android.com/training/basics/intents/result#separate
s
I guess that's better, what do you suggest for the naming of the observer?
MyActivityObserver
?
I'm actually working on a large codebase with many activities over 1k+ lines of code, we're slowly trying to refactor it
@Ian Lake the reason I'm trying to migrate is I'm using this library for handling permissions: https://github.com/nabinbhandari/Android-Permissions which uses onRequestPermissionsResult which I think is deprecated? But, in the docs they're using
onRequestPermissionsResult
to handle the request code. Is it not deprecated? If not, can I keep using that library in my app?
i
You cannot ever use a callback style API for permissions for the same reason as you can't use them for starting an activity for result (explained at the top of that page I linked) - your activity and your whole process can be destroyed while the permission request is happening (this is easy to reproduce: rotate your device while the permission request is up or turn on the "Don't keep activities" developer option). That's why you need to register ahead of time and why the result callback must be completely independent of where you request the permission. Any library that doesn't do that is fundamentally broken
👍 2