【发布时间】:2026-01-23 23:55:01
【问题描述】:
我有以下代码可以获取设备的当前位置:
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();
}
}
}
此代码工作正常,但在某些设备上无法正常工作,要使用此代码获得成功,我必须重新启动设备或关闭并重新打开活动,所以我想避免这个问题。
正如推荐的stack overflow aswer,我尝试迁移到LocationFusedLocation 来解决这个问题,但是我在Java 类中添加GooglePlayServicesClient 实现时遇到了一些问题,因为正如link 所说,这个库暂时不推荐使用。 那么……我该怎么办?还有其他方法吗?
【问题讨论】:
-
第二个链接的该问题的答案向您展示了如何以新方式注册位置更新,因此请遵循
-
看来您只需将所有代码从 onCreate()(setContentView() 除外)移至 onResume(),您的问题就会消失。
-
@DanielNugent 好的,我会试试的
标签: android locationlistener android-fusedlocation