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执行一次百度定位了