如何使用 Parceler 库将自定义对象类型的数组列表从 activity 传递到服务?

How to pass the Arraylist of custom Object type from activity to Service using the Parceler library?

我已经在 activity.Here 中完成了 responses 变量是自定义对象 LeaseDetailResponse 类型的 ArrayList。

 Intent intent = new Intent(TestActivity.this, AlarmService.class);
    intent.putParcelableArrayListExtra(AlarmService.LEASE_DETAIL_RESPONSE_LIST, (ArrayList<? extends Parcelable>) Parcels.wrap(responses));
    startService(intent);

在报警服务处

Parcels.unwrap((Parcelable) intent.getParcelableArrayListExtra(LEASE_DETAIL_RESPONSE_LIST));

显示错误

    java.lang.ClassCastException: org.parceler.NonParcelRepository$ListParcelable cannot be cast to java.util.ArrayList

  Caused by: java.lang.ClassCastException: org.parceler.NonParcelRepository$ListParcelable cannot be cast to java.util.ArrayList

问题在于您对 ArrayList 的强制转换...Parceler 仅处理 Parcelable。您需要使用 putExtra() 而不是强制转换:

Intent intent = new Intent(TestActivity.this, AlarmService.class);
intent.putExtra(AlarmService.LEASE_DETAIL_RESPONSE_LIST, Parcels.wrap(responses));
startService(intent);

并在您的 AlarmService 中反序列化:

Parcels.unwrap(intent.getParcelableExtra(LEASE_DETAIL_RESPONSE_LIST));