WIFI debugging assistant Two Use guide

This code only supports hexadecimal sending and receiving, mainly referring to the WiFi client modified by the hexadecimal sending and receiving of Bluetooth.
Basic configuration method of WiFi: https://blog.csdn.net/weixin_44244812/article/details/104303322
When I use the Android WiFi client, my android Five The version of mobile phone can connect to WiFi, send and receive data, while the developed APP is in the advanced version of big boss (such as ten edition, Eight Version) of Android can only connect, can not send and receive data, so painstakingly designed apps become useless. Great sorrow.
I'm looking for reasons and solutions, like this blogger's article https://blog.csdn.net/banzhihuanyu/article/details/81056561 , I'd like to click it. I find that the Android version of WiFi is really messy. I'm not a professional Android Studio either. I just want to be an embedded engineer and an APP as the upper computer. I found a lot of demo s on the Internet, and found that there are many people in the water integral. It should be that all kinds of solutions were effective at that time. Now the Android version has changed too much.
Finally, God rewards the diligent, and Kung Fu is not inferior to the willing. Finally, this problem is solved. If you have downloaded my old WiFi debugging assistant, send me a private message, and I will send you the latest one. If you have any problems, please let me know. I will use an old version of mobile phone, and you need your test and feedback to create a better WIFI_APP host computer.
WiFi Teaser assistant Two Download address: https://download.csdn.net/download/weixin_44244812/12356294
If you are a VIP, please support me and send me some points. I am not a VIP. Every time I download the design demo about WiFi, I feel distressed. Your billion point support is the driving force for my growth. The point support chain: https://download.csdn.net/download/weixin_44244812/12356294
DEMO introduction:
The interface is as follows:

Get IP related code:
private WifiManager wifiManager;
//Server Manager
private DhcpInfo dhcpInfo;
private int wificonnection=0;













private void wifi_Init() {
//Get the IP address of the server
wifiManager = (WifiManager) getApplicationContext(). getSystemService(Context.WIFI_SERVICE);
dhcpInfo = wifiManager.getDhcpInfo();
IPadress = Formatter.formatIpAddress(dhcpInfo.gateway);
ipadress_st.setText(IPadress);
}
I am lazy. If there is no point, please copy and paste it yourself:
Structure block diagram:

AndroidManifest.xml









<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.bkrc.car2019.socket_connect">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/bkrckj_logo"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:icon, android:theme">
        <activity android:name="com.bkrc.car2019.socket_connect.MainActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateAlwaysHidden|adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity

package com.bkrc.car2019.socket_connect;

import android.content.Context;
import android.content.res.Configuration;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {

    private byte[] mByte = new byte[11];
    private TextView Data_show_st =null;
    private EditText ipadress_st = null,ipcom_st=null,Data_send_st=null;
    private Button clear_receive_st,getClear_send_st,send_st,get_ip_st,connection_st;
    private connect_transport sock_con;
    private WifiManager wifiManager;
    // server manager
    private DhcpInfo dhcpInfo;
    private int wificonnection=0;
    static String IPadress;
    static ExecutorService executorServicetor = Executors.newCachedThreadPool();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        control_init();
        sock_con =new connect_transport();

    }

    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }
    //WiFi initialization
    private void wifi_Init() {
        // Get the IP address of the server
        wifiManager = (WifiManager) getApplicationContext(). getSystemService(Context.WIFI_SERVICE);
        dhcpInfo = wifiManager.getDhcpInfo();
        IPadress = Formatter.formatIpAddress(dhcpInfo.gateway);
        ipadress_st.setText(IPadress);
    }



    private void control_init()
    {
        ipadress_st=(EditText) findViewById(R.id.ipadress);
        ipcom_st=(EditText)findViewById(R.id.com);
        Data_show_st =(TextView) findViewById(R.id.rvdata);
        Data_send_st =(EditText) findViewById(R.id.senddata);

        clear_receive_st=(Button)findViewById(R.id.reclear);
        getClear_send_st=(Button)findViewById(R.id.sendclear);
        send_st=(Button)findViewById(R.id.sendto);

        connection_st=(Button)findViewById(R.id.buttonconnection);
        get_ip_st=(Button)findViewById(R.id.buttonip);

        clear_receive_st.setOnClickListener(new onClickListener());
        getClear_send_st.setOnClickListener(new onClickListener());
        send_st.setOnClickListener(new onClickListener());
        connection_st.setOnClickListener(new onClickListener());
        get_ip_st.setOnClickListener(new onClickListener());

    }

    // Accept data from display trolley
    private Handler recvhandler = new Handler() {
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
              // mByte = (byte[]) msg.obj;
                String result = msg.getData().get("msg").toString();
                result+=" ";
                Data_show_st.append(result);
            }
        }
    };


    private class onClickListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v) {

            switch(v.getId())
            {
                case R.id.reclear:
                    Data_show_st.setText(null);
                    break;
                case R.id.sendclear:
                    Data_send_st.setText(null);
                    break;
                case R.id.sendto:
                    sock_con.send(Data_send_st.getText().toString());
                    break;
                case R.id.buttonconnection:
                    if(wificonnection==1){
                        connection_st.setText("Not connected");
                        sock_con .destory();
                        wificonnection=0;
                    }
                    else {
                        executorServicetor.execute(new Runnable() {
                            @Override
                            public void run() {
                                if (wificonnection == 0) {
                                    try {
                                        sock_con.connect(recvhandler, ipadress_st.getText().toString(), Integer.valueOf(ipcom_st.getText().toString(), 10));
                                        connection_st.setText("Connected");
                                        wificonnection = 1;
                                    } catch (Exception e) {
                                        //Toast.makeText(MainActivity.this , "prompt: connection failed", Toast.LENGTH_SHORT).show();

                                    }

                                }

                            }
                        });
                    }

                    break;
                case R.id.buttonip:
                    wifi_Init();
                    break;
                default:
                    break;

            }
        }
    }
    private class onLongClickListener2 implements View.OnLongClickListener {
        @Override
        public boolean onLongClick(View view) {

            return true;
        }
    }


}

connect_transport

package com.bkrc.car2019.socket_connect;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class connect_transport {

	public static DataInputStream bInputStream = null;
	public static DataOutputStream bOutputStream =null;
	public static Socket socket = null;
	private byte[] rbyte = new byte[40];
	private Handler reHandler;



	public short TYPE=0xAA;
	public short MAJOR = 0x00;
	public short FIRST = 0x00;
	public short SECOND = 0x00;
	public short THRID = 0x00;
	public short CHECKSUM=0x00;
	private byte[] msg = new byte[6000];

	public void destory(){
		try {
			if(socket!=null&&!socket.isClosed()){
				socket.close();
				bInputStream.close();
				bOutputStream.close();
			}	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void connect(Handler reHandler ,String IP,int port) {
		try {
            this.reHandler =reHandler;
			socket = new Socket(IP, port);
			bInputStream = new DataInputStream(socket.getInputStream());
			bOutputStream = new DataOutputStream(socket.getOutputStream());
			reThread.start();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private Thread reThread = new Thread(new Runnable() {
		@Override
		public void run() {
			// TODO Auto1-generated method stub
			while (socket != null && !socket.isClosed()) {
				try{
					//////////////////////
					String result = bytesToString(readFromInputStream(bInputStream)); //Read the data from the input stream and return it to result
					if (!result.equals("")) {
						Message msg = new Message();  //Get information
						msg.what = 1;                 //Set what belongs to message?
						msg.obj = rbyte;
						Bundle data = new Bundle();
						data.putString("msg", result);
						msg.setData(data);
						reHandler.sendMessage(msg);   //Send message

					}
				} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
				}
			}
		}
	});
/////////////////////////////////////////////////////
public byte[] readFromInputStream(InputStream in) {
	int count = 0;
	byte[] inDatas = null;
	try {
		while (count == 0) {
			count = in.available();
		}
		inDatas = new byte[count];
		in.read(inDatas);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return inDatas ;
}


	public String getHexString(String send) {
		String s = send;
		int i;
		StringBuilder sb = new StringBuilder();
		for ( i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (('0' <= c && c <= '9') || ('a' <= c && c <= 'f') ||
					('A' <= c && c <= 'F')) {
				sb.append(c);
			}
		}
		if ((sb.length() % 2) != 0) {
			sb.deleteCharAt(sb.length());
		}
		return sb.toString();
	}

	public byte[] stringToBytes(String s) {
		byte[] buf = new byte[s.length() / 2];
		for (int i = 0; i < buf.length; i++) {
			try {
				buf[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}

		}
		return buf;
	}
	public String bytesToString(byte[] bytes) {
		final char[] hexArray = "0123456789ABCDEF".toCharArray();
		char[] hexChars = new char[bytes.length * 2];
		StringBuilder sb = new StringBuilder();
		try{
			for (int i = 0; i < bytes.length; i++) {
				int v = bytes[i] & 0xFF;
				hexChars[i * 2] = hexArray[v >>> 4];
				hexChars[i * 2 + 1] = hexArray[v & 0x0F];

				sb.append(hexChars[i * 2]);
				sb.append(hexChars[i * 2 + 1]);
				sb.append(' ');
			}}
		catch (NumberFormatException e) {
			e.printStackTrace();
		};
		return sb.toString();
	}


	public void send( String X)
	{
		CHECKSUM=(short) ((MAJOR+FIRST+SECOND+THRID)%256);
		final byte[] sbyte= stringToBytes( getHexString(X));
		 MainActivity.executorServicetor.execute(new Runnable() {  //Start thread, transfer data
			 @Override
			 public void run() {
				 // TODO Auto-generated method stub
				 try{
					 if (socket != null && !socket.isClosed()) {

						 bOutputStream.write(sbyte, 0, sbyte.length);
						 bOutputStream.flush();
					 }
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 });
	}


	public void send_voice(final byte [] textbyte) {
                    MainActivity.executorServicetor.execute(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							try {
								if (socket != null && !socket.isClosed()) {
									bOutputStream.write(textbyte, 0, textbyte.length);
									bOutputStream.flush();
								}
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					});
	}

	// a dead sleep
	public void yanchi(int time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/green"
    android:gravity="right"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="78dp"
        android:gravity="center_horizontal"
        android:text="socket Client hex display instance"
        android:textColor="@color/white"
        android:textSize="24sp" />

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

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="IP Address:" />

        <EditText
            android:id="@+id/ipadress"
            android:layout_width="172dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Format (192.168.4.1)"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/buttonip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="obtain IP" />

    </LinearLayout>

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

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Port number:" />

        <EditText
            android:id="@+id/com"
            android:layout_width="171dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="format:9999"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/buttonconnection"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="connect" />

    </LinearLayout>

    <TextView
        android:id="@+id/rvdata"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:hint="Receive data (separated by spaces)"
        android:textSize="20sp" />

    <Button
        android:id="@+id/reclear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="empty" />



    <EditText
        android:id="@+id/senddata"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:hint="Send sixteen data (separated by spaces)"/>


    <Button
        android:id="@+id/sendclear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="empty" />

    <Button
        android:id="@+id/sendto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send out" />


If I like 20 or download more than 20 points, I will write an APP for smart home, reading temperature and humidity, alcohol detection, lighting and so on.

Tags: Android socket Java xml

Posted on Tue, 19 May 2020 07:03:50 -0400 by atstein