繁体   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