我正在尝试获取当前位置,代码大部分时间都在运行。但是,尽管移动接收存在,但位置更新无法在隧道中发挥作用。
我尝试过并通过以下两种方法进行追踪:
Location NetLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location GPSLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
似乎都没有在隧道中更新。我已经与其他一些应用程序进行了交叉检查,并注意到位置服务在谷歌地图中正常运行。
那么无论如何我可以在隧道中获得正确的位置更新吗?
答案 0 :(得分:1)
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获取更多信息。