2017-02-09 22 views
0

我一直在努力通過3個不同的教程來獲得一個無頭碎片來打開套接字並保持生命週期變化。我認爲我非常接近,但最後有一個因素可以逃脫我。用於打開套接字和線程的片段的內容是基於一個相當好的類,因此我不太關心那個部分,至少現在是如此。這裏是片段的相關部分,其餘的部分放在其中,以使其不太酷。我想要做的是傳入一個P2P組所有者的IP和端口。 (沒有問題)帶參數的無頭片段,如何使用Fragment.newInstance?

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? 謝謝。

+0

爲什麼你使用Fragments這個,而不是服務? –

回答

0

你必須在創建它之後添加片段。由於它是無頭的,你不需要容器ID:

getSupportFragmentManager() 
    .beginTransaction() 
    .add(mConnection, TAG) 
    .commit(); 
+0

謝謝Krylez!你從很多痛苦中拯救了我。 –