一、适用场景:client进程必须是Activity,服务端进程必须是Service
二、基于:Activity跟Service绑定
三、问题:在Activity中可以得到的Binder对象,但是无法获得具体类型
四、使用步骤:
(一)Service中创建Binder对象
(二)创建aidl文件(接近interface)
1. 在服务端创建一个interface,方法为MyBinder中的方法
2. 把接口文件扩展名修改为“aidl”,并删除interface之前的public修饰符
3. 将aidl文件拷贝到客户端同样包名中
4. 在服务端将MyBinder继承的Binder修改为aidl文件名.Stub
5. 在客户端的onServiceConected()方法中
通过IMyBinder binder = IMyBinder.Stub.asInterface(service);
得到binder
服务端service:
import com.ex03.aidl.IMyBinder; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class MyService extends Service { private String play() { return "播放音乐"; } private String pause() { return "暂停音乐"; } public class MyBind extends IMyBinder.Stub { public String play() { return MyService.this.play(); } public String pause() { return MyService.this.pause(); } } private IBinder bind = new MyBind(); @Override public IBinder onBind(Intent intent) { return bind; } }
客户端Activity:
import com.ex03.aidl.IMyBinder;//服务端添加aidl文件后,复制到客户端,并导入包 import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener { IMyBinder bind = null; TextView textView = null; private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { bind = IMyBinder.Stub.asInterface(service);//通过此方法得到IBinder对象类型 } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_client_play).setOnClickListener(this); findViewById(R.id.btn_client_pause).setOnClickListener(this); findViewById(R.id.button3).setOnClickListener(this); textView = (TextView) findViewById(R.id.textView1); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_client_play: btnPlayClick(); break; case R.id.btn_client_pause: btnPauseClick(); break; case R.id.button3: btnBindClick(); break; default: break; } } private void btnBindClick()//点击启动服务 { Intent service = new Intent("com.ex03.ipc.aidl"); bindService(service , conn, BIND_AUTO_CREATE); } private void btnPauseClick()//点击暂停音乐 { try { textView.setText(bind.pause()); } catch (RemoteException e) { e.printStackTrace(); } } private void btnPlayClick()//点击播放音乐 { try { textView.setText(bind.play()); } catch (RemoteException e) { e.printStackTrace(); } } }