web-dev-qa-db-ja.com

Androidでロケーションマネージャーの最新の既知の場所を取得するにはどうすればよいですか?

私はシンプルなlocation managerオブジェクトをデバイスのget lastKnownLocation()に使用していますが、取得しています- null object in returnだれでも理由を教えてくれますか?

コード:

public Location getLocation() {
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);        
    if (locationManager != null) {          
        Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnownLocationGPS != null) {             
            return lastKnownLocationGPS;
        } else {                
            Location loc =  locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
            System.out.println("1::"+loc);----getting null over here
            System.out.println("2::"+loc.getLatitude());
            return loc;
        }
    } else {            
        return null;
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.location);
    getLocation();-----calling service

 }

与えられた権限:

 <uses-permission Android:name="Android.permission.INTERNET" />
 <uses-permission Android:name="Android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission Android:name="Android.permission.READ_PHONE_STATE" />
 <uses-permission Android:name="Android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission Android:name="Android.permission.ACCESS_FINE_LOCATION" />

セットアップに欠けているものはありますか?位置情報サービスがデバイスでオンになっていることを確認しました。実際の例のリンクをいくつか入力してください

9
Aditi K

これに対する答えとして愚かなこと...私はデバイスを再起動しました...そしてそれはうまくいきました...位置情報のサービスが有効になっていて正しく機能していることを確認してください

3
Aditi K

場所の名前で場所を取得するために使用するものは

GPSTracker gpsTracker = new GPSTracker(CameraActivity.this);
String stringLatitude = "", stringLongitude = "", nameOfLocation="";
    if (gpsTracker.canGetLocation()) {
        stringLatitude = String.valueOf(gpsTracker.latitude);
        stringLongitude = String.valueOf(gpsTracker.longitude);
        nameOfLocation = ConvertPointToLocation(stringLatitude,stringLongitude);
    }

public String ConvertPointToLocation(String Latitude, String Longitude) {
    String address = "";
    Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
    try {
        List<Address> addresses = geoCoder.getFromLocation(
                Float.parseFloat(Latitude), Float.parseFloat(Longitude), 1);

        if (addresses.size() > 0) {
            for (int index = 0; index < addresses.get(0)
                    .getMaxAddressLineIndex(); index++)
                address += addresses.get(0).getAddressLine(index) + " ";
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return address;
}


GPSTracker.Java

package in.appology.lss;

import Java.io.IOException;
import Java.util.List;
import Java.util.Locale;

import Android.app.AlertDialog;
import Android.app.Service;
import Android.content.Context;
import Android.content.DialogInterface;
import Android.content.Intent;
import Android.location.Address;
import Android.location.Geocoder;
import Android.location.Location;
import Android.location.LocationListener;
import Android.location.LocationManager;
import Android.os.Bundle;
import Android.os.IBinder;
import Android.provider.Settings;
import Android.util.Log;

/**
 * Create this Class from tutorial :
 * http://www.androidhive.info/2012/07/Android-gps-location-manager-tutorial
 * 
 * For Geocoder read this :
 * http://stackoverflow.com/questions/472313/Android-reverse
 * -geocoding-getfromlocation
 * 
 */

public class GPSTracker extends Service implements LocationListener {
private final Context mContext;

// flag for GPS Status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

boolean canGetLocation = false;

Location location;
double latitude;
double longitude;

// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
                                                                // metters

// The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;

            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                Log.d("Network", "Network");

                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    updateGPSCoordinates();
                }
            }

            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    Log.d("GPS Enabled", "GPS Enabled");

                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        updateGPSCoordinates();
                    }
                }
            }
        }
    } catch (Exception e) {
        // e.printStackTrace();
        Log.e("Error : Location",
                "Impossible to connect to LocationManager", e);
    }

    return location;
}

public void updateGPSCoordinates() {
    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    }
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 */

public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    return latitude;
}

/**
 * Function to get longitude
 */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS");

    // Setting Dialog Message
    alertDialog
            .setMessage("Please enable location in settings for accurate results!");

    // On Pressing Setting button
    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

    // On pressing cancel button
    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertDialog.show();
}

/**
 * Get list of address by latitude and longitude
 * 
 * @return null or List<Address>
 */
public List<Address> getGeocoderAddress(Context context) {
    if (location != null) {
        Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude,
                    longitude, 1);
            return addresses;
        } catch (IOException e) {
            // e.printStackTrace();
            Log.e("Error : Geocoder", "Impossible to connect to Geocoder",
                    e);
        }
    }

    return null;
}

/**
 * Try to get AddressLine
 * 
 * @return null or addressLine
 */
public String getAddressLine(Context context) {
    List<Address> addresses = getGeocoderAddress(context);
    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String addressLine = address.getAddressLine(0);

        return addressLine;
    } else {
        return null;
    }
}

/**
 * Try to get Locality
 * 
 * @return null or locality
 */
public String getLocality(Context context) {
    List<Address> addresses = getGeocoderAddress(context);
    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String locality = address.getLocality();

        return locality;
    } else {
        return null;
    }
}

/**
 * Try to get Postal Code
 * 
 * @return null or postalCode
 */
public String getPostalCode(Context context) {
    List<Address> addresses = getGeocoderAddress(context);
    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String postalCode = address.getPostalCode();

        return postalCode;
    } else {
        return null;
    }
}

/**
 * Try to get CountryName
 * 
 * @return null or postalCode
 */
public String getCountryName(Context context) {
    List<Address> addresses = getGeocoderAddress(context);
    if (addresses != null && addresses.size() > 0) {
        Address address = addresses.get(0);
        String countryName = address.getCountryName();

        return countryName;
    } else {
        return null;
    }
}

@Override
public void onLocationChanged(Location location) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}
}
2
Archit Jain
            // Get the location from the given provider
            Location location = locationManager
                    .getLastKnownLocation(provider);

            locationManager.requestLocationUpdates(provider, 1000, 1, this);
1

最後の場所を取得する前に、現在の場所を取得したい場合は、nullかどうかを確認してください。 FusedLocationProviderClient を使用する場合は、最後の場所を設定しないと、使用する前に次のように追加します。

実装 'com.google.Android.gms:play-services-location:16.0.0'

build.gradle(Module:app)で、アクティビティを作成するときにメソッドzoomMyCuurentLocation()を呼び出します。

private void zoomMyCuurentLocation() {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    if (location != null) {
        double lat = location.getLatitude();
        double longi = location.getLongitude();
        LatLng latLng = new LatLng(lat,longi);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.f));
        Log.d(TAG, "zoomMyCuurentLocation: location not null");
    } else {
        setMyLastLocation();
    }
}

private void setMyLastLocation() {
    Log.d(TAG, "setMyLastLocation: excecute, and get last location");
    FusedLocationProviderClient 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){
                double lat = location.getLatitude();
                double longi = location.getLongitude();
                LatLng latLng = new LatLng(lat,longi);
                Log.d(TAG, "MyLastLocation coordinat :"+latLng);
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.f));
            }
        }
    });
}
0
im-o

以下は、私が最後の場所を取得しようとしている方法です。

private void setUpMap(){
    //Location location = mMap.getMyLocation();
    mMap.setMyLocationEnabled(true);
    //mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
             mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("My Location"));
             mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),10));
             mMap.setOnMyLocationChangeListener(null);
        }
    });
}
0
Mayur