Android AIDL的简单例子

来源:互联网 发布:项目管理软件.知乎 编辑:程序博客网 时间:2024/05/01 17:39

本文介绍Android AIDL简单的使用例子,主要分为客户端和服务端。

客户端主要是绑定服务端AIDL的服务,调用服务端,通过服务端回调。实现进程间的连接。

先看看结构图:

客户端:                                                                                                                 


服务端:


这里需要的注意的是,两端的aidl文件包名,文件名,aidl代码必须是一样,建议Ctrl+C,Ctrl+V

现在看看两个aidl文件的代码

AidlCallback.aidl :

package com.lxy.aidl;  interface AidlCallback{  /**回调测试*/    void CallbackTest(in String b);  } 
AidlService.aidl :

package com.lxy.aidl;  import com.lxy.aidl.AidlCallback;interface AidlService{/**测试用的*/    void test(in String a);      /**注册回调*/    void reg(AidlCallback cb);    /**解绑回调*/    void unReg(AidlCallback cb);} 

android会自动编译生成Java文件。

服务端MyAIDLService.java代码:

package com.lxy.aidl_service;import com.lxy.aidl.AidlCallback;import com.lxy.aidl.AidlService;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.RemoteException;import android.util.Log;public class MyAIDLService extends Service {private static final String TAG = "MyAIDLService";private AidlCallback mAidlCallback = null;@Overridepublic void onCreate() {Log.d(TAG,"service created");super.onCreate();}@Overridepublic void onStart(Intent intent, int startId) {Log.d(TAG,"service started id = " + startId);super.onStart(intent, startId);}@Overridepublic void onDestroy() {Log.d(TAG,"service on destroy");super.onDestroy();}@Overridepublic boolean onUnbind(Intent intent) {Log.d(TAG,"service on unbind");return super.onUnbind(intent);}@Overridepublic void onRebind(Intent intent) {Log.d(TAG,"service on rebind");super.onRebind(intent);}@Overridepublic IBinder onBind(Intent intent) {Log.d(TAG,"service on bind");return mBinder;}private final AidlService.Stub mBinder = new AidlService.Stub() {@Overridepublic void test(String a) throws RemoteException {Log.d(TAG, TAG+"得到a的值为:"+a);if(mAidlCallback!=null){mAidlCallback.CallbackTest("ABC");}}@Overridepublic void reg(AidlCallback cb) throws RemoteException {if(cb!=null){mAidlCallback = cb;}}@Overridepublic void unReg(AidlCallback cb) throws RemoteException {if(cb!=null){mAidlCallback = cb;}}};}

服务端AndroidMainfest.xml代码:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.lxy.aidl_service"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="21" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >       <service android:name=".MyAIDLService">           <intent-filter>               <action android:name="com.lxy.aidl"/>               <category android:name="android.intent.category.DEFAULT"/>           </intent-filter>                  </service>    </application></manifest>

客户端MainActivity.java代码:

package com.lxy.aidl_client;import com.lxy.aidl.AidlCallback;import com.lxy.aidl.AidlService;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener {private static final String TAG = "AIDLActivity";private Button btnOk;private Button btnCancel;private Button btnCallBack;private TextView showCallback;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnOk = (Button) this.findViewById(R.id.button1);btnCancel = (Button) this.findViewById(R.id.button2);btnCallBack = (Button) this.findViewById(R.id.button3);showCallback = (TextView) this.findViewById(R.id.textView1);btnOk.setOnClickListener(this);btnCancel.setOnClickListener(this);btnCallBack.setOnClickListener(this);}private AidlService mAidlService;private ServiceConnection mConnection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {Log.d(TAG,"disconnect service");mAidlService = null;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {Log.d(TAG,"connect service");mAidlService = AidlService.Stub.asInterface(service);}};@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.button1:Log.d(TAG, "点击了绑定按钮,执行绑定aidl服务");Bundle bundle = new Bundle();Intent intent = new Intent("com.lxy.aidl");intent.putExtras(bundle);bindService(intent, mConnection, Context.BIND_AUTO_CREATE);break;case R.id.button2:Log.d(TAG, "点击了解绑按钮,执行解绑aidl服务");unbindService(mConnection);break;case R.id.button3:try {Log.d(TAG, "执行了aidi的test");mAidlService.test("ZXC");mAidlService.reg(new CallBack());} catch (Exception e) {e.printStackTrace();}break;default:break;}}private class CallBack extends AidlCallback.Stub{@Overridepublic void CallbackTest(String b) throws RemoteException {showCallback.setText("aidl回调给我的为:"+b);}}}

客户端activity_main.xml代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.lxy.aidl_client.MainActivity" >    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:text="ok" />    <Button        android:id="@+id/button2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/button1"        android:layout_centerHorizontal="true"        android:text="cancel" />    <Button        android:id="@+id/button3"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/button2"        android:layout_centerHorizontal="true"        android:text="callback" />    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/button3"        android:layout_centerHorizontal="true"        android:layout_marginTop="16dp"        android:text="" /></RelativeLayout>

客户端AndroidManifest.xml代码:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.lxy.aidl_client"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="21" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

现在看看运行的结果:

我们点击ok按钮:

会看到服务端log:


说明我们客户端已经绑定了服务端的aidl服务。

再次点击callback按钮:

会看到服务端log:

客服端显示为:


这样我们就实现了进程之间的通信。

我们点击cancel:

服务端log:



第一遍博客,不喜勿喷,互相学习。

0 0