安卓Service向Activity传递数据,更新UI

本文介绍了如何在Android中通过Service执行定时任务和网络请求获取位置信息,并利用接口回调、Handler及活动和服务绑定的方式,将数据传递到Activity,实现在地图上展示定位结果。关键步骤包括在Service中设置回调接口,通过LocationBinder获取Service实例,以及在Activity中接收并更新UI的消息处理。

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

接口回调、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,获取服务实例
   public class LocationBinder extends Binder {

       public LocationService getLocationService(){
           return LocationService.this;
       }
    }
//自定义异步任务
    class MyTask extends AsyncTask<String,Integer,LocationInfo>{

        @Override
        protected LocationInfo doInBackground(String... params) {
//            String userId=params[0];
            try {
                locationInfo= HttpRequestMethods.getLocation(new PostParameter[]{
                        new PostParameter("userId", params[0]), new PostParameter("startTime", params[1]),
                        new PostParameter("endTime", params[2]), new PostParameter("type", "normal")});
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return locationInfo;
        }

        @Override
        protected void onPostExecute(LocationInfo locationInfo) {
            if(locationInfo!=null){
                Log.d("chenmeng9202", locationInfo.getLongitude() + "");
                localDB.query("insert or ignore into location_table(user_id,latitude,longitude,time)values(?,?,?,?)",
                        new String[]{mCurrentUserId, locationInfo.getLatitude() + "", locationInfo.getLongitude() + "", locationInfo.getTime()});
                        //回调
                dataCallback.updateui(locationInfo);
            }
        }
    }
    //设置接口
    public void setDataCallback(DataCallback dataCallback){
        this.dataCallback=dataCallback;
    }
    //自定义回调接口
    public interface DataCallback{
        void updateui(LocationInfo locationInfo);
    }
}


2TripAvtivity完整代码
public class TripActivity extends ToolBarActivity implements View.OnClickListener {
    private final static String TAG=TripActivity.class.getSimpleName();
    private MapView mapView;
    private BaiduMapUtil baiduMapUtil;//地图工具类
    private Button btchangeMember;


    private Button btDail;
    private Button btSearchHospital;
    private Button btSearchTrack;
    private Button btTripRecord;
    private Button btFence;

    private static final int SEARCH_TYPE_CITY = 0;
    private static final int SEARCH_TYPE_BOUND = 1;
    private static final int SEARCH_TYPE_NEARBY = 2;


    private List<People> peoples;
    private LocalDB localDB;
    private String mCurrentUserId;
    private People mCurrentPeople;//当前成员
    private LocationInfo mLocationInfo;//当前定位信息

    private HospitalInfo hospitalInfo;
    private int switch_index;

    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;
            }
        }
    };

    private LocationInfo sLocationInfo;//服务传回的定位信息
    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);

                }
            });
            //更新UI

        }
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_trip);
        localDB=new LocalDB(this);
        peoples=localDB.getMemberList();
        initView();
        initData();
        new LocationTask().execute(mCurrentUserId, "0", new Date().getTime() + "");
        Intent bindIntent=new Intent(this,LocationService.class);
        startService(bindIntent);
        bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }

    private void initData() {
        if(peoples!=null&&peoples.size()>0){
            mCurrentPeople=peoples.get(0);
            mCurrentUserId=peoples.get(0).getUserid();
            btchangeMember.setText(peoples.get(0).getUsername());
        }
    }

    private void initView() {
        Toolbar toolbar = getToolBar();
        ((TextView) toolbar.findViewById(R.id.tv_title)).setText("摔倒监护");
        btchangeMember=(Button)findViewById(R.id.changeMember);
        btchangeMember.setOnClickListener(this);
        mapView = (MapView) findViewById(R.id.map_view);
        baiduMapUtil=new BaiduMapUtil(getApplicationContext(),mapView);
        //底部菜单按钮
        btDail=(Button)findViewById(R.id.trip_dail);
        btDail.setOnClickListener(this);
        btSearchHospital = (Button) findViewById(R.id.search_hospital);
        btSearchHospital.setOnClickListener(this);
        btSearchTrack = (Button) findViewById(R.id.search_track);
        btSearchTrack.setOnClickListener(this);
        btTripRecord = (Button) findViewById(R.id.trip_record);
        btTripRecord.setOnClickListener(this);
        btFence=(Button)findViewById(R.id.trip_fence);
        btFence.setOnClickListener(this);
    }



    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Bundle b = data.getExtras();
                    hospitalInfo = (HospitalInfo) b.getSerializable("hospitalInfo");
                    baiduMapUtil.showAtLocation(hospitalInfo);
                    baiduMapUtil.addOverLay(hospitalInfo);
                    baiduMapUtil.GeoCode(hospitalInfo);
                    baiduMapUtil.setGeoCallback(new BaiduMapUtil.Geocallback() {
                        @Override
                        public void geo(String address) {
                            hospitalInfo.setPoiadd(address);
                            baiduMapUtil.showInfoWindow(hospitalInfo);
                        }

                        @Override
                        public void Poi(List<HospitalInfo> list) {

                        }
                    });
                    baiduMapUtil.setNavigation(new BaiduMapUtil.Navigation() {
                        @Override
                        public void navigation(HospitalInfo hospitalInfo) {
                            Intent intent=new Intent(TripActivity.this,NavigationActivity.class);
                            intent.putExtra("hospitalinfo",hospitalInfo);
                            intent.putExtra("lacationinfo",mLocationInfo);
                            startActivity(intent);
                        }
                    });
                }
                break;
            default:
                break;
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.trip_dail:
                String mCurrentPhone= mCurrentPeople.getPhone();
                if(mCurrentPhone!=null) {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+mCurrentPeople.getPhone()));
                    TripActivity.this.startActivity(intent);
                }else{
                    ToastShow.ShortToast(getApplicationContext(),"当前成员未绑定手机");
                }
                break;
            case R.id.search_hospital:
                LatLng latLng=new LatLng(mLocationInfo.getLatitude(),mLocationInfo.getLongitude());
                Log.d("latLng",latLng.latitude+"");
                baiduMapUtil.searchByType(SEARCH_TYPE_CITY, latLng);
                baiduMapUtil.setGeoCallback(new BaiduMapUtil.Geocallback() {
                    @Override
                    public void geo(String address) {
                    }

                    @Override
                    public void Poi(List<HospitalInfo> list) {
                        Log.d("chenmeng","poi");
                        Intent intent = new Intent(TripActivity.this, HospitalActivity.class);
                        intent.putExtra("poiResult", (Serializable)list);
                        startActivityForResult(intent, 1);
                    }
                });

                break;
            case R.id.search_track:
                Intent intenttrack=new Intent(TripActivity.this,TrackActivity.class);
                startActivity(intenttrack);
                break;
            case R.id.trip_record:
                Intent intent=new Intent(TripActivity.this,FallRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.trip_fence:
                Intent intentfence=new Intent(TripActivity.this,FenceActivity.class);
                startActivity(intentfence);
                break;


          /**
            case R.id.bt_map_pattern:
                if(mCurrentMode==MyLocationConfiguration.LocationMode.NORMAL){
                    mCurrentMode= MyLocationConfiguration.LocationMode.FOLLOWING;
                    btMapPattern.setText("跟随");
                }else{
                    if( mCurrentMode== MyLocationConfiguration.LocationMode.FOLLOWING) {
                        mCurrentMode = MyLocationConfiguration.LocationMode.COMPASS;
                        btMapPattern.setText("罗盘");
                    }else {
                        if(mCurrentMode==MyLocationConfiguration.LocationMode.COMPASS) {
                            mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
                            btMapPattern.setText("普通");
                        }
                    }
                }
                break;
         **/
            case R.id.changeMember: {
                final int[] inner_which = {0};
                //切换成员
                if (peoples != null) {
                    final String[] name_list = new String[peoples.size()];
                    final String[] userId_list = new String[peoples.size()];
                    for (int i = 0; i < peoples.size(); i++) {
                        name_list[i] = peoples.get(i).getUsername();
                        userId_list[i] = peoples.get(i).getUserid();
                    }
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("成员列表");
                    builder.setSingleChoiceItems(name_list, 0, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch_index = which;
                            inner_which[0] = which;
                        }
                    });
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if (inner_which[0] != 0) {
                                mCurrentPeople=peoples.get(switch_index);
                                mCurrentUserId = userId_list[switch_index];
                                btchangeMember.setText(name_list[switch_index]);
                            }else {
                                mCurrentPeople=peoples.get(switch_index);
                                mCurrentUserId = userId_list[0];
                                btchangeMember.setText(name_list[0]);
                            }
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                } else {
                    ToastShow.ShortToast(this, "暂无成员");
                }
            }
            default:
                break;
        }
    }

    class LocationTask extends AsyncTask<String,Integer,LocationInfo>{
        @Override
        protected LocationInfo doInBackground(String... params) {
            String userId=params[0];
            LocationInfo locationInfo=null;

            try {
                locationInfo= HttpRequestMethods.getLocation(new PostParameter[]{
                new PostParameter("userId",params[0]),new PostParameter("startTime",params[1]),
                new PostParameter("endTime",params[2]),new PostParameter("type","normal")});
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return locationInfo;
        }
        @Override
        protected void onPostExecute(LocationInfo locationInfo){
            mLocationInfo=locationInfo;
            baiduMapUtil.showAtLocation(locationInfo);
            baiduMapUtil.addOverLay(locationInfo);
            baiduMapUtil.GeoCode(locationInfo);
            baiduMapUtil.setGeoCallback(new BaiduMapUtil.Geocallback() {
                @Override
                public void geo(String address) {
                    mLocationInfo.setAddress(address);
                    baiduMapUtil.showInfoWindow(mLocationInfo);

                }
                @Override
                public void Poi(List<HospitalInfo> list) {
                }
            });
            //存数据库
            localDB.execSQL("insert or ignore into location_table(user_id,latitude,longitude,time) values" +
                    "(?,?,?,?)",new String[]{mCurrentUserId,locationInfo.getLatitude()+"",locationInfo.getLongitude()+"",locationInfo.getTime()});
        }
        OnGetGeoCoderResultListener geoListener=new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                String address = geoCodeResult.getAddress();
                LatLng latLng = geoCodeResult.getLocation();
                mLocationInfo.setAddress(address);
                Log.d(TAG,mLocationInfo.getAddress());
                baiduMapUtil.showInfoWindow(mLocationInfo);
            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            }

        };

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值