携帯電話の現在の位置を取得して地図上のマーカーとして表示するアプリを作成しようとしています。私はさまざまな種類のアンドロイド版のデバイスを使用しています。 Lollipopでうまくいき、現在の場所を表示しましたが、他のバージョンでは機能していません。地図のみが表示されます。私にはエラーメッセージが表示されないので、何が起きているのか分かりません。getLastKnownLocationがAndroid(6以上)の上位バージョンで動作しません
これは私が現在位置を取得するために使用されるコードです:
public void getLocation() {
try {
_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = _locationManager.isProviderEnabled(_locationManager.GPS_PROVIDER);
isNetworkEnabled = _locationManager.isProviderEnabled(_locationManager.NETWORK_PROVIDER);
if (_locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (_locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
// Ask for update
Location mobileLocation = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null) {
onLocationChanged(mobileLocation);
}
Location netLocation = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (netLocation != null) {
onLocationChanged(netLocation);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location userLocation) {
if (userLocation == null) {
Log.e(TAG, "NO Internet");
return;
}
_longitude = userLocation.getLongitude();
_latitude = userLocation.getLatitude();
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(_latitude, _longitude)).title("I'm Here"));
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(userLocation.getLatitude(), userLocation.getLongitude(), 1);
if (addresses.size() > 0)
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String fullLocation = "Longitude : " + userLocation.getLongitude() + "\nLatitude : " + userLocation.getLatitude() + "\n\nMy Current City is: " + cityName;
Log.e(TAG, "location : " + fullLocation);
}
ありがとうございました!