我尝试使用互联网获取用户的坐标(但没有GPS)
清单:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
在onCreate()
方法中,我发起了client
:
if (client == null) {
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
According to `developer.android.com`'s docs:
@Override
protected void onStart() {
client.connect();
super.onStart();
}
@Override
protected void onStop() {
client.disconnect();
super.onStop();
}
onConnected
:
@Override
public void onConnected(@Nullable Bundle bundle) {
System.out.println("connected");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
location = LocationServices.FusedLocationApi.getLastLocation(client);
if (location != null) {
System.out.println("location " + location.getLatitude());
} else {
System.out.println("location " + "empty");
}
}
因此,当我的GPS打开时,我可以看到日志中的坐标,但是当我尝试通过互联网(3g或Wi-Fi并不重要)时,我的Location
是{ {1}}。
我错过了什么?也许我走错了路?
P.S。尝试使用null
进行相同的操作会产生相同的结果。
答案 0 :(得分:1)
试试这个
首先像这样定义LocationRequest对象
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
然后在onConnected()里面添加这个
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
然后覆盖onLocationChanged()方法
@Override
public void onLocationChanged(Location location) {
//Here you can use location.getLatitude() etc
}