Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android M onRequestPermissionsResult in non-Activity

I have an application which needs to find the user location, and location is fetched in various classes, so i have written a separate class(Not an Activity class) that fetches user location using location services, it works fine under Android M but requires run time permissions in Android M, i want to check permissions in my Location class and i know how to check them but i cannot use onRequestPermissionsResult method in my Location class, because my Location class do not extends from any activity.

So What i should do for achieving this? any help/clue is appreciated Thanks in advance

like image 810
MD Husnain Tahir Avatar asked Jul 20 '16 11:07

MD Husnain Tahir


Video Answer


2 Answers

Since public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) is an abstract method of ActivityCompat.OnRequestPermissionsResultCallback interface. See the documentation

Just implement this interface in the required class and it's done. For example

class location implements  ActivityCompat.OnRequestPermissionsResultCallback{ } 

Now just override onRequestPermissionsResult()

 @Override public void onRequestPermissionsResult(int requestCode,                                        String permissions[], int[] grantResults) {     switch (requestCode) {      // case Statements     } } 
like image 160
AkshayK Avatar answered Sep 19 '22 12:09

AkshayK


You are welcome to call checkSelfPermission() from a non-UI class, as that merely needs some Context.

However, you must call requestPermissions() on some activity or fragment. You override onRequestPermissionsResult() on that same activity or fragment. This is no different than calling startActivityForResult() and implementing onActivityResult().

The idea is that you request the permission before you do anything that involves your non-UI classes that are dealing with locations.

like image 25
CommonsWare Avatar answered Sep 20 '22 12:09

CommonsWare