android使用AIDL跨進(jìn)程通信(IPC)
AIDL的作用
AIDL (Android Interface Definition Language) 是一種IDL 語(yǔ)言,用于生成可以在Android設(shè)備上兩個(gè)進(jìn)程之間進(jìn)行進(jìn)程間通信(interprocess communication, IPC)的代碼。如果在一個(gè)進(jìn)程中(例如Activity)要調(diào)用另一個(gè)進(jìn)程中(例如Service)對(duì)象的操作,就可以使用AIDL生成可序列化的參數(shù)。
AIDL IPC機(jī)制是面向接口的,像COM或Corba一樣,但是更加輕量級(jí)。它是使用代理類在客戶端和實(shí)現(xiàn)端傳遞數(shù)據(jù)。
選擇AIDL的使用場(chǎng)合
官方文檔特別提醒我們何時(shí)使用AIDL是必要的:只有你允許客戶端從不同的應(yīng)用程序?yàn)榱诉M(jìn)程間的通信而去訪問你的service,以及想在你的service處理多線程。如果不需要進(jìn)行不同應(yīng)用程序間的并發(fā)通信(IPC),you should create your interface by implementing a Binder;或者你想進(jìn)行IPC,但不需要處理多線程的,則implement your interface using a Messenger。無(wú)論如何,在使用AIDL前,必須要理解如何綁定service——bindService。
如何使用AIDL
1.先建立一個(gè)android工程,用作服務(wù)端
創(chuàng)建一個(gè)android工程,用來(lái)充當(dāng)跨進(jìn)程通信的服務(wù)端。
2.創(chuàng)建一個(gè)包名用來(lái)存放aidl文件
創(chuàng)建一個(gè)包名用來(lái)存放aidl文件,比如com.ryg.sayhi.aidl,在里面新建IMyService.aidl文件,如果需要訪問自定義對(duì)象,還需要建立對(duì)象的aidl文件,這里我們由于使用了自定義對(duì)象Student,所以,還需要?jiǎng)?chuàng)建Student.aidl和Student.java。注意,這三個(gè)文件,需要都放在com.ryg.sayhi.aidl包里。下面描述如何寫這三個(gè)文件。
IMyService.aidl代碼如下:
package com.ryg.sayhi.aidl; import com.ryg.sayhi.aidl.Student; interface IMyService { List<Student> getStudent(); void addStudent(in Student student); }
說明:
aidl中支持的參數(shù)類型為:基本類型(int,long,char,boolean等),String,CharSequence,List,Map,其他類型必須使用import導(dǎo)入,即使它們可能在同一個(gè)包里,比如上面的Student,盡管它和IMyService在同一個(gè)包中,但是還是需要顯示的import進(jìn)來(lái)。
另外,接口中的參數(shù)除了aidl支持的類型,其他類型必須標(biāo)識(shí)其方向:到底是輸入還是輸出抑或兩者兼之,用in,out或者inout來(lái)表示,上面的代碼我們用in標(biāo)記,因?yàn)樗禽斎胄蛥?shù)。
在gen下面可以看到,eclipse為我們自動(dòng)生成了一個(gè)代理類
public static abstract class Stub extends android.os.Binder implements com.ryg.sayhi.aidl.IMyService
可見這個(gè)Stub類就是一個(gè)普通的Binder,只不過它實(shí)現(xiàn)了我們定義的aidl接口。它還有一個(gè)靜態(tài)方法
public static com.ryg.sayhi.aidl.IMyService asInterface(android.os.IBinder obj)
這個(gè)方法很有用,通過它,我們就可以在客戶端中得到IMyService的實(shí)例,進(jìn)而通過實(shí)例來(lái)調(diào)用其方法。
Student.aidl代碼如下:
package com.ryg.sayhi.aidl; parcelable Student;
說明:這里parcelable是個(gè)類型,首字母是小寫的,和Parcelable接口不是一個(gè)東西,要注意。
Student.java代碼如下:
package com.ryg.sayhi.aidl; import java.util.Locale; import android.os.Parcel; import android.os.Parcelable; public final class Student implements Parcelable { public static final int SEX_MALE = 1; public static final int SEX_FEMALE = 2; public int sno; public String name; public int sex; public int age; public Student() { } public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() { public Student createFromParcel(Parcel in) { return new Student(in); } public Student[] newArray(int size) { return new Student[size]; } }; private Student(Parcel in) { readFromParcel(in); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(sno); dest.writeString(name); dest.writeInt(sex); dest.writeInt(age); } public void readFromParcel(Parcel in) { sno = in.readInt(); name = in.readString(); sex = in.readInt(); age = in.readInt(); } @Override public String toString() { return String.format(Locale.ENGLISH, "Student[ %d, %s, %d, %d ]", sno, name, sex, age); } }
說明:通過AIDL傳輸非基本類型的對(duì)象,被傳輸?shù)膶?duì)象需要序列化,序列化功能java有提供,但是android sdk提供了更輕量級(jí)更方便的方法,即實(shí)現(xiàn)Parcelable接口,關(guān)于android的序列化,我會(huì)在以后寫文章介紹。這里只要簡(jiǎn)單理解一下就行,大意是要實(shí)現(xiàn)如下函數(shù)
readFromParcel : 從parcel中讀取對(duì)象
writeToParcel :將對(duì)象寫入parcel
describeContents:返回0即可
Parcelable.Creator<Student> CREATOR:這個(gè)照著上面的代碼抄就可以
需要注意的是,readFromParcel和writeToParcel操作數(shù)據(jù)成員的順序要一致
3.創(chuàng)建服務(wù)端service
創(chuàng)建一個(gè)service,比如名為MyService.java,代碼如下:
/** * @author scott */ public class MyService extends Service { private final static String TAG = "MyService"; private static final String PACKAGE_SAYHI = "com.example.test"; private NotificationManager mNotificationManager; private boolean mCanRun = true; private List<Student> mStudents = new ArrayList<Student>(); //這里實(shí)現(xiàn)了aidl中的抽象函數(shù) private final IMyService.Stub mBinder = new IMyService.Stub() { @Override public List<Student> getStudent() throws RemoteException { synchronized (mStudents) { return mStudents; } } @Override public void addStudent(Student student) throws RemoteException { synchronized (mStudents) { if (!mStudents.contains(student)) { mStudents.add(student); } } } //在這里可以做權(quán)限認(rèn)證,return false意味著客戶端的調(diào)用就會(huì)失敗,比如下面,只允許包名為com.example.test的客戶端通過, //其他apk將無(wú)法完成調(diào)用過程 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { String packageName = null; String[] packages = MyService.this.getPackageManager(). getPackagesForUid(getCallingUid()); if (packages != null && packages.length > 0) { packageName = packages[0]; } Log.d(TAG, "onTransact: " + packageName); if (!PACKAGE_SAYHI.equals(packageName)) { return false; } return super.onTransact(code, data, reply, flags); } }; @Override public void onCreate() { Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService"); thr.start(); synchronized (mStudents) { for (int i = 1; i < 6; i++) { Student student = new Student(); student.name = "student#" + i; student.age = i * 5; mStudents.add(student); } } mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); super.onCreate(); } @Override public IBinder onBind(Intent intent) { Log.d(TAG, String.format("on bind,intent = %s", intent.toString())); displayNotificationMessage("服務(wù)已啟動(dòng)"); return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { mCanRun = false; super.onDestroy(); } private void displayNotificationMessage(String message) { Notification notification = new Notification(R.drawable.icon, message, System.currentTimeMillis()); notification.flags = Notification.FLAG_AUTO_CANCEL; notification.defaults |= Notification.DEFAULT_ALL; PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0); notification.setLatestEventInfo(this, "我的通知", message, contentIntent); mNotificationManager.notify(R.id.app_notification_id + 1, notification); } class ServiceWorker implements Runnable { long counter = 0; @Override public void run() { // do background processing here..... while (mCanRun) { Log.d("scott", "" + counter); counter++; try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
說明:為了表示service的確在活著,我通過打log的方式,每2s打印一次計(jì)數(shù)。上述代碼的關(guān)鍵在于onBind函數(shù),當(dāng)客戶端bind上來(lái)的時(shí)候,將IMyService.Stub mBinder返回給客戶端,這個(gè)mBinder是aidl的存根,其實(shí)現(xiàn)了之前定義的aidl接口中的抽象函數(shù)。
問題:?jiǎn)栴}來(lái)了,有可能你的service只想讓某個(gè)特定的apk使用,而不是所有apk都能使用,這個(gè)時(shí)候,你需要重寫Stub中的onTransact方法,根據(jù)調(diào)用者的uid來(lái)獲得其信息,然后做權(quán)限認(rèn)證,如果返回true,則調(diào)用成功,否則調(diào)用會(huì)失敗。對(duì)于其他apk,你只要在onTransact中返回false就可以讓其無(wú)法調(diào)用IMyService中的方法,這樣就可以解決這個(gè)問題了。
4. 在AndroidMenifest中聲明service
<service android:name="com.ryg.sayhi.MyService" android:process=":remote" android:exported="true" > <intent-filter> <category android:name="android.intent.category.DEFAULT" /> <action android:name="com.ryg.sayhi.MyService" /> </intent-filter> </service>
說明:上述的 <action android:name="com.ryg.sayhi.MyService" />是為了能讓其他apk隱式bindService,通過隱式調(diào)用的方式來(lái)起activity或者service,需要把category設(shè)為default,這是因?yàn)?,隱式調(diào)用的時(shí)候,intent中的category默認(rèn)會(huì)被設(shè)置為default。
5. 新建一個(gè)工程,充當(dāng)客戶端
新建一個(gè)客戶端工程,將服務(wù)端工程中的com.ryg.sayhi.aidl包整個(gè)拷貝到客戶端工程的src下,這個(gè)時(shí)候,客戶端com.ryg.sayhi.aidl包是和服務(wù)端工程完全一樣的。如果客戶端工程中不采用服務(wù)端的包名,客戶端將無(wú)法正常工作,比如你把客戶端中com.ryg.sayhi.aidl改一下名字,你運(yùn)行程序的時(shí)候?qū)?huì)crash,也就是說,客戶端存放aidl文件的包必須和服務(wù)端一樣??蛻舳薭indService的代碼就比較簡(jiǎn)單了,如下:
import com.ryg.sayhi.aidl.IMyService; import com.ryg.sayhi.aidl.Student; public class MainActivity extends Activity implements OnClickListener { private static final String ACTION_BIND_SERVICE = "com.ryg.sayhi.MyService"; private IMyService mIMyService; private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mIMyService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { //通過服務(wù)端onBind方法返回的binder對(duì)象得到IMyService的實(shí)例,得到實(shí)例就可以調(diào)用它的方法了 mIMyService = IMyService.Stub.asInterface(service); try { Student student = mIMyService.getStudent().get(0); showDialog(student.toString()); } catch (RemoteException e) { e.printStackTrace(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (view.getId() == R.id.button1) { Intent intentService = new Intent(ACTION_BIND_SERVICE); intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE); } } public void showDialog(String message) { new AlertDialog.Builder(MainActivity.this) .setTitle("scott") .setMessage(message) .setPositiveButton("確定", null) .show(); } @Override protected void onDestroy() { if (mIMyService != null) { unbindService(mServiceConnection); } super.onDestroy(); } }
運(yùn)行效果
可以看到,當(dāng)點(diǎn)擊按鈕1的時(shí)候,客戶端bindService到服務(wù)端apk,并且調(diào)用服務(wù)端的接口mIMyService.getStudent()來(lái)獲取學(xué)生列表,并且把返回列表中第一個(gè)學(xué)生的信息顯示出來(lái),這就是整個(gè)ipc過程,需要注意的是:學(xué)生列表是另一個(gè)apk中的數(shù)據(jù),通過aidl,我們才得到的。另外,如果你在onTransact中返回false,將會(huì)發(fā)現(xiàn),獲取的學(xué)生列表是空的,這意味著方法調(diào)用失敗了,也就是實(shí)現(xiàn)了權(quán)限認(rèn)證。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳細(xì)講解Android中使用LoaderManager加載數(shù)據(jù)的方法
這篇文章主要介紹了Android中使用LoaderManager加載數(shù)據(jù)的方法,講到了LoaderManager的異步加載與聲明周期的管理等相關(guān)用法,需要的朋友可以參考下2016-04-04Android 實(shí)現(xiàn)長(zhǎng)按彈出PopupMenu 菜單欄
這篇文章主要介紹了Android 實(shí)現(xiàn)長(zhǎng)按彈出PopupMenu 菜單欄,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12Android中ListView下拉刷新的實(shí)現(xiàn)方法實(shí)例分析
這篇文章主要介紹了Android中ListView下拉刷新的實(shí)現(xiàn)方法,涉及Android操作ListView的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10非常詳細(xì)的android so庫(kù)逆向調(diào)試教程
這篇文章主要給大家介紹了關(guān)于android so庫(kù)逆向調(diào)試的相關(guān)資料,文中通過示例代碼以及圖文介紹的非常詳細(xì),對(duì)各位Android開發(fā)者具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-08-08Android UI使用HorizontalListView實(shí)現(xiàn)水平滑動(dòng)
這篇文章主要為大家詳細(xì)介紹了Android UI使用HorizontalListView實(shí)現(xiàn)水平滑動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01淺談Android應(yīng)用安全防護(hù)和逆向分析之a(chǎn)pk反編譯
我們有時(shí)候在某個(gè)app上見到某個(gè)功能,某個(gè)效果蠻不錯(cuò)的,我們想看看對(duì)方的思路怎么走的,這時(shí)候,我們就可以通過反編譯來(lái)編譯該apk,拿到代碼,進(jìn)行分析。2021-06-06Android Studio使用教程(五):Gradle命令詳解和導(dǎo)入第三方包
這篇文章主要介紹了Android Studio使用教程(五):Gradle命令詳解和導(dǎo)入第三方包,本文講解了導(dǎo)入Android Studio、Gradle常用命令等內(nèi)容,需要的朋友可以參考下2015-05-05Android編程實(shí)現(xiàn)小說閱讀器滑動(dòng)效果的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)小說閱讀器滑動(dòng)效果的方法,涉及onTouch事件滑動(dòng)效果的相關(guān)實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10Android基于注解的6.0權(quán)限動(dòng)態(tài)請(qǐng)求框架詳解
這篇文章主要介紹了Android基于注解的6.0權(quán)限動(dòng)態(tài)請(qǐng)求框架詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2018-04-04