有没有办法获取隧道中的当前位置



我正在尝试获取当前位置,代码大部分时间都有效。但是位置更新无法在隧道中工作,尽管存在移动接收。

我已经尝试并通过以下两种方法进行了跟踪:

  Location NetLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
  Location GPSLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

隧道中似乎都没有更新。我已经与其他一些应用程序进行了交叉检查,并注意到位置服务在谷歌地图中正常工作。

整个功能链接在这里

那么无论如何我可以在隧道中获得正确的位置更新吗?

Google 有一个名为 fusedLocationAPI 的新 API,你可以尝试使用它。下面是示例代码 -

public class YourActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener  {
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static final int LOCATION_PERMISSION_CODE = 42;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash_screen);
    initGoogleApiClient();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_CODE);
    } else {
        getLastKnownLocation();
    }
}
@Override
public void onConnectionSuspended(int i) {
    mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == LOCATION_PERMISSION_CODE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            getLastKnownLocation();
        } else {
            startLocationActivity();
        }
    }
}
private void getLastKnownLocation() {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
private void initGoogleApiClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
}
@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}
@Override
protected void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();
}
}

这只是对可以做什么的更高层次的概述。可以通过添加位置更新间隔等来进一步自定义代码。您可以参考此网站 - https://developer.android.com/training/location/retrieve-current.html 以获取更多信息。

最新更新