传递 Parcelable 对象,它的成员变量不是 Parcelable(属于第三方库的类) [英] Passing Parcelable object which has a member variable which is Not parcelable(a class that belongs to third party library)

查看:57
本文介绍了传递 Parcelable 对象,它的成员变量不是 Parcelable(属于第三方库的类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将类的对象(假设 X 类的对象)作为实现 Parcelable 的类的一部分发送.我在这里面临的问题是,Class X 是某个库的一部分,我无法对其进行编辑以实现 Parcelable 或可序列化.
我已经检查过 Class X 没有实现 Parcelable 或可序列化,我们也不能改变.
你们能帮我吗?

I'm trying to send a class's object(let's say Class X's object) as part of class that implements Parcelable. The problem that I am facing here is, Class X is a part of some library and I can not edit it to implement Parcelable or serializable.
I've checked that Class X does not implement Parcelable or serializable and we can not change as well.
Can you guys please help me here?

主要活动:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Start the service.
        DummyParcelableObject mObj = new DummyParcelableObject(new RandomClass(2019));
        Intent serviceIntent = new Intent(MainActivity.this, SampleService.class);
        serviceIntent.putExtra("myObj", mObj);
        startService(serviceIntent);
    }
}

Dummy Parcelable 类:

Dummy Parcelable class:

class DummyParcelableObject implements Parcelable {

    RandomClass mRandomClass;

    public DummyParcelableObject(RandomClass obj) {
        mRandomClass = obj;
    }

    protected DummyParcelableObject(Parcel in) {
        mRandomClass = (RandomClass) in.readValue(RandomClass.class.getClassLoader());
    }

    public static final Creator<DummyParcelableObject> CREATOR = new Creator<DummyParcelableObject>() {
        @Override
        public DummyParcelableObject createFromParcel(Parcel in) {
            return new DummyParcelableObject(in);
        }

        @Override
        public DummyParcelableObject[] newArray(int size) {
            return new DummyParcelableObject[size];
        }
    };

    public int getRandomVar() {
        int n = 0;

        if (mRandomClass != null)
        {
            System.out.println("Anil: DummyParcelableObject: if (mRandomClass != null) is true.\n");
            n = mRandomClass.getNumb();
        }
        else
        {
            System.out.println("Anil: DummyParcelableObject: if (mRandomClass != null) is false.\n");
        }

        return n;
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeValue(mRandomClass);
    }
}

属于另一个库的 X 类:

Class X that is part of another library:

class RandomClass{
    public static int cnt = 0;
    private int nRandomNumber = 0;
    public RandomClass(int n)
    {
        nRandomNumber = n;
    }

    public int getNumb()
    {
        return nRandomNumber;
    }
}

我们需要将数据发送到的服务:

Service that we need to send the data to:

public class SampleService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        DummyParcelableObject obj = intent.getParcelableExtra("mObj");
        if (obj == null) {
            System.out.println("\nAnil: ParcelableExtra is null");
        }
        else {
            System.out.println("\nAnil: ParcelableExtra is not null");
            System.out.println("\nAnil: obj.getRandomVar() = " + obj.getRandomVar());
        }

        return START_STICKY;
    }
}

推荐答案

如果你不能实现 ParcelableSerializable,就只剩下一个选择了:将对象通过全局状态.

If you cannot implement Parcelable or Serializable, there is only one option left: passing the object through global state.

RandomClass 类型的静态字段添加到 DummyParcelableObject,例如randomClassStatic.在启动服务之前设置它:

Add a static field of the type RandomClass to DummyParcelableObject, e.g. randomClassStatic. Set it just before starting the service:

// Start the service.
DummyParcelableObject mObj = new DummyParcelableObject(new RandomClass(2019));
Intent serviceIntent = new Intent(MainActivity.this, SampleService.class);
serviceIntent.putExtra("myObj", mObj);
DummyParcelableObject.randomClassStatic = mObj.getRandomClass();
startService(serviceIntent);

然后在 onStartCommand() 中服务启动后立即检索它:

Then retrieve it right after the service started in onStartCommand():

DummyParcelableObject obj = intent.getParcelableExtra("mObj");
obj.setRandomClass(DummyParcelableObject.randomClassStatic);
DummyParcelableObject.randomClassStatic = null;

您需要相应地定义 getRandomClass()setRandomClass() 以获取/设置 mRandomClass.

You would need to define getRandomClass() and setRandomClass() accordingly for getting / setting mRandomClass.

请注意,就并发性、对象的生命周期等而言,这不是最安全的做法……

Note that this is not the safest thing to do in regard of concurrency, objects' life cycles, etc…

仅当您在两端都可以访问 ActivityService 时才能使用此功能.

This can only be used if you have access to an Activity or Service on both ends.

子类 Application 并向其添加 RandomClass 类型的字段.它将作为中继.定义获取/设置该字段的公共方法(例如 getRandomClass()setRandomClass()).不要忘记在清单中引用您的子类 Application,如 此处.启动服务前:

Subclass Application and add a field of type RandomClass to it. It will serves as relay. Define public methods for getting / setting this field (e.g. getRandomClass() and setRandomClass()). Do not forget to reference your subclassed Application in the manifest as described here. Before starting the service:

// Start the service.
DummyParcelableObject mObj = new DummyParcelableObject(new RandomClass(2019));
Intent serviceIntent = new Intent(MainActivity.this, SampleService.class);
serviceIntent.putExtra("myObj", mObj);
((MyApplication) getApplication()).setRandomClass(mObj.getRandomClass());
startService(serviceIntent);

然后在服务启动后检索对象,仍在onStartCommand()中:

Then for retrieving the object once the service started, still in onStartCommand():

DummyParcelableObject obj = intent.getParcelableExtra("mObj");
obj.setRandomClass(((MyApplication) getApplication()).getRandomClass());
DummyParcelableObject.randomClassStatic = null;

这样做的好处是不使用静态字段,但如果处理不当(线程安全、不检查无效性……),仍然可能成为错误的来源.

This has the benefit of not using a static field, but can still be a source of bugs if handled poorly (thread safety, no checks on nullity, …).

这篇关于传递 Parcelable 对象,它的成员变量不是 Parcelable(属于第三方库的类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆