0

我对 Android 应用程序开发有点陌生。我已经创建了一个非常简单的应用程序,可以打开/关闭设备的手电筒。我想尝试创建一个消息应用程序,当你们都连接到 Wifi 时,您可以在其中与朋友聊天。有点像“WhatsApp”、“Viber”等。如果你能给我指导并帮助我了解如何开发这样的应用程序,我会非常高兴。

非常感谢你,奥雷尔。

4

2 回答 2

0

使用这个:

聊天服务器端

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ChatServerSide extends Activity implements View.OnClickListener {

private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
TextView tvMyIp;
Socket socket;
public static final int SERVERPORT = 6000;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_main_activity);
    iniUi();
    iniListener();

    updateConversationHandler = new Handler();

    this.serverThread = new Thread(new ServerThread());
    this.serverThread.start();
    tvMyIp.setText("Waiting devices on " + getIpAddress());

}

private void iniUi() {
    tvMyIp = (TextView) findViewById(R.id.tvMyIp);
    btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
    etInputMessage = (EditText) findViewById(R.id.etInputMesage);
    tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}

private void iniListener() {
    btnSendMsg.setOnClickListener(this);
}

@Override
protected void onStop() {
    super.onStop();

}

@Override
protected void onDestroy() {
    super.onDestroy();

}

@Override
public void onClick(View view) {
    try {

        String str = etInputMessage.getText().toString();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())),
                true
        );
        tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: "   + str + "\n");
        etInputMessage.setText("");
        out.println(str);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

class ServerThread implements Runnable {

    public void run() {
        socket = null;
        try {
            serverSocket = new ServerSocket(SERVERPORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (!Thread.currentThread().isInterrupted()) {

            try {
                socket = serverSocket.accept();
                CommunicationThread commThread = new CommunicationThread(socket);
                new Thread(commThread).start();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class CommunicationThread implements Runnable {

    private Socket clientSocket;
    private BufferedReader input;

    public CommunicationThread(Socket clientSocket) {
        this.clientSocket = clientSocket;

        try {
            this.input = new BufferedReader(new   InputStreamReader(this.clientSocket.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            String read = null;
            try {

                read = input.readLine();
                if (read == null) {
                    read = "Client has leave the chat";
                    socket.close();
                    updateConversationHandler.post(new updateUIThread(read));
                    break;
                }
                updateConversationHandler.post(new updateUIThread("Client Says: " +   read));


        }catch(IOException e){
            e.printStackTrace();
        }

    }
}

}

class updateUIThread implements Runnable {
private String msg;

public updateUIThread(String str) {
    this.msg = str;
}

@Override
public void run() {
    tvOutputMessage.setText(tvOutputMessage.getText().toString() + msg + "\n");
}

}

private String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += inetAddress.getHostAddress() + "\n";
                }

            }

        }

    } catch (SocketException e) {
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }

    return ip;
  }
}

聊天客户端

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ChatClientSide extends Activity implements View.OnClickListener {

private Handler handler = new Handler();
private Socket socket;
Button btnSendMsg;
EditText etInputMessage;
TextView tvOutputMessage;
Handler updateConversationHandler;
TextView tvMyIp;
private static final int SERVERPORT = 6000;
private static String SERVER_IP = "";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_main_activity);
    iniUi();
    iniListener();
    SERVER_IP = ActivityMain.ipToConnect;
    updateConversationHandler = new Handler();
    receiveMsg();

}

@Override
protected void onStop() {
    super.onStop();
    try {
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    try {
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private String getServerIp(Intent intent) {
    Bundle bundle = intent.getExtras();
    String ip = bundle.getString("destAdress");
    tvMyIp.setText("Is connected to " + ip);
    return ip;
}

private void iniUi() {
    tvMyIp = (TextView) findViewById(R.id.tvMyIp);
    btnSendMsg = (Button) findViewById(R.id.btnSendMsg);
    etInputMessage = (EditText) findViewById(R.id.etInputMesage);
    tvOutputMessage = (TextView) findViewById(R.id.tvOutputMessage);
}

private void iniListener() {
    btnSendMsg.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    try {

        String str = etInputMessage.getText().toString();
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())),
                true
        );
        tvOutputMessage.setText(tvOutputMessage.getText().toString() + "You Says: "   + str + "\n");
        etInputMessage.setText("");
        out.println(str);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


public void receiveMsg() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            final String host = SERVER_IP;

            BufferedReader in = null;
            try {
                socket = new Socket(host, SERVERPORT);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }

            while (true) {
                String msg = null;
                try {
                    msg = in.readLine();
                    //msgList.add(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (msg == null) {
                    break;
                } else {
                    displayMsg(msg);
                }
            }

        }
    }).start();


}

public void displayMsg(String msg) {
    final String mssg = msg;
    handler.post(new Runnable() {

        @Override
        public void run() {
            tvOutputMessage.setText(tvOutputMessage.getText().toString() + "Server Says: " + mssg + "\n");
        }
    });
}
}

chat_main_activity.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/tvMyIp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>
    </LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/btnSendMsg"
        android:layout_width="wrap_content"
        android:layout_height="80dp"
        android:text="send"
        android:layout_weight="0" />

    <EditText
        android:id="@+id/etInputMesage"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />


</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/tvOutputMessage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

    </TextView>
</LinearLayout>
</LinearLayout>
于 2014-08-21T20:46:03.640 回答
0

为此,您需要创建服务器程序,该程序将验证用户名和密码以及差异用户之间的通信..等,并且您需要根据用户查询发送响应。对于任何网络通信应用程序都包含两个组件:

  1. 服务器
  2. 客户

对于 WhatsApp android 应用程序,它是一个与 WhatsApp 服务器通信的客户端应用程序。

The server with exchange the data from one client to another client, the client may be desktop, android mobile, iPhone,...etc

Generally chat programs will implemented using sockets, and its depends upon the architecture and technologies which you will chose.

于 2013-04-12T10:25:46.057 回答