Android - 最简单的获取位置的方式

时间:2017-11-22 19:15:19

标签: java android location

侨!我有一个需要当前位置的Activity,因此用户可以看到哪些对象靠近他。

好吧,我会疯狂使用GoogleApiClient,FusedLocation,回调等等,我得到的唯一结果是getLastLocation返回null

我的活动实施GoogleApiClient.ConnectionCallbacksGoogleApiClient.OnConnectionFailedListener

OnCreate我致电getLocation(),就像这样:

private void getLocation(){
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(60*1000);
    locationRequest.setFastestInterval(10*1000);
    mFusedLocationApi = LocationServices.FusedLocationApi;
    gApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    if (gApiClient != null) {
        gApiClient.connect();
    }
}

我也有:

@Override
protected void onStart() {
    super.onStart();
    if (gApiClient != null) {
        gApiClient.connect();
    }
}

@Override
protected void onStop() {
    gApiClient.disconnect();
    super.onStop();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.w("ADVSEARCH","Error on connection failed");
}

@Override
public void onConnectionSuspended(int i) {
    Log.w("ADVSEARCH","Error on connection suspended");
}

@Override
public void onConnected(Bundle bundle) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

        //lastlocation = LocationServices.FusedLocationApi.getLastLocation(gApiClient);


        mFusedLocationApi.requestLocationUpdates(gApiClient, locationRequest, new com.google.android.gms.location.LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                lastlocation = location;
            }
        });
    }
    lastlocation = LocationServices.FusedLocationApi.getLastLocation(gApiClient);
}

是的,在OnCreate我检查权限。最低API 16,目标API 25。 每当我第一次崩溃时打开应用程序,因为我在空对象上使用distanceTo。我错过了什么?我搜索得越多,就越困惑。

1 个答案:

答案 0 :(得分:1)

我认为这可能是不同的事情,例如您没有在Manifest文件中设置所有内容,或者您​​在运行时没有权限(您需要在应用程序首次启动时允许此操作,或者在应用程序设置中手动设置此项)。试试这个......

<强>的build.gradle

implementation 'com.google.android.gms:play-services-location:11.6.0'
Activity.java

中的

private static final int PERMISSION_REQUEST_FINE_LOCATION = 1;

private void getLocationRequest() {
    FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
    if (!checkPermission()) {
        getLocationPermissions();
        return;
    }
    client.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // Got last known location. In some rare situations this can be null.
                    if (location != null) {
                        // Logic to handle location object
                        Log.e("TAG", "location = " + location);
                    } else {
                        Log.e("TAG", "not successful");
                    }
                }
            });
}

private boolean checkPermission() {
    return isGranted(ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION)) &&
            isGranted(ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION));
}

@TargetApi(Build.VERSION_CODES.M)
private void getLocationPermissions() {
    requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
            PERMISSION_REQUEST_FINE_LOCATION);
}

@Override
public void onRequestPermissionsResult(int code, @Nullable String permissions[], @Nullable int[] results) {
    switch (code) {
        case PERMISSION_REQUEST_FINE_LOCATION:
            if (isPermissionGranted(results)) {
                getLocationRequest();
            }
    }
}

private boolean isPermissionGranted(int[] results) {
    return results != null && results.length > 0 && isGranted(results[0]);
}

private boolean isGranted(int permission) {
    return permission == PackageManager.PERMISSION_GRANTED;
}

这会询问您是否尚未设置权限,并在肯定的对话结果后再次调用getLocationRequest

并检查您的 AndroidManifest.xml

中是否包含此内容
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-feature android:name="android.hardware.location.gps" />
<uses-feature android:name="android.hardware.location.network" />

因为你必须满足你的需要(精细或粗糙的地方等)。

希望这能让你走上正轨;)