Android基础知识--8.Android中Service通信

     启动Service并传入数据: 在Aty布局中添加“启动服务”按钮监听器调用startService方法 ,“停止服务”按钮 监听器调用stopService方法 ,id为etData的文本框,在Aty中使用intent向Service传入数据
       Intent i=new Intent(this,MyService.class);
       i.putExtra("data",etData.getText().toString());
       startService(i);
    在MyService的onStartCommand函数中通过data=intent.getStringExtra("data")来获取数据

       绑定Service进行通信: 添加“绑定”按钮 监听器调用bindService方法 ,“ 解除绑定”按钮 监听器调用unbindService方法,具体操作同上一节,再添加一个“同步数据”按钮。 在MyService中创建一个
           public class Binder extends android.os.Binder{
               public void setData(String data){
                   this.data=data;
               }
           }
      在bind方法中,写入return new Binder();
      在Aty中定义一个MyService.Binder类型的变量binder,在onServiceConnected方法中,写入
           binder=(MyService.Binder)service;
      在同步数据的监听器中,写入
           if(binder!=null){
               binder.setData(etData.getText().toString());
           }
      通过方法调用共享数据,更方便直接
    主布局再添加一个textView,在程序中获取到它tvOut;MyService中定义一个接口
         public static interface Callback{
            void onDataChange(String data);
        }
        private Callback callback=null;
        public void setCallback(Callback callback){
            this.callback=callback;
        }
        public Callback getCallback(){
            return callback;
        }
      创建一个线程,run方法中写入for循环, 循环中
           String str=i+":"+data;
        if(callback!=null){
            callback.onDataChange(str);
        }
      在Binder类中添加
           public MyService getService(){
            return MyService.this;
        }
      在Aty中定义一个
            private Handler handler=new Handler(){
            public void handleMessage(Message msg){
                super.handleMessage(msg);
                tvOut.setText(msg.getData().getString("data"));
            }
        }
      onServiceConnected方法加入
           binder.getService().setCallback(new MyService.callback(){
            public void onDataChange(String data){
                Message msg=new Message();
                Bundle b=new Bundle();
                b.putString("data",data);
                msg.setData(b);
                handle.sendMessage(msg);
            }
        });
      通过这种方法即可侦听Service中的状态变化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值