简体   繁体   English

如何在 Android 中将 Java Socket 对象添加到 Parcelable

[英]How to add Java Socket object to Parcelable in Android

I want to pass a Java Socket object from one activity to another.我想将一个 Java Socket 对象从一个活动传递到另一个活动。 I thought of using Parcelable for passing but cannot add the object to the parcel我想过使用 Parcelable 传递但无法将对象添加到包裹中

public class NetworkInformation implements Parcelable {

    private String ipAddress;
    private String portNo;
    private Socket networkSocket;

    protected NetworkInformation(Parcel in) {
    }

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

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

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(ipAddress);
        dest.writeString(portNo);
        //How to add the Socket to parcelable here ?
    }  
}

I'm not sure if this will work, but you might try:我不确定这是否有效,但您可以尝试:

private String ipAddress;
private String portNo;
private Socket networkSocket;

protected NetworkInformation(Parcel in) {
      ipAddress = in.readString();
      portNo = in.readString();
      networkSocket = new Socket(makeRealIP(ipAddress),makeRealPortNo(portNo));
}

Of course, you would have to write your own makeRealIP and makeRealPortNo to convert the strings back into useful parameters for a new Socket();当然,您必须编写自己的 makeRealIP 和 makeRealPortNo 才能将字符串转换回新的 Socket() 有用的参数;

Bundle myBundle = new Bundle();
NetworkInformation myNetworkInfo;
myBundle.putParceable("myNetworkInfo",myNetworkInfo);
myNetworkInfo = (NetworkInformation)myBundle.getParceable("myNetworkInfo");

I've not tried this, and I'll bet the other folks that answered were quite correct to warn about mucking around at the socket layer.我没有试过这个,我敢打赌,其他回答的人警告不要在套接字层乱搞是非常正确的。 It can get a bit tricky.它可能会变得有点棘手。 Good Luck.祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM