将变量传入和传出 GCM 任务服务

Passing variables in and out of GCM task service

我使用的 GCM network manager and I want to pass the service (specifically to the onRunTask(TaskParams taskParams) some objects. From the documentation taskParams 只是一个字符串和一个包,但我想传递更复杂的对象。

如何做到这一点?

谢谢!

一种方法是让您的自定义对象实现 Parcelable 接口并使用 Bundle.putParcelable/Bundle.getParcelable。

使用它比使用 Java 的本机序列化需要更多的努力,但速度更快(我的意思是,速度快得多)。

例如:

public class MyParcelable implements Parcelable {
 private int mData;

 public int describeContents() {
     return 0;
 }

 public void writeToParcel(Parcel out, int flags) {
     out.writeInt(mData);
 }

 public static final Parcelable.Creator<MyParcelable> CREATOR
         = new Parcelable.Creator<MyParcelable>() {
     public MyParcelable createFromParcel(Parcel in) {
         return new MyParcelable(in);
     }

     public MyParcelable[] newArray(int size) {
         return new MyParcelable[size];
     }
 };

 private MyParcelable(Parcel in) {
     mData = in.readInt();
 }

}

您还可以阅读Parcelable vs Serializable