Android高手進階教程(二十五)之—Android 中的AIDL!!!

來源:互聯網
上載者:User

大家好,好久不見,今天要給大家分享的是android aidl的使用。在Android中, 每個應用程式都可以有自己的進程. 在寫UI應用的時候, 經常要用到Service. 在不同的進程中, 怎樣傳遞對象呢? 顯然, Java中不允許跨進程記憶體共用. 因此傳遞對象, 只能把對象拆分成作業系統能理解的簡單形式, 以達到跨界對象訪問的目的. 在J2EE中,採用RMI的方式, 可以通過序列化傳遞對象. 在Android中, 則採用AIDL的方式. 理論上AIDL可以傳遞Bundle,實際上做起來卻比較麻煩.
 

AIDL(AndRoid介面描述語言)是一種借口描述語言; 編譯器可以通過aidl檔案產生一段代碼,通過預先定義的介面達到兩個進程內部通訊進程的目的. 如果需要在一個Activity中, 訪問另一個Service中的某個對象, 需要先將對象轉化成AIDL可識別的參數(可能是多個參數), 然後使用AIDL來傳遞這些參數, 在訊息的接收端, 使用這些參數組裝成自己需要的對象.
 

AIDL的IPC的機制和COM或CORBA類似, 是基於介面的,但它是輕量級的。它使用代理類在用戶端和實現層間傳遞值. 如果要使用AIDL, 需要完成2件事情: 1. 引入AIDL的相關類.; 2. 調用aidl產生的class.
 

 

今天的兩個執行個體用到兩個Android工程,一個是AIDL的服務端另一個是用戶端。

 

服務端的實現步驟:

首先看一下服務端,工程目錄如下:

首先建立IaidlServerService.aidl檔案,代碼如下(一個簡單方法,另一個返回對象方法),當我們點擊儲存時會在gen目錄下產生對應的java檔案,如紅色部分:

 

package com.chapter8.aidl;<br />import com.chapter8.aidl.Book;<br />interface IAIDLServerService { </p><p>String sayHello();</p><p>Book getBook();<br />}
 

第二步:因為這個介面裡有傳遞對象,所以對象要特殊處理一下,這裡繼承了Parcelable,Book.java代碼如下:

如果大家不明的地方,請參見,下面串連的文章:

Android高手進階教程(十七)之---Android中Intent傳遞對象的兩種方法(Serializable,Parcelable)!

package com.chapter8.aidl;<br />import android.os.Parcel;<br />import android.os.Parcelable;<br />public class Book implements Parcelable {</p><p>private String bookName;<br />private int bookPrice;</p><p>public Book(){</p><p>}</p><p>public Book(Parcel parcel){<br />bookName = parcel.readString();<br />bookPrice = parcel.readInt();<br />}</p><p>public String getBookName() {<br />return bookName;<br />}<br />public void setBookName(String bookName) {<br />this.bookName = bookName;<br />}<br />public int getBookPrice() {<br />return bookPrice;<br />}<br />public void setBookPrice(int bookPrice) {<br />this.bookPrice = bookPrice;<br />}</p><p>public int describeContents() {<br />return 0;<br />}<br />public void writeToParcel(Parcel parcel, int flags) {<br />parcel.writeString(bookName);<br />parcel.writeInt(bookPrice);<br />}</p><p>public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() {<br />public Book createFromParcel(Parcel source) {</p><p>return new Book(source);<br />}<br />public Book[] newArray(int size) {<br />return new Book[size];<br />}<br />};<br />}<br />
 

第三步:寫一個與Book類對應的aidl,命名為Book.aidl,代碼非常簡單,代碼如下:

parcelable Book;
 

第四步:建立一個名為AidlServerService的Service.代碼如下:

package com.chapter8.aidl;<br />import com.chapter8.aidl.IAIDLServerService.Stub;<br />import com.chapter8.aidl.IAIDLServerService;<br />import android.app.Service;<br />import android.content.Intent;<br />import android.os.IBinder;<br />import android.os.RemoteException;<br />public class AidlServerService extends Service {<br />@Override<br />public IBinder onBind(Intent intent) {<br />return mBinder;<br />}<br />/**<br /> * 在AIDL檔案中定義的介面實現。<br /> */<br />private IAIDLServerService.Stub mBinder = new Stub() {</p><p>public String sayHello() throws RemoteException {<br />return "Hello";<br />}</p><p>public Book getBook() throws RemoteException {<br />Book mBook = new Book();<br />mBook.setBookName("Android應用開發");<br />mBook.setBookPrice(50);<br />return mBook;<br />}<br />};<br />}<br />
 

第五步:在AndroidManifest.xml註冊Service,代碼如下:

<?xml version="1.0" encoding="utf-8"?><br /><manifest xmlns:android="http://schemas.android.com/apk/res/android"<br /> package="com.chapter8.aidl"<br /> android:versionCode="1"<br /> android:versionName="1.0"><br /> <application android:icon="@drawable/icon" android:label="@string/app_name"><br /> <activity android:name="AidlServerActivity"<br /> android:label="@string/app_name"><br /> <intent-filter><br /> <action android:name="android.intent.action.MAIN" /><br /> <category android:name="android.intent.category.LAUNCHER" /><br /> </intent-filter><br /> </activity><br /><service android:name="AidlServerService"<br /> android:process=":remote"><br /><intent-filter><br /> <action android:name="com.chapter8.aidl.IAIDLServerService"></action><br /> </intent-filter><br /></service><br /> </application><br /></manifest>
 

第六步:運行服務端工程,到裝置上,好讓用戶端調用,服務端的Activity什麼都沒做.效果如下:

用戶端的具體實現步驟:


第一步:建立用戶端工程,目錄結構如下:

第二步:引入Aidl檔案以及用到的類,如上面的com.chapter8.aidl包。直接從服務端裡代碼copy過來就OK.

第三步:修改main.xml布局檔案,增加一個按鈕,代碼如下:

<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:orientation="vertical"<br /> android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"<br /> ><br /><TextView<br />android:id="@+id/textview"<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:text="@string/hello"<br /> /><br /><Button<br />android:id="@+id/button"<br />android:layout_width="fill_parent"<br />android:layout_height="wrap_content"<br />android:text="調用AIDL服務"<br />/><br /></LinearLayout><br />
 

第四步:修改AidlClientActivity.java代碼如下:

package com.chapter8.aidlclient;<br />import com.chapter8.aidl.IAIDLServerService;<br />import android.app.Activity;<br />import android.content.ComponentName;<br />import android.content.Intent;<br />import android.content.ServiceConnection;<br />import android.os.Bundle;<br />import android.os.IBinder;<br />import android.os.RemoteException;<br />import android.view.View;<br />import android.view.View.OnClickListener;<br />import android.widget.Button;<br />import android.widget.TextView;<br />public class AidlClientActivity extends Activity {</p><p>private TextView mTextView;<br />private Button mButton;</p><p>private IAIDLServerService mIaidlServerService = null;</p><p>private ServiceConnection mConnection = new ServiceConnection() {</p><p>public void onServiceDisconnected(ComponentName name) {<br />mIaidlServerService = null;<br />}<br />public void onServiceConnected(ComponentName name, IBinder service) {<br />mIaidlServerService = IAIDLServerService.Stub.asInterface(service);<br />//aidl通訊<br />try {<br />String mText = "Say hello: " + mIaidlServerService.sayHello() + "/n";<br />mText += "書名: " + mIaidlServerService.getBook().getBookName()+"/n";<br />mText += "價格: " + mIaidlServerService.getBook().getBookPrice();<br />mTextView.setText(mText);<br />} catch (RemoteException e) {<br />e.printStackTrace();<br />}<br />}<br />};</p><p> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main);<br /> //初始化控制項<br /> mTextView = (TextView)findViewById(R.id.textview);<br /> mButton = (Button)findViewById(R.id.button);<br /> //增加事件響應<br /> mButton.setOnClickListener(new OnClickListener(){<br />public void onClick(View v) {<br /> //bindService<br />Intent service = new Intent("com.chapter8.aidl.IAIDLServerService");<br />bindService(service, mConnection,BIND_AUTO_CREATE);<br />}</p><p> });<br /> }</p><p>}
 

第五步:運行用戶端工程,效果如下:


 

Ok,上面就完整的作了一個Aidl開發的流程,有什麼不對的地方希望大家多多指教,今天就講到這裡。謝謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.