getLastLocation()
在我的6.0 Nexus 7平板電腦上手機位置關閉時返回NULL,但它在其他設備上無GPS功能。爲什麼是這樣以及如何解決它?我想保持GPS關閉,只需使用網絡獲取位置。Android:Google Fused位置在位置關閉時不起作用
下面是我使用來獲得位置類:
public class GPSCenter {
public static GoogleApiClient mGoogleApiClient;
public static Location mLastLocation;
private static Context mContext;
static GoogleApiClient.ConnectionCallbacks ccb = new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnectionSuspended(int arg0) {
}
@Override
public void onConnected(Bundle arg0) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_NO_POWER);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
};
static GoogleApiClient.OnConnectionFailedListener odfl = new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
};
public static synchronized void buildGoogleApiClient(Context c) {
try {
mContext = c;
mGoogleApiClient = new GoogleApiClient.Builder(c)
.addConnectionCallbacks(ccb)
.addOnConnectionFailedListener(odfl)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
} catch (Exception ex) {
Log.i("location", "error " + ex.toString());
ex.printStackTrace();
}
}
public static double getLatitude(Context c) {
try {
return mLastLocation.getLatitude();
} catch (Exception ex) {
return 0.0;
}
}
public static double getLongitude(Context c) {
try {
return mLastLocation.getLongitude();
} catch (Exception ex) {
return 0.0;
}
}
}
您是否找到任何解決方案 –
@ M.Yogeshwaran yes請檢查下面的答案:) –