使用网上最常用的几种方式获取经纬度时, Location
一直为 null, 后来找到一篇文章, 根据文章代码成功获取到经纬度, 有些地方不是很懂, 先记录下来.
public class MainActivity extends AppCompatActivity {
TextView textView;
LocationRequest mLocationRequest;
final long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
final long FASTEST_INTERVAL = 2000; /* 2 sec */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
// 动态授权
Disposable disposable = rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION).subscribe(aBoolean -> {
if (aBoolean) {
startLocationUpdates();
} else {
Logger.w("拒绝授权");
}
});
}
protected void startLocationUpdates() {
// Create the location request to start receiving updates
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(locationSettingsRequest);
// 检查
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Logger.w("用户未授权");
return;
}
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
LocationServices.getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
onLocationChanged(locationResult.getLastLocation());
}
},
Looper.myLooper());
}
private void onLocationChanged(Location location) {
// New location has now been determined
textView.setText(String.format("经度: %.2f\n维度: %.2f", location.getLongitude(), location.getLatitude()));
}
}
用到的依赖有:
// https://mvnrepository.com/artifact/com.orhanobut/logger
implementation group: 'com.orhanobut', name: 'logger', version: '2.2.0'
// 位置服务
implementation "com.google.android.gms:play-services-location:17.0.0"
// 权限请求框架
// RxJava
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.jakewharton.rxbinding2:rxbinding:2.0.0'
//rxpermissions
compile 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.4@aar'
效果图: