安卓UDP或TCP通信并实时显示解析json数据和系统时间

文章目录

      • 主函数
      • UDP通信子线程
      • Tcp通信子线程
      • 每秒获取一次时间子线程
      • 主线程对子线程进行操作
      • 处理获取的系统时间

主函数

public class MainActivity extends AppCompatActivity {
    private DatagramSocket socket;
    private static final int PhonePort = 8000;
    private DatagramPacket packet;
    private volatile boolean stopReceiver = false;
    private String receive;
    //自己添加需要的显示控件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //TcpReceive();Tcp通信
        receiveMessage();//UDP通信
        TimeThread();//每秒获取一次时间
    }

UDP通信子线程

private void receiveMessage(){
	//新建一个线程
	new Thread(){
		public void run() {
			try{
				socket  = new DatagramSocket(PhonePort);
			} catch (SocketException){
				e.printStackTrace();
			}
			byte[] recBuf = new byte[1024];
			packet = new DatagramPacket(recBuf,recBuf.length);
			while (!stopReceiver){
				try{
					socket.receive(packet);
					receive = new String(packet.getData(),0,packet.getLength(),"utf-8");
					Log.d("receive",receive);//控制台上打印接收内容
					//信息接收完毕与UI主线程通讯
					Message msg = new Message();
					msg.what = 1;
					handler.sendMessage(msg);	
				} catch (IOException e){
					e.printStackTrace();
				}
			}
		}
	}.start();
}

Tcp通信子线程

public void TcpReceive(){
	new Thread(){
		public void run(){
			ServerSocket serverSocket = null;
			try{
				Socket socket = serverSocket.accept();
				InputStream inputStream = socket.getInputStream();
				byte[] buffer = new byte[1024*4];
				int flag = 0;
				while((flag = inputStream.read(buffer)) != -1){
					receive = new String(buffer,0,flag);
					Log.d("receive ",receive);
					Message msg = new Message();
					msg.what = 1;
					handler.sendMessage(msg);
				}	
			} catch (IOException e) {
              	e.printStackTrace();
            }
		}
	}.start();
}

每秒获取一次时间子线程

	public void TimeThread(){
        new Thread(){
            @Override
            public void run() {
                do{
                    try {
                        Thread.sleep(1000);
                        Message msg = new Message();
                        msg.what = 2;
                        handler.sendMessage(msg);//每隔1秒发送一个msg给handler,在主线程中处理时间函数
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }while (true);
            }
        }.start();
    }

主线程对子线程进行操作

	private Handler handler = new Handler(){
		public void handleMessage(@NonNull Message msg) {
    		super.handleMessage(msg);
            switch (msg.what){
                case 1:
                	//若传入是json数据,可用Gson解析后显示在UI界面上
                    Gson gson = new Gson();
                    UdpData udpData = gson.fromJson(receive,UdpData.class);
                    float Hum = udpData.getHum_in() / 10;
                    String hum = String.valueOf(Hum);
                    tvHum.setText(hum);
                    break;//处理子线程通信传入的数据 
                case 2:
					getTime();//处理获取时间子线程数据显示
                    break;
                default:
                    break;
            }
        }
	};

处理获取的系统时间

	public void getTime(){
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        int way = c.get(Calendar.DAY_OF_WEEK);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int min = c.get(Calendar.MINUTE);
        int sec = c.get(Calendar.SECOND);
        Log.d("year",String.valueOf(year));
        Log.d("month",String.valueOf(month));
        Log.d("day",String.valueOf(day));
        Log.d("way",String.valueOf(way));
        Log.d("hour",String.valueOf(hour));
        Log.d("min",String.valueOf(min));
        Log.d("sec",String.valueOf(sec));

        tvData.setText(year+"年"+month+"月"+day+"号");
        if (min<10){
            if (sec<10){
                tvTime.setText(hour+":0"+min+":0"+sec);
            }else {
                tvTime.setText(hour+":0"+min+":"+sec);
            }
        }else {
            if (sec<10){
                tvTime.setText(hour+":"+min+":0"+sec);
            }else {
                tvTime.setText(hour+":"+min+":"+sec);
            }
        }
        switch (way){
            case 1:
                tvWeek.setText("星期天");
                break;
            case 2:
                tvWeek.setText("星期一");
                break;
            case 3:
                tvWeek.setText("星期二");
                break;
            case 4:
                tvWeek.setText("星期三");
                break;
            case 5:
                tvWeek.setText("星期四");
                break;
            case 6:
                tvWeek.setText("星期五");
                break;
            case 7:
                tvWeek.setText("星期六");
                break;
        }
    }

你可能感兴趣的:(安卓UDP或TCP通信并实时显示解析json数据和系统时间)