1> 创建自定义类型,并实现Parcelable接口,使其支持parcelable协议。如:在cn.jp.domain包下创建Person.java:
package cn.jp.domain; import android.os.Parcel; import android.os.Parcelable; public class Person implements Parcelable private Integer id; private String name; public Person(){} public Person(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) {//把javanbean中的数据写到Parcel dest.writeInt(this.id); dest.writeString(this.name); } //添加一个静态成员,名为CREATOR,该对象实现了Parcelable.Creator接口 public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>(){ @Override public Person createFromParcel(Parcel source) {//从Parcel中读取数据,返回person对象 return new Person(source.readInt(), source.readString()); } @Override public Person[] newArray(int size) { return new Person[size]; } }; }2> 在自定义类型所在包下创建一个aidl文件对自定义类型进行声明,文件的名称与自定义类型同名。
package cn.jp.domain; parcelable Person;
package cn.itcast.aidl; import cn.itcast.domain.Person; interface IPersonService { void save(in Person person); }
public class ServiceBinder extends IPersonService.Stub { @Override public void save(Person person) throws RemoteException { Log.i("PersonService", person.getId()+"="+ person.getName()); } }
public class PersonService extends Service { private ServiceBinder serviceBinder = new ServiceBinder(); @Override public IBinder onBind(Intent intent) { return serviceBinder; } public class ServiceBinder extends IPersonService.Stub { @Override public void save(Person person) throws RemoteException { Log.i("PersonService", person.getId()+"="+ person.getName()); } } }
<service android:name=".PersonService" > <intent-filter> <action android:name="cn.jp.process.aidl.PersonService " /> </intent-filter> </service>
public class ClientActivity extends Activity { private IPersonService personService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.bindService(new Intent("cn.jp.process.aidl.PersonService"), this.serviceConnection, BIND_AUTO_CREATE);//绑定到服务 } @Override protected void onDestroy() { super.onDestroy(); this.unbindService(serviceConnection);//解除服务 } private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { personService = IPersonService.Stub.asInterface(service); try { personService.save(new Person(56,"liming")); } catch (RemoteException e) { Log.e("ClientActivity", e.toString()); }