问题描述
我一直在研究3个不同的教程,以获取一个无头的片段来打开套接字并通过生命周期更改保持打开状态。 我想我真的很接近,但是有一个最后的要素让我逃脱了。 用于打开套接字和线程的片段的内容基于一个运行良好的类,因此至少在现在,我不太关心该部分。 这是该片段的相关部分,其余部分则省略了部分内容,以减少阅读的麻烦。 我想做的是传递p2p组所有者的IP和端口。 (没有问题)
public class ConnectionFragment extends Fragment {
private InetAddress mGoAddress;
private int mGoPort;
private Client mClient;
private static final String TAG = "Connection";
private static final String CLIENT_TAG = "Client";
private Server mServer;
private Socket mSocket;
private ConnectionFragmentListener mListener;
public static ConnectionFragment newInstance(InetAddress address, int port){
Bundle bundle = new Bundle();
bundle.putSerializable("GoAddress", address);
bundle.putInt("GoPort", port);
ConnectionFragment fragment = new ConnectionFragment();
fragment.setArguments(bundle);
return fragment;
}
private void readBundle(Bundle bundle){
if (bundle != null){
mGoAddress = (InetAddress)bundle.getSerializable("GoAddress");
mGoPort = bundle.getInt("GoPort");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
readBundle(getArguments());
mGoAddress = (InetAddress) getArguments().getSerializable("GoAddress");
mGoPort = getArguments().getInt("GoPort");
mServer = new Server();
}
然后,在我的活动中,我将其分配给组所有者IP和端口。
mConnection = ConnectionFragment.newInstance(goInetAddress, prefixedPort);
我的问题是,下一步要运行mConnection吗? 谢谢。
1楼
创建片段后,您必须添加该片段。 由于它是无头的,因此您不需要容器ID:
getSupportFragmentManager()
.beginTransaction()
.add(mConnection, TAG)
.commit();