Android--高德地图后台持续定位

该博客主要探讨如何在Android应用中实现在后台进行高德地图的持续定位。通过在本地服务启动连续定位,并设定Alarm定期唤醒服务,以维持定位功能。同时,为防止CPU休眠导致定位中断,会进行屏幕点亮操作。遇到location Error, ErrCode:7的问题,解决方案是检查并更新应用的SHA1值以匹配高德地图API的设置。" 123331848,12572233,消息推送接口设计与实现,"['性能优化', 'java', '前端', '开发语言', '后端']
摘要由CSDN通过智能技术生成

核心类/接口

接口

说明

版本

AMapLocationClient

startLocation();

启动定位

V2.0.0版本起

 

setLocationOption(mLocationOption);

给定位客户端设置参数

V2.0.0版本起

AMapLocationClientOption

setInterval(long time);

设置连续定位时间间隔

V2.0.0版本起

AMapLocationListener

onLocationChanged(AMapLocation amapLocation) ;

监听器回调方法

V2.0.0版本起

核心难点

首先在本地服务中启动连续定位功能,通过设置一个Alarm定期对本地服务进行周期唤起,从而达到后台持续定位的效果。

1、在本地服务里启动连续定位:

//在activity中启动自定义本地服务LocationService
getApplicationContext().startService(new Intent(this, LocationService.class));

//在LocationService中启动定位
mLocationClient = new AMapLocationClient(this.getApplicationContext());
mLocationOption = new AMapLocationClientOption();
// 使用连续定位
mLocationOption.setOnceLocation(false);
// 每10秒定位一次
mLocationOption.setInterval(10 * 1000);
mLocationClient.setLocationOption(mLocationOption);
mLocationClient.setLocationListener(locationListener);
mLocationClient.startLocation();

2、创建并启动Alarm。

//创建Alarm并启动
Intent intent = new Intent("LOCATION_CLOCK");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
// 每五秒唤醒一次
long second = 15 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), second, pendingIntent);

3、通过Alarm启动本地服务,如果定位停止,在服务中再次启动。

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("LOCATION_CLOCK")) {
            Log.e("ggb", "--->>>   onReceive  LOCATION_CLOCK");
            Intent locationIntent = new Intent(context, LocationService.class);
            context.startService(locationIntent);
        }
    }
}
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值