0

我正在构建一个应用程序,我需要在其中获取设备位置和我使用的代码

Double latitude = 0.0;
    Double longitude = 0.0;
    String TAG = "HomeActivity";
    Location gpsLoc = null, networkLoc = null, finallLoc = null;
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED){
                Toast.makeText(this,"Not Granted",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(this,"Granted",Toast.LENGTH_LONG).show();
            }
            try{
                gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }catch(Exception e){
                e.printStackTrace();
            }
            if(gpsLoc!= null){
                finallLoc = gpsLoc;
                latitude = finallLoc.getLatitude();
                longitude = finallLoc.getLongitude();
            }else if(networkLoc!=null){
                finallLoc = networkLoc;
                latitude = finallLoc.getLatitude();
                longitude = finallLoc.getLongitude();
            }else{
                latitude = 0.0;
                longitude=0.0;
            }
            try{
                Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());
                List<Address> addresses = geocoder.getFromLocation(latitude,longitude,1);
                if(addresses!=null && addresses.size()>0){
                    String country = addresses.get(0).getCountryName();
                    String address = addresses.get(0).getAddressLine(0);
                    String city = addresses.get(0).getLocality();

                }

            }catch (Exception e){
                e.printStackTrace();
            }

我几乎准备好部署这个应用程序,我想确定我是否可以依靠这段代码来正确获取位置?如果没有,我应该做什么样的改进?代码工作正常只是想知道我是否缺少某些东西或在某些条件下可能导致错误的东西。

4

2 回答 2

0

您可以使用上述代码从 gps/network 获取最后一个已知位置。但不确定您是否会获得当前位置,或者有时您可能无法获得该位置。

如果该位置对您来说是强制性的,那么您应该强制用户打开 gps 并获取当前位置。这可以通过使用来实现LocationManager.requestLocationUpdates

请点击链接https://stackoverflow.com/a/10917500/3886504

于 2019-05-06T19:47:06.113 回答
0

试试下面的代码这是如何获取设备位置的标准方法,

public class GpsTracker extends Service implements LocationListener {
private final Context mContext;
Location location;
double latitude;
double longitude;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
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 {
            try {
                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);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

                // 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, (android.location.LocationListener) this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }

            } catch (SecurityException se) {
                Log.d("ERROR", se.toString());
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }
    return latitude;
}


public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }
    return longitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

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

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not Enabled.");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        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() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onLocationChanged(Location location) {

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

并在您的活动中调用 GpsTracker 类,如下所示,

 GpsTracker gps = new GpsTracker(getActivity());
    if (gps.canGetLocation()) {
        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        location = new LatLng(latitude, longitude);
        geoLocation = new GeoLocation(latitude, longitude);
        Log.d("*******latitude", String.valueOf(latitude));
        Log.d("*******longitude", String.valueOf(longitude));

    }
}

并且不要在清单文件中添加权限,

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

并且不要忘记请求运行时权限。现在您有了设备当前位置latitudelongitude。使用它从GeoCoder获取当前地址。

于 2019-05-07T06:24:43.653 回答