patrick1980 patrick1980 - 1 month ago 10
Java Question

Error when trying to make a method with delay

Trying to call this method with delay:

LocationServices.FusedLocationApi.requestLocationUpdates(GoogleApiClient, LocationRequest, (LocationListener) this);


I found on stack this method that causes delay:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);


But when i trying to call this method like this:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
LocationServices.FusedLocationApi.requestLocationUpdates(GoogleApiClient, LocationRequest, (LocationListener) this);
}
}, 100);


Android studio change this for

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) this);
}
}, 100);


and now my problem, android studio highlighted errors:

this
in
(this, Manifest.permission.ACCESS_FINE_LOCATION)


this
in
(this, Manifest.permission.ACCESS_COARSE_LOCATION)


and
(LocationListener) this
in
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) this);


What to do to make it work?

Answer

In Java, this is a keyword that references the context to which the method your executing is in. this in the run() method is actually referring to the Runnable() class created by your Handler.

You need to pass in your activity context to the Runnable() and use that in those methods.