Bound Service 1.创建BoundService继承类,并复写onBind()方法(当其他程序组件(Activity)绑定该Service对象时调用该方法) publicIBinder onBind(Intent intent){ IBinder binder = new MyBinder( ); return binder; } 2.创建Binder的继承类(在BoundService继承类中的内部类) class MyBinder extends Binder{ public String get Data( ){ return "test data"; } } 3. 在AndroidManifest.xml文件中注册service <service android:name=".类名"/> 4.创建连接对象 ServiceConnection conn = newServiceConnection(){ public void onServiceConnection(ComponentNamename, IBinder service){ //绑定时调用 } public voidonServiceDisconnection(ComponentName name){ //解除绑定时调用 } } 5.在Activity中,绑定servicer Intent intent = new Intent( ); intent.setClass(Activity.this,BoundService.class); bindService(intent,conn,flags);flags:BIND_AUTO_CREATE; Bound Service与Start Service区别
StartService无法给Activity返回数据,而Bound Service可以进行交互
|