通过bindService调用服务里面的方法

来源:互联网 发布:linux 创建新文件 编辑:程序博客网 时间:2024/05/21 19:48

通过bindService方式调用服务方法里面的过程
     (1)、定义一个服务,服务里面有一个方法需要Activity调用。
     (2)、定义一个中间人对象(IBinder)继承Binder;
     (3)、在onbind方法里面把我们定义的中间人对象返回。
     (4)、在Activity的onCreate方法里面调用bindService,目的是获取我们定义的中间人对象。
     (5)、拿到中间人对象后,就可以间接的调用到服务里面的方法
Activity使用bindService开启服务

public class MainActivity extends Activity{     MyConn conn;     MyBinder mMyBinder ;     @Override     public void onCreate(Bundle onSaveInstanceState){             super.onCreate(onSaveInstanceState);             Intent intent = new Intent(this,TestService.class);             conn = new MyConn();              //连接到服务             bindService(intent,conn, BIND_AUTO_CREATE);      }      public void click(View v){           mMyBinder.banZheng(1000);       }       private class MyConn implements ServiceConnection {            @Override             public void onServiceConnected(ComponentName name, IBinder service){                   mMyBinder = (MyBinder)IBinder ;                                }              @Override             public void onServiceDisconnected(ComponentName name){              }       }      @Override      protected void onDestory(){         //当activity销毁的时候,取消绑定服务         unbindService(conn);       }}

TestService继承Service

public class MyService extends Service {        @Override      public IBinder onBind(Intent intent) {          //定义的中间人对象        MyBinder mMyBinder =new MyBinder();          return mMyBinder ; //返回的mCallmethod对象会在onServiceConnected()中调用      }     @Override      public int onStartCommand(Intent intent, int flags, int startId) {          return super.onStartCommand(intent, flags, startId);      }          public void banZheng(int money){          if (money > 1000){             Toast.makeText(getApplicationContext(),"",1).show();        }else{            Toast.makeText(getApplicationContext(),"",1).show();         }        Toast.makeText(getApplicationContext(), "我是服务里的方法"0).show();      }          public class MyBinder extends Binder{          //[2]定义一个方法 调用办证的方法        public void callBanZheng(int money) {                banZheng(money);                    }                }  }  
原创粉丝点击