簡體   English   中英

與android的線程和網絡

[英]Threads and networking with android

美好的一天,

我正忙着為一個Android應用程序編寫一個網絡類,它將利用手機上的無線tcp連接。

下面這個類是我到目前為止編碼的。 但是在編碼時我忘記了它的多線程方面。

網絡課程:

// Network Class That controls all the connecting, sending of data and recieving of data over the tcp protocol
public class Network {

    // GLOBAL VARIABLE DELERATIONS
    public Socket TCPSocket;
    public OutputStream out;
    public BufferedReader in;
    public InetAddress serverAddr;
    // Servers IP address
    public String SERVERIP;
    // Servers Port no.
    public int SERVERPORT;

    BufferedReader stdIn;

    // Constructor
    public Network() {

        // Set The IP of the server
        SERVERIP = "41.134.61.227";
        // Define the port for the socket
        SERVERPORT = 8020;
        // Resolve the ip adress
        try {
            serverAddr = InetAddress.getByName(SERVERIP);
            Log.i("IP Adress: ", "Has been resolved");
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * Connect to the server socket
     * 
     * @return a boolean indicating if the connection was successful
     */
    public boolean connect() {

        // Create the Socket Connections
        try {
            Log.i("TCP is attempting to establish a connection", null);
            TCPSocket = new Socket(serverAddr, SERVERPORT);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("TCP Connection error :", e.toString());
            return false; // Returns if the connection was unsuccessful
        }
        Log.i("TCP Connection :", "Connected");
        return true; // Returns if the connection was successful
    }

    /**
     * Disconnect from the server socket: Method to Call once you are done with
     * the network connection, Disconnects the socket from the server
     */
    public void disconnect() {

        try {
            out.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } // Close the out Stream

        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // stdIn.close();
        try {
            TCPSocket.close(); // Close the TCP Socket
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.i("TCP Connection :", "Disconnected");
    }

    /**
     * Send: Function that will transmit data aver the tcp socket (network)
     * 
     * @param data
     *            the packet in raw data form, recieves a byte array
     * @return Returns a boolean if the transaction was successful.
     */
    // Function that will transmit the data over the tcp socket.
    public boolean send(byte[] data) {
        try {
            out.write(data); // Write the data to the outStream
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false; // Return false if the TCP Transmit failed or
                            // encounted an error
        }
        return false;
    }

    // Function that will return the data that has been recieved on the tcp
    // connection from the server

    /**
     * Recieve: Function that recives data from the socket.
     * 
     * @return
     */
    public byte[] recieve() {

        return null;
    }

我需要做什么才能將我的類轉換為使用線程?

它需要在自己的線程上運行哪些部分?

我認為只有接收需要它自己的線程? 因為發送只在你打電話時運行?

對於noob問題很抱歉,這是我第一次嘗試編寫網絡應用程序,而不僅僅是從網上處理一些示例代碼。 我最初遵循本教程: NETWORKING TUTORIAL ,我沒有完全站在他們運行方法的tcp類。

那么總結一下我的問題,哪些特定的部分,當網絡需要但在不同的線程上運行? 謝謝

謝謝

我只是在不同的線程上運行所有類。 那么......你如何轉換一個類來使用線程? 我認為那是你實際上不確定的部分。 這很簡單......它可以像在線程中使用類一樣簡單:

new Thread(new Runnable(){
  public void run() {
    new Network().connect();
  }
}).start();

這將在單獨的線程上運行您的代碼,您甚至不必修改類。 所以...說...讓我們談談Android(上面的代碼片段是純Java,但這只是冰山一角)。

在Android上,使用線程以避免阻止UI非常重要; 可以使用上面的代碼片段來完成,但這種方法可能會導致一些問題。 所以你必須學習這個規則: 我不會在外部線程中更改我的UI 所以這里的問題是:“ 我應該如何更新我的UI以反映我的工作線程的變化? ”。

有很多方法......最流行的是AsyncTask類。 它基本上允許您運行后台線程並提供以安全的方式更新UI的方法。 如果您知道在AsyncTask運行時不會完成Activity則它們非常有用。

如果您正在運行更多長期任務,則最好使用Service 有一些奇特的方法可以在服務上運行后台線程 ; 但你也可以自己做。

任何可以阻止的東西都應該在不同的線程上運行。 這將是發送數據,接收數據或連接的任何嘗試。 在服務器上它將包括接受。

你想要在后台線程上運行的所有網絡(接收和發送),例如在AsynTask中 ,因為它將阻止你的UI線程。 讓您的Networkextends AsyncTask並實現文檔中顯示的所需方法。

是否所有的在你的后台任務doInBackground()然后操縱在你的結果onPostExecute()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM