在 UniApp 中实现后台保活定位能力通常涉及几个关键步骤,包括获取定位权限、实现定位功能、处理后台定位以及确保应用在后台时能够持续定位。以下是一个基本的指南:
1. 系统定位
IOS系统
首先开启系统定位能力
需要配置后台运行能力
注意:本地测试需要打自定义基座包 才行
代码实现(可进行定时获取,实现后台实时定位能力)
uni.getLocation({
type: 'wgs84',
success: function(res) {
console.log('系统当前地址' + JSON.stringify(res))
}
});
安卓系统
/utils/location.js
export default {
//检测是否开启系统定位权限
hasLocationPermission() {
let system = uni.getSystemInfoSync();
if (system.platform === 'android') { //安卓
let context = plus.android.importClass("android.content.Context");
let locationManager = plus.android.importClass("android.location.LocationManager");
let main = plus.android.runtimeMainActivity();
let service = main.getSystemService(context.LOCATION_SERVICE);
//已开启系统定位服务功能
if (service.isProviderEnabled(locationManager.GPS_PROVIDER)) return true;
else { //未开启引导开启
uni.showModal({
title: '友情提示',
content: '请开启位置服务功能',
success: e => {
if (e.confirm) {
//打开手机系统gps定位设置页面
let Intent = plus.android.importClass('android.content.Intent');
let Settings = plus.android.importClass('android.provider.Settings');
let intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
main.startActivity(intent);
}
}
})
// return false
}
} else if (system.platform === 'ios') { //ios
let cllocationManger = plus.ios.import("CLLocationManager");
let enable = cllocationManger.locationServicesEnabled();
let status = cllocationManger.authorizationStatus();
plus.ios.deleteObject(cllocationManger);
if (enable && status != 2) return true; //已开启定位功能
else {
// return false
uni.showModal({
title: '友情提示',
content: '请前往设置-定位服务打开定位服务功能',
success: e => {
if (e.confirm) {
let UIApplication = plus.ios.import("UIApplication");
let application = UIApplication.sharedApplication();
let NSURL = plus.ios.import("NSURL");
let setting = NSURL.URLWithString("app-settings:");
application.openURL(setting);
plus.ios.deleteObject(setting);
plus.ios.deleteObject(NSURL);
plus.ios.deleteObject(application);
}
}
});
}
}
return false;
},
gotoLocationSetting() {
let system = uni.getSystemInfoSync();
if (system.platform === 'ios') {
let UIApplication = plus.ios.import("UIApplication");
let application = UIApplication.sharedApplication();
let NSURL = plus.ios.import("NSURL");
let setting = NSURL.URLWithString("app-settings:");
application.openURL(setting);
plus.ios.deleteObject(setting);
plus.ios.deleteObject(NSURL);
plus.ios.deleteObject(application);
} else {
let main = plus.android.runtimeMainActivity();
//打开手机系统gps定位设置页面
let Intent = plus.android.importClass('android.content.Intent');
let Settings = plus.android.importClass('android.provider.Settings');
let intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
main.startActivity(intent);
}
},
gotoAppSetting() {
let system = uni.getSystemInfoSync();
if (system.platform === 'ios') {
var UIApplication = plus.ios.import("UIApplication");
var application2 = UIApplication.sharedApplication();
var NSURL2 = plus.ios.import("NSURL");
var setting2 = NSURL2.URLWithString("app-settings:");
application2.openURL(setting2);
plus.ios.deleteObject(setting2);
plus.ios.deleteObject(NSURL2);
plus.ios.deleteObject(application2);
} else {
var Intent = plus.android.importClass("android.content.Intent");
var Settings = plus.android.importClass("android.provider.Settings");
var Uri = plus.android.importClass("android.net.Uri");
var mainActivity = plus.android.runtimeMainActivity();
var intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
intent.setData(uri);
mainActivity.startActivity(intent);
}
},
/**开启后台持续获取定位功能
* successCallBack:成功回调函数
*failCallBack:失败回调函数
*maximumAge:获取定位间隔时间
*/
startLocationService(successCallBack = () => {}, failCallBack = () => {}, maximumAge = 10 * 1000) {
if (this.hasLocationPermission()) { //有定位权限
let locationWatcherId = plus.geolocation.watchPosition((position) => {
console.log(position);
successCallBack({
locationWatcherId,
position: position.coords
})
}, function(e) {
console.log(e, '定位失败');
failCallBack(e)
}, {
provider: 'system', //优先使用定位模块,“system”:表示系统定位模块,支持wgs84坐标系; “baidu”:表示百度定位模块,支持gcj02/bd09/bd09ll坐标系; “amap”:表示高德定位模板,支持gcj02坐标系,默认值按以下优先顺序获取(amap>baidu>system)
// timeout: 10000, //定位超时
enableHighAccuracy: false, //高精确度获取位置信息
coordsType: "wgs84", //坐标系类型, “wgs84”:表示WGS-84坐标系; “gcj02”:表示国测局经纬度坐标系,"bd09":百度地图使用的坐标系
//geocode:false//是否解析地址
geocode: true,
maximumAge: maximumAge,
});
}
},
//关闭定位功能
closeLocationService(locationWatcherId) { //locationWatcherId:开启步骤生成的监听器id
plus.geolocation.clearWatch(locationWatcherId)
},
}
调用:
import locationWatcher from '@/utils/location.js'
// 其他代码...
let locationWatcherId;
locationWatcher.startLocationService(e => {
let {
latitude,
longitude
} = e.position
console.log('地位中', e)
if (!locationWatcherId) {
locationWatcherId = e.locationWatcherId //举例保存到data,实际可以缓存到全局
}
}, (e) => {
console.log(e, '定位失败')
}, 10 * 1000)
2. 第三方SDK定位(高德定位)
勾选相应的定位模块
申请相关的key,根据后面的获取方式步骤进行申请即可;
uni.getLocation({
type: 'gcj02',
success: function(res) {
console.log('高德当前地址' + JSON.stringify(res))
}
});
注意:系统定位只支持 wgs84 gps 坐标系, 不设置type默认就会使用系统定位返回 wgs84 坐标,如果设置了 gcj02 类型,那就会使用高德定位。