实现定位的方法有两种,一种是使用系统提供的定位API,另一种是使用三方地图的定位功能。
系统自带的定位API只能获取到经纬度信息,具体的位置信息获取不到,三方的地图定位可以获取到所有的信息。
系统的API实现(简单定位):
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = LocationManager.NETWORK_PROVIDER;// 指定LocationManager的定位方法
//NETWORK_PROVIDER 网络定位、GPS_PROVIDER GPS定位
Location location = locationManager.getLastKnownLocation(provider);// 调用getLastKnownLocation()方法获取当前的位置信息
double lat = location.getLatitude();//获取纬度
double lng = location.getLongitude();//获取经度
在AndroidManifest中添加权限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
百度地图提供的定位方法:
1、百度地图开发者平台注册账户及创建应用
2、在AndroidManifest中添加
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="你的API_KEY" />
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote"/>
添加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!--获取设备网络状态,禁用后无法获取网络状态-->
<uses-permission android:name="android.permission.INTERNET"/>
<!--网络权限,当禁用后,无法进行检索等相关业务-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!--读取设备硬件信息,统计数据-->
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<!--读取系统信息,包含系统版本等信息,用作统计-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--获取设备的网络状态,鉴权所需网络代理-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--允许sd卡写权限,需写入地图数据,禁用后无法显示地图-->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
3、添加jar包
将下载的jar包放到相应的位置如下:
在build.gradle中添加
android {
.....
defaultConfig {
.....
ndk {
abiFilters "armeabi" // 指定要ndk需要兼容的架构(这样其他依赖包里mips,x86,armeabi,arm-v8之类的so会被过滤掉)
}
}
准备工作OK了,开始干活。
自定义的开启定位的类,在这里做了一个时间的限制,超过1分钟位置信息就更新:
import android.content.Context;
import android.util.Log;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import java.util.List;
public class LocationUtils {
private static LocationClient mLocationClient;
public static BDLocationListener myListener = new MyLocationListener();
public static void initLocation(Context context) {
mLocationClient = new LocationClient(context); // 声明LocationClient类
mLocationClient.registerLocationListener(myListener); // 注册监听函数
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
option.setCoorType("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系
int span = 0;
option.setScanSpan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
option.setIsNeedAddress(true);//可选,设置是否需要地址信息,默认不需要
option.setOpenGps(true);//可选,默认false,设置是否使用gps
option.setLocationNotify(true);//可选,默认false,设置是否当GPS有效时按照1S/1次频率输出GPS结果
option.setIsNeedLocationDescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近”
option.setIsNeedLocationPoiList(true);//可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到
option.setIgnoreKillProcess(false);//可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死
option.SetIgnoreCacheException(false);//可选,默认false,设置是否收集CRASH信息,默认收集
option.setEnableSimulateGps(false);//可选,默认false,设置是否需要过滤GPS仿真结果,默认需要
mLocationClient.setLocOption(option);
mLocationClient.start();
}
public static LocationBean getLocation() {
if (System.currentTimeMillis() - MyApplication.time > 60000) {//设置1分钟超时
mLocationClient.start();
return null;
} else {
return MyApplication.locationData;
}
}
public static void unRegisterListener(){
mLocationClient.unRegisterLocationListener(myListener);
}
public static void startLocation() {
if (mLocationClient != null) {
System.out.println("开启定位");
mLocationClient.start();
}
}
public static class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
LocationBean bean;//自定义的位置信息的对象
System.out.println("定位信息返回");
// if (location.getLocType() == BDLocation.TypeGpsLocation || location.getLocType() == BDLocation.TypeNetWorkLocation || location.getLocType() == BDLocation.TypeOffLineLocation) {
bean = new LocationBean();
bean.setLAT(location.getLatitude());
bean.setLNG(location.getLongitude());
bean.setPROVINCE(location.getProvince());//获取省份
bean.setCITY(location.getCity()); //获取城市
bean.setCOUNTY(location.getDistrict()); //获取区县
bean.setSTREET(location.getAddrStr());
// } else {
// System.out.println("返回位置信息为null");
// bean = null;
// }
MyApplication.locationData = bean;//存储位置信息
MyApplication.time = System.currentTimeMillis();
StringBuffer sb = new StringBuffer(256);
sb.append("time : ");
sb.append(location.getTime());
sb.append("\nerror code : ");
sb.append(location.getLocType());
sb.append("\nlatitude : ");
sb.append(location.getLatitude());
sb.append("\nlontitude : ");
sb.append(location.getLongitude());
sb.append("\nradius : ");
sb.append(location.getRadius());
if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
sb.append("\nspeed : ");
sb.append(location.getSpeed());// 单位:公里每小时
sb.append("\nsatellite : ");
sb.append(location.getSatelliteNumber());
sb.append("\nheight : ");
sb.append(location.getAltitude());// 单位:米
sb.append("\ndirection : ");
sb.append(location.getDirection());// 单位度
sb.append("\naddr : ");
sb.append(location.getAddrStr());
sb.append("\ndescribe : ");
sb.append("gps定位成功");
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
sb.append("\naddr : ");
sb.append(location.getAddrStr());
//运营商信息
sb.append("\noperationers : ");
sb.append(location.getOperators());
sb.append("\ndescribe : ");
sb.append("网络定位成功");
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
sb.append("\ndescribe : ");
sb.append("离线定位成功,离线定位结果也是有效的");
} else if (location.getLocType() == BDLocation.TypeServerError) {
sb.append("\ndescribe : ");
sb.append("服务端网络定位失败,可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com,会有人追查原因");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
sb.append("\ndescribe : ");
sb.append("网络不同导致定位失败,请检查网络是否通畅");
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
sb.append("\ndescribe : ");
sb.append("无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机");
}
sb.append("\nlocationdescribe : ");
sb.append(location.getLocationDescribe());// 位置语义化信息
List<Poi> list = location.getPoiList();// POI数据
if (list != null) {
sb.append("\npoilist size = : ");
sb.append(list.size());
for (Poi p : list) {
sb.append("\npoi= : ");
sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
}
}
System.out.println("BaiduLocati: " + sb.toString());
Log.e("BaiduLocati", sb.toString());
}
}
}
使用:在获取位置信息前初始化,例如:
public class MyApplication extends Application {
public static LocationBean locationData = null;
public static long time = 0;
@Override
public void onCreate() {
super.onCreate();
LocationUtils.initLocation(getApplicationContext());
}
获取位置:
LocationBean location = LocationUtils.getLocation();
if (location == null) {
Toast.makeText(this, "无位置信息,定位时间" + MyApplication.time, Toast.LENGTH_SHORT).show();
}else{
//处理位置信息
}
注意:需要动态申请权限。