Android-绑定服务

来源:互联网 发布:四个系统数据库是什么 编辑:程序博客网 时间:2024/06/05 05:47

绑定式服务

第一次绑定服务自动调用 onCreate->onBind
多次调用绑定服务 不会调用任何方法.
只能解绑一次,解绑时调用 unBind->onDestroy


当onBind返回值不为null,函数的执行过程为onCreate->onBind->ServiceConnection.onServiceConnected



如果Activity已经成功绑定过一个服务,ctivity报异常
Activity has leaked ServiceConnection that was originally bound here

解决:退出前先解绑

ServiceConnection serviceConnection=new ServiceConnection() {

    @Overridepublic void onServiceConnected(ComponentName name,
                                   IBinder service) {



        LHBindService.MyIBinder s=(LHBindService.MyIBinder)service;



        System.out.println("MainActivity.onServiceConnected  " +
                "Random   "+s.getRandom());


        System.out.println("name = [" + name + "], service = ["
                + service + "]");
        @Override/**
     * 当服务"异常"断开时调用的方法
     */public void onServiceDisconnected(ComponentName name)     {
            System.out.println("MainActivity.onServiceDisconnected");            System.out.println("name = [" + name + "]");

};Intent intent=new Intent(this,LHBindService.class);
intent.putExtra("key","传值");
bindService(intent//意图对象,指定要绑定的服务
,serviceConnection//服务连接对象
,BIND_AUTO_CREATE//标志位,如果没有创建服务则自动创建
);
0 0
原创粉丝点击