我正在构建一个需要获取设备位置以及此处使用的代码的应用程序
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();
}
我几乎准备部署此应用程序,我想确定是否可以依靠此代码正确获取位置?如果没有,我应该做哪些改进?该代码运行良好,只是想知道在某些情况下我是否缺少某些东西或可能导致错误的东西。
答案 0 :(得分:0)
您可以使用上述代码从gps / network获取最后的已知位置。但不能确定您将获得当前位置,否则有时可能无法获得该位置。
如果您必须使用该位置,则应强制用户打开gps并获取当前位置。这可以通过使用LocationManager.requestLocationUpdates
答案 1 :(得分:0)
尝试以下代码,这是获取设备位置的标准方法,
Either a c
在您的活动中,如下所示调用GpsTracker类,
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 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));
}
}
并且不要忘记请求运行时权限。现在,您有了设备的当前位置纬度和经度。使用它从 GeoCoder 获取当前地址。