接口回调、Handler、活动和服务绑定
1服务:执行定时任务,发起网络请求定位,请求到的结果传递到活动,在地图上展示。
2活动关键代码:
绑定服务后会获取LocationService.LocationBinder对象,在此处调用getLocationService()方法获取Service实例,service设置回调接口获取位置信息,并发送消息,handler接收消息后更新UI。
//绑定服务
private LocationService service;
private ServiceConnection serviceConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
service=((LocationService.LocationBinder)iBinder).getLocationService();
service.setDataCallback(new LocationService.DataCallback() {
@Override
public void updateui(LocationInfo locationInfo) {
Message message=new Message();
message.what=LocationService.UpdateLocation;
message.obj=locationInfo;
handler.sendMessage(message);
}
});
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
//handler处理消息更新UI
public Handler handler=new Handler(){
public void handleMessage(Message message){
switch (message.what){
case LocationService.UpdateLocation:
//更新UI
sLocationInfo=(LocationInfo)message.obj;
baiduMapUtil.showAtLocation(sLocationInfo);
baiduMapUtil.mBaiduMap.clear();
baiduMapUtil.addOverLay(sLocationInfo);
baiduMapUtil.GeoCode(sLocationInfo);
baiduMapUtil.setGeoCallback(new BaiduMapUtil.Geocallback() {
@Override
public void geo(String address) {
sLocationInfo.setAddress(address);
baiduMapUtil.showInfoWindow(sLocationInfo);
}
@Override
public void Poi(List<HospitalInfo> list) {
}
});
break;
}
}
};
public class LocationService extends Service {
public static final int UpdateLocation=1;//更新UI
private LocalDB localDB;
private List<People> peoples;
private People mCurrentPeople;
private String mCurrentUserId;
public LocationInfo locationInfo;
private DataCallback dataCallback=null;
public LocationService() {
}
private LocationBinder mBinder=new LocationBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate(){
super.onCreate();
localDB=new LocalDB(this);
peoples=localDB.getMemberList();
mCurrentPeople=peoples.get(0);
mCurrentUserId=mCurrentPeople.getUserid();
}
@Override
public int onStartCommand(Intent intent,int flags,int startId){
//自定义的异步定时任务从网络请求定位,获取经纬度,没隔10秒请求一次
new MyTask().execute(mCurrentUserId,"0",new Date().getTime()+"");
AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);
int anHour=60*60*1000;
long triggerAtTime= SystemClock.elapsedRealtime()+10*1000;
Intent i=new Intent(this, LocationReceiver.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,i,0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendingIntent);
return super.onStartCommand(intent,flags,startId);
}
//定义Binder,获取服务实例