1. Development environment

1.1 Development Tools

  • IDE: AndroidStudio 2.3
  • Language: the Java
  • jdk1.8
  • Minimum support: Android4.1 or above

1.2 Test Environment

  • Redmi 4(Android 6.0.1) and Redmi Note5A(Android 7.1.2) performed flawfully.

  • Realized two Android devices in the same LAN through UDP real-time chat communication. Measured support for emoji, emoji.

  • The operation is simple, enter the IP address of the other party that needs to be connected, you can immediately communicate.

2. Demo effect

  • Enter the IP address of the peer party

  • Chat screen

  • Supports sliding to view multiple chat records

3. Code implementation process

3.1 Interface Code

First to write good chat interface code

  • The chat interface simply mimics the interface of a regular chat application

  • At the top is a TextView that displays all the chat content, and at the bottom is a text input box with a send button.

  • As shown in figure:

  • Code:

<?xml version="1.0" encoding="utf-8"? >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="20dp"
    android:paddingBottom="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="8.5"
        android:background="@drawable/shape_background_content"
        android:orientation="vertical"
        android:padding="5dp">
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/scrollView">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/tv_receive_content"
                android:textSize="18sp"
                android:textColor="#36b722"/>
        </ScrollView>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"
        android:layout_weight="1">
        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="8"
            android:layout_gravity="center"
            android:id="@+id/et_send_content"
            android:background="@drawable/shape_background_et"
            android:layout_marginRight="5dp" />

        <Button
            android:layout_width="0dp"
            android:layout_weight="1.5"
            android:layout_height="wrap_content"
            android:text="Send"
            android:layout_gravity="center"
            android:id="@+id/btn_send"
            android:background="@drawable/selector_button"/>
    </LinearLayout>
</LinearLayout>

Copy the code
  • Note: in order to make the interface more beautiful, I set the background of the button and the chat record display area above, write a shape with rounded corners and edges to achieve, download the specific demo code can be seen.

3.2 Java logic implementation

3.2.1 Udp-based Socket communication

DatagramSocket for UDP-based Socket communication

  • Sending data:
public void sendDataWithUDPSocket(String str) {
        try {
            InetAddress serverAddress = InetAddress.getByName(ipAddr);
            byte data[] = str.getBytes();
            DatagramPacket packet = new DatagramPacket(data, data.length ,serverAddress ,10025);
            socket.send(packet);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch(IOException e) { e.printStackTrace(); }}Copy the code

Received data:

 public void ServerReceviedByUdp(a){
        DatagramSocket socket;
        try {
            socket = new DatagramSocket(10025);
            while (true) {byte data[] = new byte[4*1024];
                DatagramPacket packet = new DatagramPacket(data,data.length);
                socket.receive(packet);
                String result = new String(packet.getData(),packet.getOffset() ,packet.getLength());
                if(! TextUtils.isEmpty(result)){ WordsEvent wordsEvent=new WordsEvent(result);
                    EventBus.getDefault().post(wordsEvent);

                }
                System.out.println("Received message as:"+result); }}catch (SocketException e) {
            e.printStackTrace();
        } catch(IOException e) { e.printStackTrace(); }}Copy the code
  • Close the Socket
 public void disconnect(a){
        socket.close();
        socket.disconnect();
    }
Copy the code
3.2.2 Manifests document
  • Network related permission declarations:

    <! Allow applications to change network state -->
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

    <! -- Allows applications to change WIFI connection status -->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

    <! Allow applications to access related network information -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <! Allow the application to access the network information of the WIFI card -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <! Allow applications to fully use the network
    <uses-permission android:name="android.permission.INTERNET" />
Copy the code
  • ** Activity has the following properties to avoid compression of the interface when the soft keyboard pops up and block the bar proposal content input box **
android:windowSoftInputMode="stateHidden|stateAlwaysHidden|stateUnspecified|adjustPan"
Copy the code
3.2.3 Checking IP Address validity

The regular expression is used to check the validity of the IP address entered by the user

  • Using Patern, Matcher and other classes in the Java API, using regular expressions to achieve.
  • Download demo to see the source code.

4. Download the Demo

Test perfect running Demo download address