通过一段时间的学习和应用,理解了Android通信,通过这篇文章记录一下学习过程。

基于ESP8266的Android WiFi通信广泛应用于物联网领域,常用是通过局域网实现Android端和下位机的通信,达到控制目的。

此篇文章记录的内容,需要手机连接到WiFi模块,通过wifi让Android端和硬件部分处于同一个局域网内。Android网络通信通过socket编程实现网络的连接,通过IO流实现数据的发送与接收。

首先,创建一个Android项目,首先,需要给予APP网络权限:

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

第二步,创建一个类SendThead,内容为发送和接收的代码,首先定义IP,端口port,以及接收/发送’变量,打开套接字实现网络的连接,连接结束关闭套接字,采取多线程实现信息的发送与接收:

package com.example.a14942.smart_see;/*** Created by 14942 on 2018/3/26.*/import android.os.Handler;
import android.os.Message;
import android.util.Log;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;
import java.util.ArrayList;class SendThread implements Runnable {private String ip;private int port;BufferedReader in;PrintWriter out;      //打印流Handler mainHandler;Socket s;private String receiveMsg;ArrayList<String> list = new ArrayList<String>();public SendThread(String ip,int port, Handler mainHandler) {     //IP,端口,数据this.ip = ip;this.port=port;this.mainHandler = mainHandler;}/*** 套接字的打开*/void open(){try {s = new Socket(ip, port);//in收单片机发的数据in = new BufferedReader(new InputStreamReader(s.getInputStream()));out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);} catch (IOException e) {e.printStackTrace();}}/*** 套接字的关闭*/void close(){try {s.close();} catch (IOException e) {e.printStackTrace();}}@Overridepublic void run() {//创建套接字open();//BufferedReaderThread thread = new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(200);close();open();} catch (InterruptedException e1) {e1.printStackTrace();}if (!s.isClosed()) {if (s.isConnected()) {if (!s.isInputShutdown()) {try {Log.i("mr", "等待接收信息");char[] chars = new char[1024];                 //byte[] bys = new byte[1024];     int len = 0;                           //int len = 0;while((len = in.read(chars)) != -1){               //while((len = in.read(bys)) != -1) { System.out.println("收到的消息:  "+new String(chars, 0, len));      in.write(bys,0,len);receiveMsg = new String(chars, 0, len);               // }Message msg=mainHandler.obtainMessage();msg.what=0x00;msg.obj=receiveMsg;mainHandler.sendMessage(msg);}} catch (IOException e) {Log.i("mr", e.getMessage());try {s.shutdownInput();s.shutdownOutput();s.close();} catch (IOException e1) {e1.printStackTrace();}e.printStackTrace();}}}}}}});thread.start();while (true) {//连接中if (!s.isClosed()&&s.isConnected()&&!s.isInputShutdown()) {// 如果消息集合有东西,并且发送线程在工作。if (list.size() > 0 && !s.isOutputShutdown()) {out.println(list.get(0));list.remove(0);}Message msg=mainHandler.obtainMessage();msg.what=0x01;mainHandler.sendMessage(msg);} else {//连接中断了Log.i("mr", "连接断开了");Message msg=mainHandler.obtainMessage();msg.what=0x02;mainHandler.sendMessage(msg);}try {Thread.sleep(200);} catch (InterruptedException e) {try {out.close();in.close();s.close();} catch (IOException e1) {e1.printStackTrace();}e.printStackTrace();}}}public void send(String msg) {System.out.println("msg的值为:  " + msg);list.add(msg);}}

第三步,创建主活动,编写布局(xml)文件,这里我创建了一个温度显示框,和两个开关控制按钮(switch控件):

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/screen"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="@drawable/bb"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="10dp"android:layout_x="30dp"android:layout_y="130dp"android:orientation="horizontal"><TextViewandroid:id="@+id/textView2"android:layout_width="50sp"android:layout_height="wrap_content"android:layout_marginLeft="33px"android:text="湿度"android:textColor="#000000"android:textSize="18sp" /><TextViewandroid:id="@+id/ttv2"android:layout_width="160sp"android:layout_height="wrap_content"android:background="#FFFFFF"android:text=""android:textSize="18sp" /><TextViewandroid:layout_width="60sp"android:layout_height="wrap_content"android:gravity="center"android:paddingLeft="10px"android:text="%rh"android:textColor="#000000"android:textSize="18sp" /></LinearLayout><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="开         关"android:textColor="#000000"android:textSize="18sp"android:layout_x="50dp"android:layout_y="200dp"/><Switchandroid:id="@+id/Switch2"android:layout_width="50sp"android:layout_height="wrap_content"android:layout_weight="1.01"android:layout_x="210dp"android:layout_y="270dp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="自动手动"android:textColor="#000000"android:textSize="18sp"android:layout_x="50dp"android:layout_y="270dp"/><Switchandroid:id="@+id/Switch1"android:layout_width="50sp"android:layout_height="wrap_content"android:layout_x="210dp"android:layout_y="200dp" /></AbsoluteLayout>

第四步,编写主活动,包括实现网络连接(SendThead),实现消息的发送和接收,对开关控件(switch)定义点击事件:

package com.example.a14942.smart_see;import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;public class MainActivity extends AppCompatActivity{/*接收发送定义的常量*/private String mIp = "192.168.4.1";private int mPort = 9000;private SendThread sendthread;String receive_Msg;String l;String total0,total1,total2,total3;private Button button0;private Button button1;static PrintWriter mPrintWriterClient = null;static BufferedReader mBufferedReaderClient = null;Switch switch1,switch2;/*****************************/@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//getSupportActionBar().hide();setContentView(R.layout.activity_main);
//        button0= (Button)findViewById(R.id.Water_W_N);
//        button0.setOnClickListener(button0ClickListener);
//        button1= (Button)findViewById(R.id.Water_W_O);
//        button1.setOnClickListener(button1ClickListener);/***************连接*****************/sendthread = new SendThread(mIp, mPort, mHandler);Thread1();new Thread().start();/**********************************/switch1 = (Switch) findViewById(R.id.Switch1);switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {// TODO Auto-generated method stubif (isChecked) {sendthread.send("A");} else {sendthread.send("B");}}});switch2 = (Switch) findViewById(R.id.Switch2);switch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {// TODO Auto-generated method stubif (isChecked) {sendthread.send("C");} else {sendthread.send("D");}}});}
//    private View.OnClickListener button0ClickListener = new View.OnClickListener() {
//        public void onClick(View arg0) {
//            mPrintWriterClient.print("j");
//            mPrintWriterClient.flush();
//
//        }
//    };
//    private View.OnClickListener button1ClickListener = new View.OnClickListener() {
//        public void onClick(View arg0) {
//            mPrintWriterClient.print("m");
//            mPrintWriterClient.flush();
//        }
//    };private class FragmentAdapter extends FragmentPagerAdapter {List<Fragment> fragmentList = new ArrayList<Fragment>();public FragmentAdapter(FragmentManager fm, List<Fragment> fragmentList) {super(fm);this.fragmentList = fragmentList;}@Overridepublic Fragment getItem(int position) {return fragmentList.get(position);}@Overridepublic int getCount() {return fragmentList.size();}}/*接收线程*******************************************************************************//*** 开启socket连接线程*/void Thread1(){
//        sendthread = new SendThread(mIp, mPort, mHandler);new Thread(sendthread).start();//创建一个新线程}Handler mHandler = new Handler(){public void handleMessage(Message msg){TextView text0 = (TextView)findViewById(R.id.ttv2);super.handleMessage(msg);if (msg.what == 0x00) {Log.i("mr_收到的数据: ", msg.obj.toString());receive_Msg = msg.obj.toString();l = receive_Msg;text0.setText(l);}}};
}

这样,一个简单的物联网通信就实现了。希望对大家有所帮助,如有疑问,欢迎留言。

本次文章一样的源码暂时找不到了,附上依托以上的代码开发的简单的demo示例

csdn:https://download.csdn.net/download/weixin_40042248/13456038

github:https://github.com/Yang-Jianlin/ESP8266-with-Android

基于WiFi模块的Android WiFi通信相关推荐

  1. php和javascript的get和post方式 有人串口转wifi模块httpdclient网页交互通信成功源码2 wifi继电器小黄人软件ypnr

    全部源码下载:链接: http://pan.baidu.com/s/1qXxr0i4 密码: 有人串口转wifi模块 httpd client通信示例-用户使用网页通过服务器收发串口数据get 功能: ...

  2. 基于MT7688AN模块开发板WiFi路由方案无线音频传输WiFi音箱测试

    无线路由解决方案无损WiFi音频传输测试 基于MT7688AN模块开发板WiFi路由方案无线音频传输WiFi音箱测试 L107物联网路由器模块是基于联发科MT7688或MT7628芯片组.该模块只需要 ...

  3. android wifi 框架图,android wifi框架

    ---恢复内容开始--- frameworks/base/services/java/com/android/server/wifi 中的ReadMe文件 WifiService: Implement ...

  4. 无线WiFi模块通信技术,WiFi技术方案应用,物联网智能发展

    时下主流的智能控制方案基本都可实现在家控制和远程控制两种方式.在家的情况下,用户手机APP通过路由器连接WiFi控制内置WiFi模块的产品(比如智能开关(插座),智能灯泡--控制产品的应用.在室外,用 ...

  5. 迅为RK3399开发板基于RTL8822CS模块Android7移植WiFi

    近期需要把 wifi 无线网络功能(RTL8822CS 模块)移植到 iTOP-3399 开发板,经过一段时间研究, 调试,终于成功的将 wifi 功能移植到开发板上面. 移植的环境: 1. iTOP ...

  6. linux wifi开发书籍,Android WIFI开发介绍.pdf

    Android WIFI开发介绍: WifiStateTracker 会创建WifiMonitor 接收来自底层的事件,WifiService 和WifiMonitor 是整个模块的核心.WifiSe ...

  7. wifi信号增强android,wifi信号增强器下载安装

    wifi信号增强器软件简介 WiFi信号增强器是专注的增强Wi-Fi网络信号.释放内存.优化硬件,管理Wi-Fi账号的APP工具.软件通过优化手机设备.自动校准无线模块等原理,让在使用中的WiFi信号 ...

  8. android wifi的进程,Android wifi简要分析

    这里列了很多,但是大致可以分为四个主要的类ScanResult wifiConfiguration WifiInfo WifiManager (1)ScanResult,主要是通过wifi 硬件的扫描 ...

  9. 基于AOA协议的android USB通信

    摘 要:AOA协议是Google公司推出的用于实现Android设备与外围设备之间USB通信的协议.该协议拓展了Android设备USB接口的功能,为基于Android系统的智能设备应用于数据采集和设 ...

最新文章

  1. PHP APC安装与使用
  2. Android --- 快速将字符串定义到strings.xml文件的方法
  3. Oracle linux R5-U7中YUM 源配置
  4. linux nginx大量TIME_WAIT的解决办法--转
  5. 华为主题包hwt下载_华为主题太丑?修改方式它来了
  6. MFC初步教程(一)
  7. 《计算机网络》学习笔记 ·003【数据链路层】
  8. JS中的函数,Array对象,for-in语句,with语句,自定义对象,Prototype
  9. 29.yii2 RBAC
  10. oracle 2的次方,Oracle第二次课 - osc_qyg23ccq的个人空间 - OSCHINA - 中文开源技术交流社区...
  11. php 同义词词库,php实现SEO伪原创同义词替换函数
  12. Python爬虫系列(五)360图库美女图片下载
  13. java运行环境配置_配置java开发运行环境的步骤
  14. 土地数据合集-土地出让数据2020版Globe30土地覆盖数据
  15. 【重要】国庆节快乐!有三AI所有课程限时7天优惠
  16. 「完美解决」关于最新Ubuntu22.04.1安装launchpad里面PPA报错:“InRelease not available“,“not found file“等
  17. C语言——常量,变量
  18. WordPress必装插件推荐
  19. K8S==springboot项目生成image部署到K8S
  20. Springboot 集成 Activiti时启动报错!'org.activiti.spring.boot.SecurityAutoConfiguration

热门文章

  1. 隐私保护集合交集计算技术研究综述 ——内容总结
  2. 飞机票网上订票系统javabean+jsp+mysql
  3. 拼题a做题时遇到的知识点
  4. 孙茂松:深度学习的红利我们享受得差不多了!
  5. 支教生活| 在凉山最贵的快乐5毛钱
  6. mysql 求上个月、上上个月的第一天和最后一天
  7. 解决问题Description Resource Path Location Type Archive for required library:
  8. Linux查看emc存储挂载情况
  9. Markdown 换行,空格
  10. 电路分析笔记-电路模型