Android Activity Result API with Hilt(Dependency Injection)

Hello folks, I wanted to tell you everything about Activity Result API, but I will not do at all. :D As far as you know there are a lot of writings and also you can reach official info from here.

I am going to tell you about Activity Result API with using DI (Hilt) and LifecycleObserver. At last days I have been using Hilt, I am giving my sample with it. We can exemplify with camera and storage permissions.


Firstly we are creating two helper classes , the first one is;

The second one is;

AbstractPermissionObserve inherits from lifecycleObserver, that’s why we can bind this permission class to any activity lifecycle.

Step 2:

We had created AbstractLifecycleObserver in step 1, so we will write main injectable permission class which is inherited by AbstractPermissionObserver.

Above, I am defining ActivityScoped for this class because I want it will bind to activity lifecycle.Another reason is ActivityContext. I need to reach activity instance thanks to ActivityContext qualifier that has been predefined in Hilt, we can do it easily. Also we have two main function inside class, in onCreate method we are registering ActivityResult and in onDestroy we are equals requestPermission object to null to avoid memory leak issue.


launch: We are using this method to trigger request permission dialog from user.


The last thing in CameraPermissionObserver class is checkPermission method. Sometimes we might need to check all permission granted or denied, we can learn permissions’ status with using this method implementation.

So far, we have explained what the permission classes and therir functions are, as well as what they do. So now, how do we use it in activity?
Just remember, we defined CameraPermissionObserver class as ActivityScoped because of that we should add this observer to Any Activity class. Like below I have a BaseActivity class and I am injecting observer.

Eventually we can create a fragment to use our PermissionObserver.

Github sample project is here.

If you have any issue for codebase, please warn me from comments, as soon as possible I will fix.

Happy coding :)

Oktein Company, Software Engineer, Python Enthusiast