Home > Enterprise >  How to avoid using Listener on Android - Java
How to avoid using Listener on Android - Java

Time:11-24

I'm trying to get the last user's position but I'm in a static context.

Here's the code

public void getLastKnownLocation() {
    FusedLocationProviderClient fusedLocationClient = LocationServices.
            getFusedLocationProviderClient(App.getContext());

    fusedLocationClient.getLastLocation()
            .addOnSuccessListener(**activity_needed_here**, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        System.out.println("Speed is "   location.getSpeed());
                    }
                }
            });

The problem is that I'm in a static context and I cannot have an activity here to call. I can, however, access the app context.

How can I avoid using the addOnSuccessListener or how can I implement this in a static context?

CodePudding user response:

According to the Task JavaDocs, there are three forms of addOnSuccessListener(). You could consider using the one that does not take an Activity as the first parameter.

CodePudding user response:

you can change the code to export this listener, example:

public Task<Location> getLastKnownLocation() {
    FusedLocationProviderClient fusedLocationClient = LocationServices.
            getFusedLocationProviderClient(App.getContext());

    return fusedLocationClient.getLastLocation()

And when you call getLastKnownLocation, should do:

getLastKnownLocation().addOnSuccessListener(....).addOnFailureListener(...)
  • Related