public class LocationActivity extends FragmentActivity {
private TextView mLatLng;
private TextView mAddress;
private Button mFineProviderButton;
private LocationManager mLocationManager;
private Handler mHandler;
private boolean mGeocoderAvailable;
private boolean mUseFine;
private String Add,Lat;
// Keys for maintaining UI states after rotation.
private static final String KEY_FINE = "use_fine";
// UI handler codes.
private static final int UPDATE_ADDRESS = 1;
private static final int UPDATE_LATLNG = 2;
private static final int TEN_SECONDS = 10000;
private static final int TEN_METERS = 10;
private static final int TWO_MINUTES = 1000 * 60 * 2;
/**
* This sample demonstrates how to incorporate location based services in your app and
* process location updates. The app also shows how to convert lat/long coordinates to
* human-readable addresses.
*/
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Restore apps state (if exists) after rotation.
if (savedInstanceState != null) {
mUseFine = savedInstanceState.getBoolean(KEY_FINE);
} else {
mUseFine = false;
}
mLatLng = (TextView) findViewById(R.id.latlng);
mAddress = (TextView) findViewById(R.id.address);
// Receive location updates from the fine location provider (gps) only.
mFineProviderButton = (Button) findViewById(R.id.provider_fine);
// The isPresent() helper method is only available on Gingerbread or above.
mGeocoderAvailable =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();
// Handler for updating text fields on the UI like the lat/long and address.
mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_ADDRESS:
mAddress.setText((String) msg.obj);
Add=(String) msg.obj;
break;
case UPDATE_LATLNG:
mLatLng.setText((String) msg.obj);
Lat=(String) msg.obj;
break;
}
}
};
// Get a reference to the LocationManager object.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
// Restores UI states after rotation.
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_FINE, mUseFine);
}
@Override
protected void onResume() {
super.onResume();
setup();
}
@Override
protected void onStart() {
super.onStart();
// Check if the GPS setting is currently enabled on the device.
// This verification should be done during onStart() because the system calls this method
// when the user returns to the activity, which ensures the desired location provider is
// enabled each time the activity resumes from the stopped state.
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
// Build an alert dialog here that requests that the user enable
// the location services, then when the user clicks the "OK" button,
// call enableLocationSettings()
new EnableGpsDialogFragment().show(getSupportFragmentManager(), "enableGpsDialog");
}
}
// Method to launch Settings
private void enableLocationSettings() {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
// Stop receiving location updates whenever the Activity becomes invisible.
@Override
protected void onStop() {
super.onStop();
mLocationManager.removeUpdates(listener);
}
// Set up fine and/or coarse location providers depending on whether the fine provider or
// both providers button is pressed.
private void setup() {
Location gpsLocation = null;
mLocationManager.removeUpdates(listener);
mLatLng.setText(R.string.unknown);
mAddress.setText(R.string.unknown);
// Get fine location updates only.
if (mUseFine) {
mFineProviderButton.setBackgroundResource(R.drawable.button_active);
// Request updates from just the fine (gps) provider.
gpsLocation = requestUpdatesFromProvider(
LocationManager.GPS_PROVIDER, R.string.not_support_gps);
// Update the UI immediately if a location is obtained.
if (gpsLocation != null) updateUILocation(gpsLocation);
}
}
/**
* Method to register location updates with a desired location provider. If the requested
* provider is not available on the device, the app displays a Toast with a message referenced
* by a resource id.
*
* @param provider Name of the requested provider.
* @param errorResId Resource id for the string message to be displayed if the provider does
* not exist on the device.
* @return A previously returned {@link android.location.Location} from the requested provider,
* if exists.
*/
private Location requestUpdatesFromProvider(final String provider, final int errorResId) {
Location location = null;
if (mLocationManager.isProviderEnabled(provider)) {
mLocationManager.requestLocationUpdates(provider, TEN_SECONDS, TEN_METERS, listener);
location = mLocationManager.getLastKnownLocation(provider);
} else {
Toast.makeText(this, errorResId, Toast.LENGTH_LONG).show();
}
return location;
}
// Callback method for the "fine provider" button.
public void useFineProvider(View v) {
mUseFine = true;
setup();
}
// Callback method for the "both providers" button.
public void useCoarseFineProviders(View v) {
mUseFine = false;
setup();
}
private void doReverseGeocoding(Location location) {
// Since the geocoding API is synchronous and may take a while. You don't want to lock
// up the UI thread. Invoking reverse geocoding in an AsyncTask.
(new ReverseGeocodingTask(this)).execute(new Location[] {location});
}
private void updateUILocation(Location location) {
// We're sending the update to a handler which then updates the UI with the new
// location.
Message.obtain(mHandler,
UPDATE_LATLNG,
location.getLatitude() + ", " + location.getLongitude()).sendToTarget();
// Bypass reverse-geocoding only if the Geocoder service is available on the device.
if (mGeocoderAvailable) doReverseGeocoding(location);
}
private final LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// A new location update is received. Do something useful with it. Update the UI with
// the location update.
updateUILocation(location);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
/** Determines whether one Location reading is better than the current Location fix.
* Code taken from
* http://developer.android.com/guide/topics/location/obtaining-user-location.html
*
* @param newLocation The new Location that you want to evaluate
* @param currentBestLocation The current Location fix, to which you want to compare the new
* one
* @return The better Location object based on recency and accuracy.
*/
protected Location getBetterLocation(Location newLocation, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return newLocation;
}
// Check whether the new location fix is newer or older
long timeDelta = newLocation.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved.
if (isSignificantlyNewer) {
return newLocation;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return currentBestLocation;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (newLocation.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(newLocation.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return newLocation;
} else if (isNewer && !isLessAccurate) {
return newLocation;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return newLocation;
}
return currentBestLocation;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
// AsyncTask encapsulating the reverse-geocoding API. Since the geocoder API is blocked,
// we do not want to invoke it from the UI thread.
private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
Context mContext;
public ReverseGeocodingTask(Context context) {
super();
mContext = context;
}
@Override
protected Void doInBackground(Location... params) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
Location loc = params[0];
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
// Update address field with the exception.
Message.obtain(mHandler, UPDATE_ADDRESS, e.toString()).sendToTarget();
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
// Update address field on UI.
Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();
}
return null;
}
}
/**
* Dialog to prompt users to enable GPS on the device.
*/
private class EnableGpsDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.enable_gps)
.setMessage(R.string.enable_gps_dialog)
.setPositiveButton(R.string.enable_gps, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
enableLocationSettings();
}
})
.create();
}
}
}
分享到:
相关推荐
标题“GPS定位得到经纬度”涉及的是全球定位系统(Global Positioning System,GPS)在获取地理位置信息中的应用,特别是如何通过GPS技术获取到地球表面某一点的经度和纬度坐标。这一过程对于各种需要定位服务的应用...
GPS定位是通过接收多个卫星信号来确定设备的精确地理位置。在Android中,我们可以使用`LocationManager`服务来请求GPS定位服务。首先,需要在AndroidManifest.xml文件中添加必要的权限: ```xml ``` 然后,...
本篇文章将深入探讨如何实现GPS定位功能,检测GPS状态,并实时采集当前经纬度信息。 首先,我们需要理解GPS定位的基本原理。GPS系统由24颗以上的卫星组成,这些卫星不断发送信号到地球表面。当用户设备(如智能手机...
### GPS经纬度转换为百度经纬度 在地理信息系统(GIS)和定位技术中,不同的地图服务提供商使用不同的坐标系统来表示地理位置。例如,GPS设备通常使用的是WGS-84坐标系,而百度地图则使用了经过加密处理的BD-09坐标...
"GPS定位获取经纬度"这个主题涉及到如何在应用中检测并利用GPS服务来获取用户的精确地理位置坐标,即经度和纬度。这里我们将深入探讨相关知识点。 首先,我们需要了解GPS的基本原理。GPS是一个全球卫星导航系统,...
xamarin android中使用gps定位获取经纬度,入门的简单介绍:http://blog.csdn.net/kebi007/article/details/74936979
中国各省市地区3180个城市GPS坐标经纬度数据Jsons格式
本示例将深入探讨如何通过GPS获取iPhone的经纬度坐标,以及相关的知识点。 首先,我们需要导入Core Location框架,它是苹果提供的用于地理位置服务的核心框架。在Swift中,我们可以在代码顶部添加以下代码来引入: ...
其中,ACCESS_FINE_LOCATION用于获取更精确的GPS定位,而ACCESS_COARSE_LOCATION则可以获取基于网络的粗略位置。 接下来,创建一个工具类,用于获取GPS经纬度。我们可以创建一个名为`LocationUtil`的Java类,包含一...
在Android平台上,开发一款应用以实现GPS定位并获取经纬度值是常见的需求。这个"Android应用实现GPS定位返回经纬度Demo"就是一个实例,它演示了如何有效地从Android系统的Location服务中获取地理位置信息。下面我们...
在Android平台上,开发一款应用程序以实现手机原生GPS定位功能并循环获取经纬度坐标,将这些数据存储到SQLite数据库中,是一项常见的需求。这个过程涉及到了Android系统服务、位置API、时间戳处理以及本地数据库操作...
本篇将详细探讨如何解决“location返回为null”这一常见问题,以及如何进行有效的室外GPS定位测试。 首先,我们需要了解Android系统中的定位服务框架。Android提供了LocationManager服务,它是获取地理位置信息的...
在实际应用中,可能需要处理位置权限的动态请求、位置更新频率的调整、网络定位与GPS定位的结合(称为“融合定位”)等问题,以提高用户体验和节省资源。 总结,获取Android设备的GPS经纬度涉及权限设置、...
MySQL是一个高效、可靠的开源关系型数据库管理系统,用于存储GPS定位数据。在系统中,可能需要创建一个包含地理位置信息(如经度、纬度、时间戳等)的表,并通过PHP编写SQL查询语句来插入、更新或检索这些数据。确保...
在iOS开发中,使用Core Location框架进行GPS定位。首先,需要在Info.plist文件中声明定位权限: ```xml <key>NSLocationWhenInUseUsageDescription 需要您的位置信息来提供服务。 ``` 然后,导入CoreLocation框架...
在IT领域,GPS(全球定位系统)模块是用于获取地理位置信息的重要硬件组件,它通过接收卫星信号来计算设备的位置。本篇文章将详细讲解如何通过串口连接GPS模块,实时读取经纬度数据。 首先,我们需要了解GPS模块的...
在Android设备上,我们可以利用内置的GPS传感器或者网络定位服务来获取经纬度坐标。 1. **开启GPS服务** 在Android中,使用LocationManager服务来管理位置更新。首先,在AndroidManifest.xml中添加权限: ```xml `...
1. **单片机控制GPS定位系统**:利用51单片机实现对GPS系统的控制,接收并处理经纬度、时间等信息。 2. **触摸式定时电路**:介绍一种基于555定时器的触摸式电路设计,适用于楼梯照明场景。 3. **GPS系统原理与应用*...
- **WGS84**:世界大地坐标系统,是国际标准的地理坐标系,广泛应用于GPS定位系统,其经纬度是全球通用的。WGS84坐标系以地球质心为原点,参考椭球体为WGS84椭球体。 - **BD-09**:这是百度地图自定义的坐标系,...
在Android开发中,GPS定位是实现移动应用地理位置功能的关键技术。本教程将深入探讨如何在Android应用程序中使用GPS获取经纬度坐标,并将其显示在TextView中。以下是一系列详细步骤和相关知识点: 1. **...