zoukankan      html  css  js  c++  java
  • 通过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) {
                
            }
            
        }
        
        
    }
  • 相关阅读:
    【网络爬虫】【python】网络爬虫(五):scrapy爬虫初探——爬取网页及选择器
    AndroidStudio的transformDexArchiveWithExternalLibsDexMergerForDebug报错解决方案
    SQL笔记
    基尼系数
    搜索评价指标——NDCG
    Bayes' theorem (贝叶斯定理)
    itembase协同过滤的详细介绍
    线性回归

    指标、统计和分布
  • 原文地址:https://www.cnblogs.com/xufengyuan/p/5987791.html
Copyright © 2011-2022 走看看