简体   繁体   中英

Google play services location listener not being called but program still needs it to work?

So as I stated in the question, I am implementing location services (google not android version) and I am tryin to toast from the method to see it being called but I am not having any luck. If i remove it though I get errors on this line and thus can not request location updates

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

is this part of the location listener library or something? I just can't understand why the app won't toast when i change location. I have researched a lot but can not find the answer so I am asking here. It is picking up a location and toasting the latitude in my handleNewLocation method.

Here is my code

package com.example.mick.mylocation;

import android.app.Activity;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;

public class MainActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener
        {
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private LocationRequest mLocationRequest;

    private GoogleApiClient mGoogleApiClient;
    public static final String TAG = MainActivity.class.getSimpleName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds


        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        Toast.makeText(getApplicationContext(),"PAUSED ", Toast.LENGTH_LONG).show();

        super.onPause();
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

            Toast.makeText(getApplicationContext(), "Location services conntected", Toast.LENGTH_LONG).show();
            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (location == null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            } else {
                handleNewLocation(location);
            }

        }


    private void handleNewLocation(Location location) {
        Toast.makeText(getApplicationContext(),"HANNDLE NEW LOCATION METHOD lat is "+location.getLatitude(), Toast.LENGTH_LONG).show();


    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(getApplicationContext(),"SUSPENDED", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
            Toast.makeText(getApplicationContext(),"Location services connection failed with code " + connectionResult.getErrorCode(), Toast.LENGTH_LONG).show();

        }

    }


    @Override
    public void onLocationChanged(Location location) {
        Toast.makeText(getApplicationContext(),"ON LOCATION CHANGED METHOD", Toast.LENGTH_LONG).show();

//        handleNewLocation(location);
    }

}

Thanks

My guess is that you're never doing the 1st requestLocationUpdates() in onConnect() . Just because you're newly connected does not mean that getLastLocation() will be null. In fact, you're hoping it won't be so that a display can be updated as soon as possible.

Try this:

    if (location != null) {
        handleNewLocation(location);
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

It won't hurt to send a new requestLocationUpdates() each time you're connected. (In fact, I think if config change has caused you to disconnect & re-connect to GoogleApiClient, you need to send a new request)

If I were you, I would save myself from the unnecessary boilerplate and the headache of dealing with googleApiClients by using ReactiveLocation:

public class MainActivity extends Activity {

     public static final String TAG = MainActivity.class.getSimpleName();
     private Subscription subscription;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds


         ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
         subscription = locationProvider.getUpdatedLocation(mLocationRequest)
            .subscribe(new Action1<Location>() {
                @Override
                public void call(Location location) {
                    //This will be called every time a new location is received
                    Toast.makeText(getApplicationContext(), "Location updated", Toast.LENGTH_LONG).show();
                }
            });

    }

    @Override
    public void onPause() {
         //Make sure to stop listening for updates when you don't need them anymore
         subscription.unsubscribe();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM