uniapp开发APP后台保活机制
android和ios通过开启定位来实现保活。需要用户授权定位
1、开启定位代码 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: '定位权限开启提醒',confirmText: "去设置",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);}}})}} else if (system.platform === 'ios') { //ioslet cllocationManger = plus.ios.import("CLLocationManager");let enable = cllocationManger.locationServicesEnabled();let status = cllocationManger.authorizationStatus();plus.ios.deleteObject(cllocationManger);if (enable && status != 2) return true; //已开启定位功能else {uni.showModal({title: '定位权限开启提醒',confirmText: "去设置",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;},/**开启后台持续获取定位功能* successCallBack:成功回调函数*failCallBack:失败回调函数 *maximumAge:获取定位间隔时间*/startLocationService(successCallBack = () => {}, failCallBack = () => {}, maximumAge = 10 * 1000) {if (this.hasLocationPermission()) { //有定位权限let locationWatcherId = plus.geolocation.watchPosition((position) => {successCallBack({locationWatcherId,position: position.coords})}, function(e) {failCallBack(e)}, {maximumAge, //获取位置间隔时间});}},//关闭定位功能closeLocationService(locationWatcherId) { //locationWatcherId:开启步骤生成的监听器idplus.geolocation.clearWatch(locationWatcherId)},
}
2、在App.vue中使用
import locationWatcher from '@/utils/location.js';// 在生命周期onLaunch中使用
locationWatcher.startLocationService((e) => {let { latitude, longitude } = e.position;console.log(`当前位置,经度${longitude},纬度${latitude}`);},(e) => {console.log(e, '定位失败');}
);