在全局service里面30s做一次百度定位的方法

本文介绍如何在全局Service中每30秒进行一次百度定位。通过创建并启动LocationService,注意不能使用bindService,而是利用全局变量进行数据传递。另外,调用mLocClient.start()后需等待定位生效,避免立即stop导致数据丢失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1.注册文件里面注册一下service,保证service可以启动:

        <service
            android:name="com.test.service.LocationService"
            android:enabled="true" android:permission="5">
            <intent-filter>
                <action android:name="com.test.location" />
            </intent-filter>
        </service>

2.application里面启动service:

Intent intet = new Intent(this, LocationService.class);

startService(intet);

此处要注意:因为使用的是全局的service,不能用bind,与activity生命周期绑定并非我们所愿的。

由于不能bind,所以在service里面取出数据太麻烦,以下数据传递直接使用的全局变量;

3.

public void startLoc() {
		final Handler timeHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Log.e(TAG, "重新定位");
				// 每30秒做一次定位,此方法是一个百度地图的回调,当百度定位数据有返回时会走getLoc方法。
				MapUtil.getInstence().getLoc(LocationService.this,
						new IWaittingLoc() {
							@Override
							public void GetLoc(LatLng ll) {
								LocationService.this.ll = ll;
								if (ll != null) {
									GlobleVariable.currentLatlng = ll;
								} else {
									Log.e(TAG,
											getResources().getString(
													R.string.login_fail));
								}
							}
						});
				// 30秒后再做一次请求
				sendEmptyMessageDelayed(0, 1000 * 30);
			}
		};
		timeHandler.sendEmptyMessage(0);
	}

4.百度地图要多次定位的话有一点很要注意:调用mLocClient.start()之后并不是马上就能生效的,如果此时stop会导致返回无数据,步骤3的方法也会一直在else里面跑。

所以建议如下处理:

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null)
				return;
			LatLng ll = null;
			ll = new LatLng(location.getLatitude(), location.getLongitude());
			System.out.println(ll);
			// }
                       //这里是就是步骤3里面执行的回调方法
			waitLoc.GetLoc(ll);
			if (ll != null) {
				mLocClient.stop();
			}
		}
这样就能完成30s执行一次百度定位了


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值