Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: ActivityCompat.requestPermissions requires activity and not context :/

I'm calling ActivityCompat.requestPermissions in order to get permissions under android M, however, this requires an activity in the argument. This would be fine, except that I want to call it from a singleton, and the singleton can be used by any activity in the app.

ActivityCompat.requestPermissions(context, PERMISSIONS_LOCATION, REQUEST_LOCATION);

I want to avoid holding a reference to any activity within the singleton as that's a surefire recipe for a memory leak, and also I'd prefer that the singleton not hold an activity at all because it requires useless code in all the activities that call (every single one of them is going to have to include an extra argument in the getInstance() in order for the singleton to hold an activity - the singleton needs to get the activity from somewhere).

Now, I can technically get an activity and then set it to null straight after I request the permission, however that still leaves me with tons of useless activity arguments in every single activity where I make a call to the singleton. Is there a more elegant solution to this problem that I'm just not seeing?

like image 557
Jon Avatar asked Aug 19 '15 13:08

Jon


1 Answers

The documentation on requestPermissions says that the activity parameter is the target activity where you want to show the pop up if you haven't included the permission in your manifest and for this purpose that method requires you to pass an activity and not the context, because upon finish the request permissions task it will then return a result to the calling activity(that is the activity passed as the parameter to the method). If you are so adamant about implementing this through your singleton I suggest you create a function that accepts the activity in the parameter and the callbacks too as you WILL need to handle the callbacks if the permissions were given or not

like image 198
Bhargav Avatar answered Nov 15 '22 15:11

Bhargav