bindService的使用:
当需要调Service里面的方法时,可以用bindService()
首先定义一个类继承于Service,然后配置Manifest.xml文件
1 public class MyBindService extends Service { 2 @Nullable 3 @Override 4 public IBinder onBind(Intent intent) { 5 return new MyBinder(); 6 } 7 public void myfunction(){ 8 System.out.println("我是服务里的方法"); 9 } 10 @Override 11 public void onCreate() { 12 super.onCreate(); 13 } 14 public class MyBinder extends Binder{ 15 public void call(){ 16 myfunction(); 17 } 18 } 19 }
通过onBind()方法返回一个对象,给onServiceConnected(ComponentName name, IBinder service)
方法里面的Service,然后通过强转得到一个MyBinder对象
myBinder = (MyBindService.MyBinder)service;
用myBinder对象调用call方法,从而调到服务里面的myfunction()方法
1 public class MainActivity extends AppCompatActivity { 2 3 private Myconn conn; 4 private MyBindService.MyBinder myBinder; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main); 10 } 11 12 public void click(View v){ 13 conn = new Myconn(); 14 bindService(new Intent(this,MyBindService.class),conn,BIND_AUTO_CREATE); 15 } 16 17 public void click1(View v){ 18 myBinder.call(); 19 } 20 public void click2(View v){ 21 unbindService(conn); 22 } 23 24 private class Myconn implements ServiceConnection { 25 @Override 26 public void onServiceConnected(ComponentName name, IBinder service) { 27 myBinder = (MyBindService.MyBinder)service; 28 } 29 @Override 30 public void onServiceDisconnected(ComponentName name) { 31 } 32 } 33 }
onServiceConnected()当绑定成功后调用该方法。
onServiceDisconnected()取消绑定后调用该方法