service组件如何跟acitivity通信

service与mainactivity  需要在mainacitvity中定义中间类(服务连接类)实现信息交流。

话不多说,直接上代码:

 

1.service类  定义服务类myservice   实现抽象类方法。 并且书写自定义方法。

注意:此服务会自动调用两个方法,并且服务要想实现通信 ,服务的方法IBinder方法会返回binder类型对象,必须定义内部类来继承B

inder类,

2.最后要在androidmanifest.xml中注册service类

public class myservice extends Service{

    public void onCreate() {
        super.onCreate();
        Log.i("chuangjian","oncreate()被调用");
    }


    public IBinder onBind(Intent intent) {
        Log.i("onbind", "onBind方法被调用");
        return new servizhuacelei();
    }
    public void callservice(){
        Log.i("xinfuwu","方法被调用");

    }public boolean onUnbind(Intent intent) {
        Log.i("unbind","unbind方法被调用");
        return super.onUnbind(intent);

    }
    //service与服务只允许传输binder对象 切onbind方法要返回binder类型值;
    public class servizhuacelei extends Binder{
        public void callxinxilei(){
            callservice();
        }
    }


}

二。定义mainactivityl类

定义内部类 得到service中的binder类对象。从而实现service中的方法。

实际上要想实现通信,必须定义两个内部类来实现通信。

(1)acitivity与service必须实现服务连接类

(2)由于服务启动会返回一个binder值,所以必须定义内部类,把服务类中的其他需要得到的通信方法放在定义的binder内部类中

(3)最后在主布局中添加三个按钮  一个启动服务,一个停止服务,一个调用服务中的方法。

public class MainActivity extends AppCompatActivity {
    private myservice.servizhuacelei inbinder;
    private myconn Myconn;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public  void btn_start(View view){
        if(Myconn==null){
            Myconn=new myconn();
        }
        Intent intent =new Intent(this,myservice.class);
        bindService(intent,Myconn,BIND_AUTO_CREATE);
    }
    public void btn_call(View view){
        inbinder.callxinxilei();
    }
    public void btn_stop(View view){
        if(Myconn!=null){
            unbindService(Myconn);
            Myconn=null;
        }
    }

    class myconn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            inbinder=(myservice.servizhuacelei)service;

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值