我想从一个活动传递一个Java Socket对象到另一个。我想用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 ?
}
}
我不知道这是否会工作,但你可以试试:
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));
}
当然,你会写自己的makeRealIP和makeRealPortNo到字符串转换回为一个新的Socket有用的参数();
Bundle myBundle = new Bundle();
NetworkInformation myNetworkInfo;
myBundle.putParceable("myNetworkInfo",myNetworkInfo);
myNetworkInfo = (NetworkInformation)myBundle.getParceable("myNetworkInfo");
我还没有试过,我敢打赌其他人认为回答是相当正确的警告在套接字层碴周围。它可以得到一个有点棘手。祝好运。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句