天天看點

向廣播發送自定義類型的對象

當要向廣播發送自定義類型的對象的時候,屬于程序間的通信。有兩種解決方式,一種是Serializable,另一種是Parcelable。

首先來看Parcelable:

用戶端(廣播發送端),有一個自定義的類,Person,現在要發送一個廣播,裡面有Person的對象person,若不對這個類做任何處理,是肯定會報錯的。那麼,現在用Parcelable解決如下:

public class Person implements Parcelable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 187L;
	private String name;
	private int age;

	public Person(){
		
	}
	
	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}
	
	public void displayPerson(){
		Log.i("Person", "name:" + name + "  age:" + age);
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(name);
		dest.writeInt(age);
	}
	
	private Person readFromParcel(Parcel source){
		this.name = source.readString();
		this.age = source.readInt();
		return this;
	}
	
	public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() {
		public Person[] newArray(int size) {
            return new Person[size];
        }
        public Person createFromParcel(Parcel source) {
            return new Person().readFromParcel(source);
        }
	};

}
           

在client端發送廣播:

Intent intent = new Intent(ACTION);
			intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
			Person person = new Person("jack_" + i, i);	
			Bundle bundle = new Bundle();
			bundle.putParcelable(MESSAGE, person);
			intent.putExtras(bundle);
           

Person類實作Parcelable,然後複寫writeToParcel和CREATOR,并且自定義一個read方法。

将該類連同包一起複制到服務端(廣播接受方)。在廣播接收方讀出該對象:

Bundle bundle = intent.getExtras();
				Person person = (Person) bundle.getParcelable(MESSAGE);	
           

這樣就可以取到自定義類型的對象了。

第二種方式,讓Person類實作Serializable

不需要再添加任何其他代碼。

發送:

Bundle bundle = new Bundle();
			bundle.putSerializable(MESSAGE, person);
			intent.putExtras(bundle);
			sendBroadcast(intent);
           

在服務端讀取:

Bundle bundle = intent.getExtras();	
				Person person = (Person) bundle.getSerializable(MESSAGE);
           

這樣也可以讀取到自定義的對象。

在使用Serializable的時候要注意一個非常重要的問題,用戶端的Person類和服務端的Person類的serialVersionUID必須一緻。

使其一緻有兩個方式,第一種是顯示指定,如:

private static final long serialVersionUID = 187L;
           

另一種是不指定serialVersionUID的值,然後将用戶端的Person類拷貝到服務端(包保持一緻;服務端的Person類拷過去亦可)。否則将讀取失敗。