What is the correct usage of "this" in Android Studio - ActivityCompat.requestPermissions?

723 Views Asked by At

In using the method below, Android Studio is generating the following error on the keyword "this":

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_READ_FINE_LOCATION);

Error:

Wrong first argument type...found com.websmithing.wp.gpstracker.LocationService, required android.app. Activity

I can reference the activity using "this" without any error when evaluating the manifest file permissions check as per below.

ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)   !=
  PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
  PackageManager.PERMISSION_GRANTED) {

Can anyone point me in the right direction?

3

There are 3 best solutions below

0
On

this refers to the present class. It only works with this when you are in an activity while requesting permission.

Solution

Send a notification from the service so when the user clicks it, open the activity and ask for the permissions you need.

How do I send a notification?

Simple refer to Building a Notification.

2
On

Pay attention to the error message. It's pointing you toward the solution.

Wrong first argument type...found com.websmithing.wp.gpstracker.LocationService, required android.app. Activity

It means that ActivityCompat.requestPermissions() is expecting an Activity as the first argument but you are providing a LocationService instance. I guess you are invoking this from an inner class, then perhaps you have to use WhateverYouActivityClassIs.this to refer to the outer class.

2
On

You have to write the checkSelfpermission code in the activity where you call the class.