我有以下代码可以获取设备的当前位置:
public class MapPlace extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
// location coordinates
double dLatitude = 0.0;
double dLongitude = 0.0;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_place);
if (mGoogleApiClient == null || !mGoogleApiClient.isConnected())
{
buildGoogleApiClient();
mGoogleApiClient.connect();
}
MapFragment mapF = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
if (mapF != null)
mapF.getMapAsync(this);
}
protected synchronized void buildGoogleApiClient()
{
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
@Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
dLatitude = mLastLocation.getLatitude();
dLongitude = mLastLocation.getLongitude();
}
}
}
此代码工作正常,但在某些设备中无法正常工作,要使用此代码获得成功,我必须重新启动设备或关闭并重新打开活动,所以我想避免这个问题。
作为推荐这个堆栈溢出的原因,我试图迁移到 LocationFusedLocation 来解决这个问题,但是我在 java 类中添加 GooglePlayServicesClient 实现时遇到了一些问题,因为正如这个链接所说,这个库暂时被弃用了。那么……我该怎么办?还有其他方法吗?