遠端service
AIDL
每個應用程式都運作在自己的獨立程序中,
并且可以啟動另一個應用程序的服務,
而且經常需要在不同的程序間傳遞資料對象。
在Android平台,一個程序不能直接通路另一個程序的記憶體空間,
是以要想對話,需要将對象分解成作業系統可以了解的基本單元(例如基本資料類型),
并且有序的通過程序邊界。
AIDL (Android Interface Definition Language)
用于生成可以在Android裝置上兩個程序之間
進行程序間通信(interprocess communication, IPC)的代碼。
如果在一個程序中(例如Activity)要調用另一個
程序中(例如Service)對象的操作,就可以使用AIDL生成可序列化的參數。
練習例子
首先定義AIDL接口
這個AIDL接口和接口的類很像,我們可以先定義一個這樣的接口
然後再進行适當的修改就可以了
建立檔案:IStudentService.aidl
package com.example.service;
import com.example.service.Student;
interface IStudentService
{
Student getStudentById(int id);
}
編寫AIDL需要注意:
1.接口名和aidl檔案名相同.
2.接口和方法前不用加通路權限修飾符public,private,protected等,也不能用final,static.
3.aidl預設支援的類型包話java基本類型(int,long,boolean等)和(String,List,Map,CharSequence),
使用這些類型時不需要import聲明.對于List和Map中的元素類型必須是aidl支援的類型.
如果使用自定義類型作為參數或傳回值,自定義類型必須實作Parcelable接口.
4.自定義類型和aidl生成的其它接口類型在aidl描述檔案中,應該顯式import,
即便在該類和定義的包在同一個包中.
5.在aidl檔案中所有非Java基本類型參數必須加上in、out、inout标記,
以指明參數是輸入參數、輸出參數還是輸入輸出參數.
6.Java原始類型預設的标記為in,不能為其它标記.
然後建立自定義類型Student
package com.example.service;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
public class Student implements Parcelable
{
private int id;
private String name;
private double price;
@Override
public int describeContents()
{
return 0;
}
// 将目前對象的屬性資料打成包: 寫到包對象中
@Override
public void writeToParcel(Parcel dest, int flags)
{
Log.e("TAG", "打包 writeToParcel()");
// id
dest.writeInt(id);
// name
dest.writeString(name);
// price
dest.writeDouble(price);
}
// 添加一個靜态成員,名為CREATOR,該對象實作了Parcelable.Creator接口
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>()
{
// 解包: 讀取包中的資料并封裝成對象
@Override
public Student createFromParcel(Parcel source)
{
Log.e("TAG", "解包 createFromParcel()");
// id
int id = source.readInt();
// name
String name = source.readString();
// price
double price = source.readDouble();
return new Student(id, name, price);
}
// 傳回一個指定大小的對象容器
@Override
public Student[] newArray(int size)
{
return new Student[size];
}
};
public Student(int id, String name, double price)
{
super();
this.id = id;
this.name = name;
this.price = price;
}
public Student()
{
super();
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
@Override
public String toString()
{
return "Student [id=" + id + ", name=" + name + ", price=" + price+ "]";
}
}
然後定義自定義類型的AIDL接口
建立檔案:Student.aidl
package com.example.service;
parcelable Student;
然後會自動生成一個通信接口類
粘出來給看看吧
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: E:\\Android\\WorkSpace\\Service\\src\\com\\example\\service\\IStudentService.aidl
*/
package com.example.service;
public interface IStudentService extends android.os.IInterface
{
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements
com.example.service.IStudentService
{
private static final java.lang.String DESCRIPTOR = "com.example.service.IStudentService";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an com.example.service.IStudentService
* interface, generating a proxy if needed.
*/
public static com.example.service.IStudentService asInterface(
android.os.IBinder obj)
{
if ((obj == null))
{
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof com.example.service.IStudentService)))
{
return ((com.example.service.IStudentService) iin);
}
return new com.example.service.IStudentService.Stub.Proxy(obj);
}
@Override
public android.os.IBinder asBinder()
{
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data,
android.os.Parcel reply, int flags)
throws android.os.RemoteException
{
switch (code)
{
case INTERFACE_TRANSACTION:
{
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_getStudentById:
{
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
com.example.service.Student _result = this
.getStudentById(_arg0);
reply.writeNoException();
if ((_result != null))
{
reply.writeInt(1);
_result.writeToParcel(reply,
android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else
{
reply.writeInt(0);
}
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements
com.example.service.IStudentService
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
@Override
public android.os.IBinder asBinder()
{
return mRemote;
}
public java.lang.String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
@Override
public com.example.service.Student getStudentById(int id)
throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
com.example.service.Student _result;
try
{
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(id);
mRemote.transact(Stub.TRANSACTION_getStudentById, _data,
_reply, 0);
_reply.readException();
if ((0 != _reply.readInt()))
{
_result = com.example.service.Student.CREATOR
.createFromParcel(_reply);
} else
{
_result = null;
}
} finally
{
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_getStudentById = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
}
public com.example.service.Student getStudentById(int id)
throws android.os.RemoteException;
}
下一步是:
在Service類中使用生成的類實作業務方法
package com.example.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class MyRemoteService extends Service
{
@Override
public IBinder onBind(Intent intent)
{
Log.e("TAG", "onBind()");
return new StudentService();
}
@Override
public boolean onUnbind(Intent intent)
{
Log.e("TAG", "onUnbind()");
return super.onUnbind(intent);
}
// 處理Student相關的業務邏輯類
class StudentService extends IStudentService.Stub
{
@Override
public Student getStudentById(int id) throws RemoteException
{
Log.e("TAG", "Service getStudentById() " + id);
return new Student(id, "jane", 10000000);
}
}
}
然後再到用戶端進行編碼的了
首先複制服務端AIDL的相關定義
自動生成一個通信接口類
在Activity中bind遠端Service,并調用業務方法
public void bindRemoteService(View v)
{
Intent intent = new Intent("com.example.service.MyRemoteService.Action");
if (conn == null)
{
conn = new ServiceConnection()
{
@Override
public void onServiceDisconnected(ComponentName name)
{
}
@Override
public void onServiceConnected(ComponentName name,IBinder service)
{
Log.e("TAG", "onServiceConnected()");
studentService = IStudentService.Stub.asInterface(service);
}
};
bindService(intent, conn, Context.BIND_AUTO_CREATE);
Toast.makeText(this, "綁定Service", 0).show();
} else
{
Toast.makeText(this, "已經綁定Service", 0).show();
}
}
到這裡是終于結束了
總的代碼
服務端
package com.example.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class MyRemoteService extends Service
{
@Override
public IBinder onBind(Intent intent)
{
Log.e("TAG", "onBind()");
return new StudentService();
}
@Override
public boolean onUnbind(Intent intent)
{
Log.e("TAG", "onUnbind()");
return super.onUnbind(intent);
}
// 處理Student相關的業務邏輯類
class StudentService extends IStudentService.Stub
{
@Override
public Student getStudentById(int id) throws RemoteException
{
Log.e("TAG", "Service getStudentById() " + id);
return new Student(id, "jane", 10000000);
}
}
}
package com.example.service;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
public class Student implements Parcelable
{
private int id;
private String name;
private double price;
@Override
public int describeContents()
{
return 0;
}
// 将目前對象的屬性資料打成包: 寫到包對象中
@Override
public void writeToParcel(Parcel dest, int flags)
{
Log.e("TAG", "打包 writeToParcel()");
// id
dest.writeInt(id);
// name
dest.writeString(name);
// price
dest.writeDouble(price);
}
// 添加一個靜态成員,名為CREATOR,該對象實作了Parcelable.Creator接口
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>()
{
// 解包: 讀取包中的資料并封裝成對象
@Override
public Student createFromParcel(Parcel source)
{
Log.e("TAG", "解包 createFromParcel()");
// id
int id = source.readInt();
// name
String name = source.readString();
// price
double price = source.readDouble();
return new Student(id, name, price);
}
// 傳回一個指定大小的對象容器
@Override
public Student[] newArray(int size)
{
return new Student[size];
}
};
public Student(int id, String name, double price)
{
super();
this.id = id;
this.name = name;
this.price = price;
}
public Student()
{
super();
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
@Override
public String toString()
{
return "Student [id=" + id + ", name=" + name + ", price=" + price+ "]";
}
}
package com.example.service;
import com.example.service.Student;
interface IStudentService
{
Student getStudentById(int id);
}
package com.example.service;
parcelable Student;
對應下面四個檔案
用戶端
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="bindRemoteService"
android:text="bind remote Service" />
<EditText
android:id="@+id/et_aidl_id"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:hint="學員ID"
android:text="3" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="invokeRemote"
android:text="調用遠端服務端的方法" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="unbindRemoteService"
android:text="unbind remote Service" />
</LinearLayout>
package com.example.client;
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.Toast;
import com.example.service.IStudentService;
import com.example.service.Student;
public class MainActivity extends Activity
{
private EditText et_aidl_id;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_aidl_id = (EditText) findViewById(R.id.et_aidl_id);
}
private ServiceConnection conn;
private IStudentService studentService;
public void bindRemoteService(View v)
{
Intent intent = new Intent("com.example.service.MyRemoteService.Action");
if (conn == null)
{
conn = new ServiceConnection()
{
@Override
public void onServiceDisconnected(ComponentName name)
{
}
@Override
public void onServiceConnected(ComponentName name,IBinder service)
{
Log.e("TAG", "onServiceConnected()");
studentService = IStudentService.Stub.asInterface(service);
}
};
bindService(intent, conn, Context.BIND_AUTO_CREATE);
Toast.makeText(this, "綁定Service", 0).show();
} else
{
Toast.makeText(this, "已經綁定Service", 0).show();
}
}
public void invokeRemote(View v) throws RemoteException
{
if (studentService != null)
{
int id = Integer.parseInt(et_aidl_id.getText().toString());
Student student = studentService.getStudentById(id);
Toast.makeText(this, student.toString(), 0).show();
}
}
public void unbindRemoteService(View v)
{
if (conn != null)
{
unbindService(conn);
conn = null;
studentService = null;
Toast.makeText(this, "解綁Service", 0).show();
} else
{
Toast.makeText(this, "還未綁定Service", 0).show();
}
}
}
還需要導入服務端AIDL的相關定義
比如
Student.java
IStudentService.aidl
Student.aidl