通过bindservice方式调用服务方法里面的过程

为什么要引入bindService:目的为了调用服务里面的方法

(1)定义一个服务 服务里面有一个方法需要Activity调用

(2)定义一个中间人对象(IBinder) 继承Binder

(3)在onbind方法里面把我们定义的中间人对象返回

(4)在Activity的oncreate 方法里面调用bindservice 目的是为来获取我们定义的中间人对象

(4.1)获取中间人对象

(5)拿到中间人对象后就可以间接的调用到服务里面的方法

public class TestService extends Service {

    //当bindservice 
    @Override
    public IBinder onBind(Intent intent) {
        
        //[3]把我们定义的中间人对象返回
        return new MyBinder();
    }


    
    @Override
    public void onCreate() {
        super.onCreate();
    }

    //测试方法
    public void banZheng(int money){
        
        if (money > 1000) {
            Toast.makeText(getApplicationContext(), "我是领导 把证给你办了", 1).show();
        }else{
            
            Toast.makeText(getApplicationContext(), "这点钱 还想办事", 1).show();
        } 
            
    }
    
    //[1定义一个中间人对象 ]
    
    public  class MyBinder extends Binder{
        
        //[2]定义一个方法 调用办证的方法 
        public void callBanZheng(int money){
            banZheng(money);
            
        }
        
    }
    
    
}
public class MainActivity extends Activity {

    private MyBinder myBinder; //这个是我们定义的中间人对象
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
//        //开启服务 
        Intent intent = new Intent(this,TestService.class);
        //连接服务 TestService
        MyConn conn = new  MyConn();
        //绑定服务 
        bindService(intent, conn, BIND_AUTO_CREATE);
        
    }

    
    //点击按钮 调用TestService 服务里面的办证方法 
    public void click(View v) {
        //通过我们定义的中间人对象 间接调用服务里面的方法
        myBinder.callBanZheng(102);
        
    }
    
    //监视服务的状态
    private class MyConn implements ServiceConnection{

        

        //当连接服务成功后
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            
            //[4]获取我们定义的中间人对象 
            
            myBinder = (MyBinder) service;
        }

        //失去连接
        @Override
        public void onServiceDisconnected(ComponentName name) {
            
        }
        
    }
    
    
}
原文地址:https://www.cnblogs.com/xufengyuan/p/5987791.html