您的位置:首页 > 移动开发 > Android开发

Android--使用手机GPS获取经纬度

2015-11-03 18:04 896 查看
有很多应用在打开应用的时候,就需要去获取当前手机的地址位置并且显示出地名等,现在介绍一种方法通过手机内置的GPS获取当前位置的经纬度.

思路: 首先判断手机当前是否打开GPS功能-->如果没有打开就通过代码帮助用户强制打开手机GPS功能-->根据手机GPS获取手机当前位置的经纬度.

注意:打开gps和访问网络的权限.

1.上代码:
1.1判断手机是否打开GPS-需要使用到Android系统的LocationManager对象.

/**
* 判断手机GPS是否开启
* @param mainActivity
* @return
*/
public boolean isOpen(Context context) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//通过GPS卫星定位,定位级别到街
boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//通过WLAN或者移动网络确定位置
boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps || network) {
return true;
}
return false;
}


1.2用户未打开GPS,帮助用户打开该功能.

/**
* 开启手机GPS
*/
public void openGPS(Context context) {
Intent GPSIntent = new Intent();
GPSIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvide");
GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
GPSIntent.setData(Uri.parse("custom:3"));

try {
//使用PendingIntent发送广播告诉手机去开启GPS功能
PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
}


1.3使用手机的GPS功能获取当前位置的经纬度

/**
* GPS功能已经打开-->根据GPS去获取经纬度
*/
public void getGPSConfi() {
Location location;
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
tv_content.setText("经纬度:" + latitude + "--" + longitude);
} else {
tv_content.setText("未获取到经纬度数据");
}
}


2.需要的权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

3.界面很简单,就不贴代码了,一个按钮和一个文本框显示经纬度
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  gps 经纬度