通过bindService调用服务里面的方法
2017-05-25 16:59
555 查看
通过bindService方式调用服务方法里面的过程
(1)、定义一个服务,服务里面有一个方法需要Activity调用。
(2)、定义一个中间人对象(IBinder)继承Binder;
(3)、在onbind方法里面把我们定义的中间人对象返回。
(4)、在Activity的onCreate方法里面调用bindService,目的是获取我们定义的中间人对象。
(5)、拿到中间人对象后,就可以间接的调用到服务里面的方法
Activity使用bindService开启服务
TestService继承Service
(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); } } }
相关文章推荐
- 通过bindservice方式调用服务方法里面的过程
- Android 服务(service)的生命周期以及利用bindservice调用服务里面的方法
- Android通过bindservice方式调用服务的方法
- android服务_通过bindService调用服务里的方法
- 通过bindservice调用服务内部方法
- 为什要使用BindService?为了调用服务中的方法
- Android通过广播接收者调用服务(service)内方法
- Android - 绑定服务调用服务里面的方法,start/bind开启服务的比较,混合方式开启服务,本地服务,远程服务,系统服务,录音API
- Service一直存在并且能调用服务里面的方法
- android90 bind方式启动服务service调用service里的方法
- Android(java)学习笔记229:服务(service)之绑定服务调用服务里面的方法 (采用接口隐藏代码内部实现)
- Android 通过接口的方式去调用服务里面的方法
- 通过接口方式调用服务里面的方法
- bindService调用Service里面方法的步骤
- Android通过接口方式调用服务里面的方法
- android bindService 来调用服务中的方法
- 调用android非unbind的服务中的方法(不使用bindService启动的服务)
- Android(java)学习笔记228:服务(service)之绑定服务调用服务里面的方法
- 代码注册广播接受者调用服务里面的方法
- activity以绑定服务的方式开启服务并调用服务里面的方法