一、 AIDL
- 上一篇文章 中,我们通过Bind启动Service,当我们的Service和Activity不在同一进程里面,会报错:java.lang.ClassCastException: android.os.BinderProxy cannot be cast to …
- 是时候了解了解我们的AIDL了。
- AIDL(Android Interface Define Language) 是IPC进程间通信方式的一种.用于生成可以在Android设备上两个进程之间进行进程间通信(interprocess communication, IPC)的代码.
二、使用步骤
- Android studio 很方便就能创建AIDL。
- 新建一个aidl的文件夹。看图
- 新建的AIDL叫 IMyAidlInterface.aidl。
interface IMyAidlInterface {
//从简,我修改了一下
void start();
}
- 点击运行,图
运行成功,继续。废话不多说,看代码。
Service类的代码
public class AbleService extends Service { public final static String TAG = "AbleService"; public AbleService() { } private IBinder aidlInterface = new IMyAidlInterface.Stub() { @Override public void start() throws RemoteException { Log.v(TAG,"IMyAidlInterface实现了进程通信!"); } }; @Override public IBinder onBind(Intent intent) { return aidlInterface ; } }
AndroidManifest.xml注册。
<service android:name=".service.AbleService" android:enabled="true" android:exported="true" android:process="com.fingerth.able.service"> </service>
Activity的代码
Intent intent = new Intent(this, AbleService.class); bindService(intent, conn, BIND_AUTO_CREATE);
private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { //这里得到IMyAidlInterface,可以直接调用它的方法,这样就完成了和Service的通信 IMyAidlInterface aidlInterface = IMyAidlInterface.Stub.asInterface(service); try { aidlInterface.start(); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } };
三、代码写完,运行looklook
- 运行当然是成功的了。
- 完。