通過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) {
            
        }
        
    }
    
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM