简体   繁体   English

Google Play服务位置监听器没有被调用,但是程序仍需要它工作吗?

[英]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. 因此,正如我在问题中指出的那样,我正在实现位置服务(不是Google的android版本),并且正在尝试从方法中吐司,以查看它是否被调用,但是我没有任何运气。 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. 它在我的handleNewLocation方法中选择一个位置并烘烤纬度。

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() . 我的猜测是,您永远不会在onConnect()执行第一个requestLocationUpdates() onConnect() Just because you're newly connected does not mean that getLastLocation() will be null. 仅仅因为您是新连接的,并不意味着getLastLocation()将为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. 每次连接时发送新的requestLocationUpdates()都没有问题。 (In fact, I think if config change has caused you to disconnect & re-connect to GoogleApiClient, you need to send a new request) (实际上,我认为如果配置更改导致您断开并重新连接到GoogleApiClient,则需要发送新请求)

If I were you, I would save myself from the unnecessary boilerplate and the headache of dealing with googleApiClients by using ReactiveLocation: 如果您是我,则可以使用ReactiveLocation避免不必要的样板工作以及与googleApiClients交往的麻烦

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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