-1
我一直在嘗試使用融合位置API來獲取用戶的位置,完全像這裏所描述的https://developer.android.com/training/location/retrieve-current.html 但我沒有得到任何結果。有時它可以工作,但大多數情況下它不工作,並且這只是在虛擬設備上,真正的設備上沒有發生。 這裏是我的MainActivity.java:如何獲取用戶在android上的當前位置?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFusedLocationClient = 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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
10);
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
10);
// 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;
}
Log.v("","the beg");
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// ...
Log.v("", String.valueOf(location.getLatitude()));
Log.v("", String.valueOf(location.getLongitude()));
}
}
});
Log.v("","the end");
}
} 這我Android.m
@hassanitohajj in'onSucces'方法你有這個嗎? if(location!= null)Geocoder geoCoder = new Geocoder(getBaseContext(),Locale.getDefault());''你有一些'...'因此我只是在問。 –