AIDL
安卓中的每一個進程享有獨立的運行內存,因此進程間不能像線程間一樣,直接定義公共的變量進行通信,static的變量也不可以。今天要講的就是Android進程間通信方式的一種—–AIDL
AIDL是進程間通信接口的描述語言,它定義了兩個進程間通信的接口,比如定義一個IBookManager.aidl文件,然後編譯工具會自動生成相應的接口類IBookManager.java文件,這個文件存放在gen目錄下面。這時候我們需要在Service端去實現這個接口,Client端就可以去調用這些定義好的接口了。現在需要面對的一個問題就是,我們要怎麼去把他們連接起來。在Android的四大主件Service必須要實現的一個方法就是public IBinder onBind(Intent intent),而這個返回值IBinder 就可以用作跨進程件的傳輸和調用。接下來我們看一下代碼的實現
我們先要定義一個aidl文件
IBookManager.aidl
package com.fht.ada.binder;
import java.util.List;
interface IBookManager{
List<String> getAllBook();
void putBook(String name);
}
定義好IBookManager.aidl文件過後,我們可以在gen目錄下的com.fht.ada.binder包中看到生成了一個IBookManager.java文件(如果沒有可以手動點擊編譯或運行),打開這個文件可以看到這裏面就是一個接口public interface IBookManager extends android.os.IInterface {…}。由於自動生成的代碼有一點亂,在觀看的時候可以先格式化一下,這樣可以方便我們看到這個接口的結構。
接下來我們需要定義一個Service,讓它單獨的運行在一個進程中,在AndroidManifest.xml中的配置如下
我們讓這個服務單獨運行在:book.manager.service進程中
<service
android:name="com.fht.ada.binder.BookManagerService"
android:process=":book.manager.service" >
<intent-filter>
<action android:name="com.fht.ada.binder.BookManagerService" />
</intent-filter>
</service>
在服務中,我們需要編寫一個個內部類去實現我們的接口,並且在綁定服務的時候返回這個類的一個對象的引用
BookManagerService.java
package com.fht.ada.binder;
import java.util.ArrayList;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class BookManagerService extends Service {
private BookManager mBookManager = new BookManager();
private List<String> books = new ArrayList<String>();
@Override
public IBinder onBind(Intent intent) {
return mBookManager;
}
class BookManager extends IBookManager.Stub {
@Override
public List<String> getAllBook() throws RemoteException {
return books;
}
@Override
public void putBook(String name) throws RemoteException {
books.add(name);
}
}
}
到此,我們的服務端就寫好了,接下是我們的客戶端的實現代碼,客戶端我們選擇在一個Activity中去實現
ClientActivity.java
package com.fht.ada.binder;
import java.util.List;
import com.fht.ada.R;
import com.fht.ada.binder.BookManagerService.BookManager;
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.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ClientActivity extends Activity {
private static final String TAG = "AIDL";
private EditText mEditText;
private TextView mTextView;
private Intent mContectBookManagerService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_client);
mEditText = (EditText) findViewById(R.id.edit_book_name);
mTextView = (TextView) findViewById(R.id.show_all_book);
mContectBookManagerService = new Intent(this, BookManagerService.class);
}
@Override
protected void onStart() {
super.onStart();
this.bindService(mContectBookManagerService, mConn, Context.BIND_AUTO_CREATE);
}
public void addBook(View view) {
Log.i(TAG, "addBook(View view) ");
String bookName = mEditText.getText().toString();
if (bookName != null && "".equals(bookName.trim())) {
Toast.makeText(getApplicationContext(), "書名爲空,不能添加", Toast.LENGTH_SHORT).show();
return;
}
try {
mConn.mBookManager.putBook(mEditText.getText().toString());
} catch (RemoteException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "圖書添加成功", Toast.LENGTH_SHORT).show();
}
public void queryAllBooks(View view) {
Log.i(TAG, "queryAllBooks(View view) ");
List<String> books = null;
try {
books = mConn.mBookManager.getAllBook();
} catch (RemoteException e) {
e.printStackTrace();
}
if (books != null) {
String mid = "";
for (int i = 0; i < books.size(); i++) {
mid += i + " " + books.get(i) + "\n";
}
mTextView.setText(mid);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
this.unbindService(mConn);
}
private Connection mConn = new Connection();
class Connection implements ServiceConnection {
private IBookManager mBookManager;
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (service == null) {
Log.i(TAG, "service is null");
return;
}
mBookManager = BookManager.Stub.asInterface(service);
};
};
}
activity_client.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/edit_book_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:ems="10"
android:text="Android" >
<requestFocus />
</EditText>
<Button
android:id="@+id/add"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="addBook"
android:text="增加" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/show_all_book"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="10dp"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#FF896167"
android:paddingLeft="5dp"
android:textSize="20sp" />
<Button
android:id="@+id/query"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="queryAllBooks"
android:text="查看" />
</LinearLayout>
</LinearLayout>
至此,我們的代碼就寫完了,我們可以通過界面上的按鈕去把圖書添加到List books = new ArrayList();中,然後通過查詢按鈕去把books 中所有的書查詢出來,並且顯示在界面上。