为什么FusedLocationApi.getLastLocation返回null

44

我正在尝试使用FusedLocationApi.getLastLocation获取位置,并在清单文件中获得了位置许可:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

然而,当我从系统请求位置时,我得到了null。我只是在测试开启和关闭位置服务,所以这可能与此有关(当然,在我尝试时它是打开的)。但即使返回null,我还在等待调用onLocationChanged,但从未被调用过。我在这里也看到了一个类似的问题:FusedLocationApi.getLastLocation always null 这是我的代码:
 protected LocationRequest createLocationRequest() {
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(120000);
    mLocationRequest.setFastestInterval(30000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    return mLocationRequest;
}

protected GoogleApiClient getLocationApiClient(){
    return new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

LocationRequest locationRequest = createLocationRequest(); 

@Override
public void onLocationChanged(Location location) {
    App.setLocation(location); // NEVER CALLED
}

@Override
public void onConnected(Bundle bundle) {
    App.setLocation(LocationServices.FusedLocationApi.getLastLocation(locationApiClient)); //RETURNS NULL
    LocationRequest locationRequest = createLocationRequest();
    LocationServices.FusedLocationApi.requestLocationUpdates(locationApiClient, locationRequest, this);
}

在我的应用程序的onCreate方法中:

locationApiClient = getLocationApiClient();
locationApiClient.connect();

为什么我得到了空值(是的,我知道在某些罕见情况下它可能为空,如文档中所述,但我总是得到这个空值,而不是很少)而且之后仍然没有得到位置更新? 这是一个真实的设备(三星Galaxy S3),没有SIM卡,如果可以帮助的话。


3
在Android中没有ACCESS_GPSACCESS_LOCATION权限。除此之外,如果没有代码,很难为您提供帮助。 - CommonsWare
@CommonsWare 我不知道我是怎么变成那样的,但无论如何,它不应该影响行为。 - Can Poyrazoğlu
你是在真实设备上测试吗?除了文档中说,如果客户端未连接,则返回null。确保您的客户端始终处于连接状态。 - Amit K. Saha
你能否粘贴一下初始化 API 客户端和获取 null 的代码? - Borja Alvarez
1
那个回答和这篇文章中到处都是的废话完全一样。问题不在于位置回调,而在于FusedLocationProvider返回getLastLocation时返回null。我亲眼看到它先是报告null,然后正确地报告,几秒钟后又再次报告null,但只有某些设备会出现这种情况。 - Saik Caskey
显示剩余7条评论
14个回答

20

如果没有至少一个客户端连接到融合定位提供程序,它将只维护后台位置。仅打开位置服务并不能保证存储上一次已知的位置。

一旦第一个客户端连接,它将立即尝试获取位置。如果您的活动是第一个连接的客户端,并且在onConnected()中立即调用了getLastLocation(),那么这可能不足以等待第一个位置信息到达。

然后,您设置了mLocationRequest.setFastestInterval(30000),基本上意味着30秒。因此,在最少30秒后且通常根据您的设置首选时间为120秒后,如果完全没有存储的上一个已知位置,会不会很长时间?此外,您正在设置平衡电池优先级,这将使您等待更长时间。

mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

我建议您先打开地图应用程序,以便至少有一些已确认的位置,然后再测试您的应用程序。


我和 OP 有同样的问题,但是在使用模拟器时,我手动设置了设备的位置。在模拟器中打开地图后,这个问题就解决了。 - Daniel O

19

我在我的应用程序中使用FusedLocationProvider api, 这是我的代码,可以在设备和模拟器上都运行 -

  @Override
  protected void onCreate(Bundle savedInstanceState){
     //put your code here
     ....
     getLocation();

  }

 private void getLocation(){
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(LOCATION_INTERVAL);
    locationRequest.setFastestInterval(LOCATION_INTERVAL);
    fusedLocationProviderApi = LocationServices.FusedLocationApi;
    googleApiClient = new GoogleApiClient.Builder(this)
    .addApi(LocationServices.API)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .build();
    if (googleApiClient != null) {
        googleApiClient.connect();
    }
}


   @Override
   public void onConnected(Bundle arg0) {
        fusedLocationProviderApi.requestLocationUpdates(googleApiClient,  locationRequest, this);
   }

   @Override
   public void onLocationChanged(Location location) {
        Toast.makeText(mContext, "location :"+location.getLatitude()+" , "+location.getLongitude(), Toast.LENGTH_SHORT).show();
    }

这是我的可运行代码。

希望我的代码能帮到你。

干杯!


6
请注意,您需要实现GoogleApiClient.ConnectionCallbacks和com.google.android.gms.location.LocationListener。 - DJ_Polly
1
那么作者的代码主要有什么不同之处呢?是指命令序列吗? - Mando
2
@AlexeyStrakh 是的。当应用程序启动时,googleApiClient的lastLocation对象为空。因此,在空对象上调用last location将返回null,因此算法应通过首先更新位置,然后在googleApiClient获取当前位置后继续询问来进行改进。但要小心,因为如果位置不变,则不会触发onLocationChanged。 - Haikal Nashuha
3
你甚至没有使用fusedLocationProviderApi……问题是“为什么FusedLocationApi.getLastLocation为空”,而不是“我如何在没有FusedLocationApi的情况下获取位置更新”。 - Saik Caskey

5
如果它返回null,这意味着您需要在检索位置之前使用LocationServices.FusedLocationApi.requestLocationUpdates开始接收位置更新。
对我而言,解决问题的方法是调用:
LocationServices.FusedLocationApi.requestLocationUpdates(locationApiClient, locationRequest, this);
在以下代码之前:
App.setLocation(LocationServices.FusedLocationApi.getLastLocation(locationApiClient));
问题在于最后的位置不存在,所以它是空的。
如果问题仍然存在,请尝试以下操作:
检查必要的权限。
确保您已经启用了设备上的位置,然后重新启动。

1
这是正确的,我之前也遇到过类似的问题。 lastKnownLocation只是一个缓存位置。实际上,当其他应用程序请求位置时,该位置会被缓存。 - Ersen Osman

4
我使用了FusedAPI,以下代码在实际设备上可行...请测试:

我已经使用了FusedAPI,以下代码在实际设备中可行... 请测试

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.PermissionChecker;
import android.widget.ProgressBar;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.ArrayList;
import java.util.LinkedHashMap;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> {

    private static final int REQUEST_CHECK_SETTINGS = 214;
    private static final int REQUEST_ENABLE_GPS = 516;
    private final int REQUEST_LOCATION_PERMISSION = 214;
    protected GoogleApiClient mGoogleApiClient;
    protected LocationSettingsRequest mLocationSettingsRequest;
    /* For Google Fused API */
    private FusedLocationProviderClient mFusedLocationClient;
    private SettingsClient mSettingsClient;
    private LocationCallback mLocationCallback;
    private LocationRequest mLocationRequest;
    private Location mCurrentLocation;
    /* For Google Fused API */
    private Context context;
    private ProgressBar progressBar;
    private AsyncTask task;
    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        try {
            int permissionCheck = PermissionChecker.checkCallingOrSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                Helper.showLog("Permission is already allowed. Build Client");
                buildGoogleApiClient();
            } else {
                Helper.showLog("Permission is requested");
                ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    protected synchronized void buildGoogleApiClient() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mSettingsClient = LocationServices.getSettingsClient(this);

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

        connectGoogleClient();

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Helper.showLog("Location Received");
                mCurrentLocation = locationResult.getLastLocation();
                onLocationChanged(mCurrentLocation);
            }
        };
    }

    private void connectGoogleClient() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int resultCode = googleAPI.isGooglePlayServicesAvailable(this);
        if (resultCode == ConnectionResult.SUCCESS) {
            mGoogleApiClient.connect();
        } else {
            int REQUEST_GOOGLE_PLAY_SERVICE = 988;
            googleAPI.getErrorDialog(this, resultCode, REQUEST_GOOGLE_PLAY_SERVICE);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(30 * 1000);
        mLocationRequest.setFastestInterval(5 * 1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);
        mLocationSettingsRequest = builder.build();

        mSettingsClient
                .checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                        Helper.showLog("GPS Success");
                        requestLocationUpdate();
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                int statusCode = ((ApiException) e).getStatusCode();
                switch (statusCode) {
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            ResolvableApiException rae = (ResolvableApiException) e;
                            rae.startResolutionForResult(MapsActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sie) {
                            Helper.showLog("PendingIntent unable to execute request.");
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Helper.showLog("Location settings are inadequate, and cannot be fixed here. Fix in Settings.");
                }
            }
        }).addOnCanceledListener(new OnCanceledListener() {
            @Override
            public void onCanceled() {
                Helper.showLog("checkLocationSettings -> onCanceled");
            }
        });
    }

    @Override
    public void onConnectionSuspended(int i) {
        connectGoogleClient();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        buildGoogleApiClient();
    }

    @Override
    public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
        String latitude = String.valueOf(location.getLatitude());
        String longitude = String.valueOf(location.getLongitude());

        if (latitude.equalsIgnoreCase("0.0") && longitude.equalsIgnoreCase("0.0")) {
            requestLocationUpdate();
        } else {
            //Perform Your Task with LatLong
        }
    }

    @SuppressLint("MissingPermission")
    private void requestLocationUpdate() {
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CHECK_SETTINGS) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    Helper.showLog("User allow to access location. Request Location Update");
                    requestLocationUpdate();
                    break;
                case Activity.RESULT_CANCELED:
                    Helper.showLog("User denied to access location.");
                    openGpsEnableSetting();
                    break;
            }
        } else if (requestCode == REQUEST_ENABLE_GPS) {
            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            if (!isGpsEnabled) {
                openGpsEnableSetting();
            } else {
                requestLocationUpdate();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_LOCATION_PERMISSION) {
            int permissionCheck = PermissionChecker.checkCallingOrSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                Helper.showLog("User Allowed Permission Build Google Client");
                buildGoogleApiClient();
            } else {
                Helper.showLog("User Denied Permission");
            }
        }

    }

    private void openGpsEnableSetting() {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, REQUEST_ENABLE_GPS);
    }

    @Override
    protected void onDestroy() {
        //Remove location update callback here
        mFusedLocationClient.removeLocationUpdates(mLocationCallback);
        super.onDestroy();
    }
}

辅助类

public class Helper {
    public static void showLog(String message) {
        Log.e("Ketan", "" + message);
    }

    public static void showToast(Context context, String message) {
        Toast.makeText(context, "" + message, Toast.LENGTH_SHORT).show();
    }
}

可能有帮助


3

可能你遇到的问题是在连接客户端时,我现在无法进行测试,但正如Google文档中所示的那样,在活动的onStart()方法中连接客户端。

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

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

对我来说,这使得getLocation起作用。

7
在 Activity 类的 OnStop() 方法中调用 super 方法之前,你应该断开 Google API 客户端的连接。 - Mrigank

2

1
我不认为这是编程问题。
看起来设备位置提供程序在建议的时间无法确定位置,因此 locationChanged() 方法从未被调用。
检查设备配置是否选择了更严格的位置模式(例如仅 GPS)。
如果是这样,你的代码无法通过 GPS 确定你的室内位置(我猜你是在室内)。选择高精度选项,你的问题就会解决。

1
我找到了解决方法。
我在API 22的手机上测试我的应用程序,它可以正常工作,但是在API 17上位置一直返回null。
事实证明,您必须允许您的手机使用Google位置服务。您可以通过转到“设置->位置访问->勾选“ WLAN和移动网络位置”(在另一个API中可能会有所不同)来完成。其描述如下:
“让应用程序使用Google的位置服务更快地估算您的位置。匿名位置数据将被收集并发送给Google。”
启用它后,我突然开始获得非常需要的融合位置数据。
希望这可以帮助!

1
这是确切的解决方案。但我想添加一些简单的说明步骤,以便任何人都能理解确切的概念。为什么它返回null,我同意遵循Amit K的答案。但是,为了确保避免位置NullPointerException,您应该在onLocationChanged()回调中开始处理与位置相关的内容。
1)Android组件(例如Activity、Fragment或Service。注意:不是IntentService)的onCreate()方法中,构建并连接GoogleApiClient,如下所示。
buildGoogleApiClient();
mGoogleApiClient.connect();

其中,buildGoogleApiClient() 的实现在哪里?

protected synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building GoogleApiClient");

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

    }

稍后在onDestroy()中,您可以断开GoogleApiClient连接,如下:
@Override
    public void onDestroy() {
        Log.i(TAG, "Service destroyed!");
        mGoogleApiClient.disconnect();
        super.onDestroy();
    }

步骤1确保您构建并连接GoogleApiClient。

1)第一次连接GoogleApiClient实例是在onConnected()方法中完成的。现在,您的下一步应该查看onConnected()方法。

@Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.i(TAG, "GoogleApiClient connected!");
        buildLocationSettingsRequest();
        createLocationRequest();
        location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        Log.i(TAG, " Location: " + location); //may return **null** because, I can't guarantee location has been changed immmediately 
    }

在上面,您调用了一个名为createLocationRequest()的方法来创建位置请求。该方法的代码如下。
protected void createLocationRequest() {
        //remove location updates so that it resets
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); //Import should not be **android.Location.LocationListener**
    //import should be **import com.google.android.gms.location.LocationListener**;

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        //restart location updates with the new interval
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    }

3)现在,在LocationListener接口的onLocationChange()回调中,您可以获得新的位置。

@Override
    public void onLocationChanged(Location location) {
        Log.i(TAG, "Location Changed!");
        Log.i(TAG, " Location: " + location); //I guarantee of change of location here.


    }

您可以在Logcat中看到如下结果: 03-22 18:34:17.336 817-817/com.LiveEarthquakesAlerts I/LocationTracker: 位置:Location[fused 37.421998,-122.084000 acc=20 et=+15m35s840ms alt=0.0]

注意:上述位置是Google总部的位置,尽管我在阿肯色州。这是使用模拟器时发生的情况。在真实设备上,它会显示正确的地址。

要执行这三个步骤,您应该将build.gradle配置如下:

 compile 'com.google.android.gms:play-services-location:10.2.1'

1
每个人都知道样板代码在哪里可以找到...问题是提供程序为什么会返回最后位置为 null。 - Saik Caskey
3
注意措辞? :S 你还是没有回答问题...另外,这不就是样板代码吗? 即使你在你的应用程序中使用它或将其用于研究论文,也并不意味着它属于你,或者说它不容易找到(咳咳: https://developer.android.com/training/location/change-location-settings.html .. 你的代码几乎完全相同)。除非一切正常工作,否则无法绝对保证最后的位置,而这种情况恰恰是这个问题所探讨的情况。 - Saik Caskey
@SaikCaskey,我保证在onLocationChange()回调函数中有最后位置。绝对不可能在空位置中调用onLocationChange()。如果onLocationChang()在每个我的位置请求中都提供新位置(我可以每2秒钟询问一次),我可以保证我正在获取我的新位置。 - Uddhav P. Gautam
@SaikCaskey,为什么位置返回null,这取决于系统。FocusedLocation Provider根据您当前的条件智能地切换到各种位置提供系统(如GPS、Wifi、Internet等)。这有点难以准确解释。但我已经解释了如何避免NullPointerException。 - Uddhav P. Gautam
1
“onLocationChange()在空位置中被调用绝对是零可能性”,这与问题(getLastLocation)实际上无关。 “为什么FusedLocationApi.getLastLocation为空”这个问题并没有得到“这是我的代码”和“这是如何避免空指针”的答案。“它取决于系统”是一个更好的答案,尽管对于遇到该问题的人来说,它与“这是我的代码”一样有用。 - Saik Caskey
显示剩余4条评论

0

请检查您的设备是否已经启用了位置

您可以从通知面板设置中启用它:

设置 -> 个人 -> 位置

我只使用了以下权限:

ACCESS_FINE_LOCATION

我的工作代码如下:

package com.go.findlocation;

import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
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;

public class MainActivity extends AppCompatActivity implements     GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleApiClient mGoogleApiClient = null;
//private Location mLocation = null;
private LocationManager mLocationManager = null;
private LocationRequest mLocationRequest = null;

private TextView tv1 = null;
private TextView tv2 = null;

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

    mLocationRequest = new LocationRequest();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(7000);
    mLocationRequest.setSmallestDisplacement(1);

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

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    tv1 = (TextView) findViewById(R.id.tv1);
    tv2 = (TextView) findViewById(R.id.tv2);
}

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

    Log.d("abc", "def");

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Log.d("ghi", "jkl");

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

    Log.d("connected", String.valueOf(mGoogleApiClient.isConnected()));

   /* if (mLocation != null) {
        tv1.setText(String.valueOf(mLocation.getLatitude()));
        tv2.setText(String.valueOf(mLocation.getLongitude()));
    } else
        Toast.makeText(this, "mLocation is null", Toast.LENGTH_SHORT).show();*/
}

@Override
public void onConnectionSuspended(int i) {

}

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

}

@Override
protected void onStart() {

    mGoogleApiClient.connect();
    super.onStart();
}

@Override
protected void onStop() {

    if (mGoogleApiClient.isConnected())
        mGoogleApiClient.disconnect();
    super.onStop();
}

@Override
public void onLocationChanged(Location location) {

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    Log.d("mno",String.valueOf(mGoogleApiClient.isConnected()));

if (location != null)
    {
        tv1.setText(String.valueOf(location.getLatitude()));
        tv2.setText(String.valueOf(location.getLongitude()));
        Toast.makeText(this, location.getLatitude()+" "+location.getLongitude(), Toast.LENGTH_SHORT).show();
    }
    else
        Toast.makeText(this, "location is null", Toast.LENGTH_SHORT).show();
}
}

你难道不觉得我已经尝试了所有可能的位置设置组合吗? - Can Poyrazoğlu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接