我在手机上尝试。它始终返回null。为什么?(已授予所有权限.ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
Toast.makeText(MainActivity.this, "Location: "+location, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "null", Toast.LENGTH_SHORT).show();
}
});```
依存关系:
dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.google.android.gms:play-services-location:16.0.0'}
表现:
问题来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
永远不能保证您会从中获得位置getLastLocation()。通常,这意味着没有任何应用程序没有使用GPS来获取您的位置,因此不会缓存任何内容。
通常,您要做的就是打开google地图,或者在拥有锁定后会缓存位置的信息
回答来源:Stack Overflow