gpt4 book ai didi

android - 在不同的进程中将自定义对象传递给 android 服务

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:15:11 24 4
gpt4 key购买 nike

我有一个服务设置为在单独的进程中启动:

<service android:name=".services.UploadService"
android:process=":UploadServiceProcess" />

我可以使用 bindService() 成功绑定(bind)到它。当我尝试通过调用 Messenger.send() 发送消息时出现问题:

service.send(Message.obtain(null, UploadService.MESSAGE_UPLOAD_REQUEST, uploadRequest));

其中 uploadRequest 是实现 Parcelable 的自定义对象

public class UploadRequest implements Parcelable {
public File file;
public boolean deleteOnUpload;<p></p>

<pre><code>public UploadRequest(File file, boolean deleteOnUpload) {
this.file = file;
this.deleteOnUpload = deleteOnUpload;
}

private UploadRequest(Parcel in) {
this.file = new File(in.readString());
}

public int describeContents() {
return 0;
}

public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.file.getPath());
}

public static final Parcelable.Creator<UploadRequest> CREATOR = new Parcelable.Creator<UploadRequest>() {
public UploadRequest createFromParcel(Parcel in) {
return new UploadRequest(in);
}
public UploadRequest[] newArray(int size) {
return new UploadRequest[size];
}
};
</code></pre>

}

我在我的服务 handleMessage 中设置了一个断点,但我的应用程序从未到达断点。但是,如果我没有使用我的自定义 UploadRequest 对象而是发送 null,我会像我预期的那样到达 handleMessage 断点,但显然我此时无法执行任何操作。我在调用 writeToParcel 返回非空字符串时验证了 file.getPath()。这让我相信我的 UploadRequest 类中有问题,但通过谷歌搜索我看不出我的类有任何问题。有什么想法吗?

最佳答案

Message member obj 的文档说:

An arbitrary object to send to the recipient. When using Messenger to send the message across processes this can only be non-null if it contains a Parcelable of a framework class (not one implemented by the application). For other data transfer use setData(Bundle). Note that Parcelable objects here are not supported prior to the FROYO release.

我的猜测是您看到了一个问题,因为您正在创建自己的 parcelable,这在跨越流程边界时是不允许的。相反,您必须将您的对象打包成一个包。这也意味着您的对象将需要实现 Serializable 但不需要是 Parcelable。

关于android - 在不同的进程中将自定义对象传递给 android 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5100527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com