WiFi管理工具类

package com.wyf.app.common;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List; import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager; public class WifiManageUtils
{
private static WifiManager wifiManager;
private static WifiInfo wifiInfo;
private static List<ScanResult> wifiScanlist;
private static List<WifiConfiguration> wifiConfigurationlist;
private static DhcpInfo wifiDhcpInfo; public WifiManageUtils(Context context)
{
// 取得WifiManager对象
wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
} public WifiInfo getWifiConnectInfo()
{
wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo;
} public List<ScanResult> getScanResult()
{
wifiScanlist = wifiManager.getScanResults();
return wifiScanlist;
} public List<WifiConfiguration> getConfiguration()
{
wifiConfigurationlist = wifiManager.getConfiguredNetworks();
return wifiConfigurationlist;
} public DhcpInfo getDhcpInfo()
{
wifiDhcpInfo = wifiManager.getDhcpInfo();
return wifiDhcpInfo;
} /**
* 开启热点作为服务端的配置
*
* @param ssid
* @param passwd
* @param type
* @return
*/
public WifiConfiguration getCustomeWifiConfiguration(String ssid,
String passwd, int type)
{
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = ssid;
if (type == 1) // NOPASS
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 2) // WEP
{
config.hiddenSSID = true;
config.wepKeys[0] = passwd;
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 3) // WPA
{
config.preSharedKey = passwd;
config.hiddenSSID = true;
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
// config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
}
if (type == 4) // WPA2psk test
{
config.preSharedKey = passwd;
config.hiddenSSID = true; config.status = WifiConfiguration.Status.ENABLED;
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); }
return config; } /**
* 客户端添加配置,作为连接认证配置
* ssid、passwd 配置前后必须加上双引号“
* @param ssid
* @param passwd
* @param type
* @return
*/
public WifiConfiguration getCustomeWifiClientConfiguration(String ssid,
String passwd, int type)
{
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
//双引号必须
config.SSID = "\"" + ssid + "\"";
if (type == 1) // WIFICIPHER_NOPASS
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 2) // WIFICIPHER_WEP
{
config.hiddenSSID = true;
config.wepKeys[0] = "\"" + passwd + "\"";
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers
.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 3) // WIFICIPHER_WPA
{
config.preSharedKey = "\"" + passwd + "\"";
config.hiddenSSID = true;
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
// config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
}
if (type == 4) // WPA2psk test
{
config.preSharedKey = "\"" + passwd + "\"";
config.hiddenSSID = true; config.status = WifiConfiguration.Status.ENABLED;
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); }
return config; } public Boolean stratWifiAp(String ssid, String psd, int type)
{
Method method1 = null;
try
{
method1 = wifiManager.getClass().getMethod("setWifiApEnabled",
WifiConfiguration.class, boolean.class);
WifiConfiguration netConfig = getCustomeWifiConfiguration(ssid,
psd, type); method1.invoke(wifiManager, netConfig, true);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
} public void closeWifiAp()
{
if (isWifiApEnabled())
{
try
{
Method method = wifiManager.getClass().getMethod(
"getWifiApConfiguration");
method.setAccessible(true); WifiConfiguration config = (WifiConfiguration) method
.invoke(wifiManager); Method method2 = wifiManager.getClass().getMethod(
"setWifiApEnabled", WifiConfiguration.class,
boolean.class);
method2.invoke(wifiManager, config, false);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
} public boolean isWifiApEnabled()
{
try
{
Method method = wifiManager.getClass().getMethod("isWifiApEnabled");
method.setAccessible(true);
return (Boolean) method.invoke(wifiManager); }
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
} return false;
}
}

开启热点服务端部分代码

    public void startWifiHot()
{
btnServer.setEnabled(false);
if (wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
} Boolean b = wifimanageutils.stratWifiAp(mSSID, mPasswd,3);
if (b)
{
serverThread = new WifiServerThread(context, testh);
Toast.makeText(context, "server 端启动", 3000).show();
serverThread.start();
}
else
{
btnServer.setEnabled(true);
Toast.makeText(context, "server 端失败,请重试", 3000).show();
}
}

WifiServerThread服务端线程

public class WifiServerThread extends Thread
{
public ServerSocket mserverSocket;
public Socket socket;
public Context context;
public static final int SERVERPORT = 8191;
public Boolean isrun = true;
public Handler handler; public WifiServerThread(Context context, Handler handler)
{
this.context = context;
this.handler = handler;
} public void run()
{
try
{
mserverSocket = new ServerSocket(SERVERPORT);
while (isrun)
{
socket = mserverSocket.accept();
new Thread(new Runnable()
{
@Override
public void run()
{
byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null; try
{
mmInStream = socket.getInputStream();
}
catch (IOException e1)
{
e1.printStackTrace();
}
System.out.println("server"); try
{
InputStream in = socket.getInputStream();
OutputStream os = socket.getOutputStream(); byte[] data = new byte[1024];
while (in.available() <= 0)
;// 同步 int len = in.read(data); String[] str = new String(data, 0, len, "utf-8")
.split(";"); String path = Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/CHFS/000000000000" + "/";
if (len != -1)
{
path += "socket_" + str[0];// str[0]是文件名加类型
}
handler.obtainMessage(10, (Object) str[0])
.sendToTarget(); System.out.println(path); os.write("start".getBytes()); os.flush(); File file = new File(path); DataOutputStream out = new DataOutputStream(
new FileOutputStream(file)); System.out.println("开始接收.....");
int countSize = 0; while ((len = in.read(data)) != -1)
{
out.write(data, 0, len);
countSize += len;
} os.close();
out.flush();
out.close();
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
System.out.println("关闭....");
}
catch (Exception e)
{
e.printStackTrace();
}
handler.obtainMessage(10, (Object) "接受 完成")
.sendToTarget();
} }
}).start();
}
if (mserverSocket != null)
{
try
{
mserverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
} }
catch (Exception e)
{
e.printStackTrace();
} }
}

开启客户端部分代码

btnClient.setOnClickListener(new OnClickListener()
{ @Override
public void onClick(View v)
{
WifiConfiguration netConfig = wifimanageutils
.getCustomeWifiClientConfiguration(mSSID, mPasswd,3); int wcgID = wifiManager.addNetwork(netConfig);
boolean b = wifiManager.enableNetwork(wcgID, true); Boolean iptoready = false;
if (!b)
{
Toast.makeText(context, "wifi 连接配置不可用", 3000).show();
return;
}
while (!iptoready)
{
try
{
// 为了避免程序一直while循环,让它睡个100毫秒在检测……
Thread.currentThread();
Thread.sleep(100);
}
catch (InterruptedException ie)
{
} DhcpInfo dhcp = new WifiManageUtils(context).getDhcpInfo();
int ipInt = dhcp.gateway;
if (ipInt != 0)
{
iptoready = true;
}
}
wifiLock.acquire();
clientThread = new WifiClientThread(context);
clientThread.start();
}
});

WifiClientThread客户端线程

public class WifiClientThread extends Thread
{
public Socket socket;
public Context context;
public Boolean isrun = true;
public static final int SERVERPORT = 8191; public OutputStream os;
public InputStream in; public WifiClientThread(Context context)
{
this.context = context;
} public void run()
{
try
{
DhcpInfo dhcp = new WifiManageUtils(context).getDhcpInfo();
int ipInt = dhcp.gateway;
String serverip = String.valueOf(new StringBuilder()
.append((ipInt & 0xff)).append('.').append((ipInt >> 8) & 0xff)
.append('.').append((ipInt >> 16) & 0xff).append('.')
.append(((ipInt >> 24) & 0xff)).toString() );
socket = new Socket(serverip, SERVERPORT); new Thread(new Runnable()
{ @Override
public void run()
{
if (socket == null)
{
return;
}
System.out.println("client connect"); try
{
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/CHFS/000000000000";
if (android.os.Build.MODEL.contains("8812"))
{
path += "/camera/" + "camera_temp_name.jpg";
}
else
{
// path += "/camera/" + "camera_temp_name.mp4";
path+="/ARChon-v1.1-x86_64.zip";
}
DataInputStream read = new DataInputStream(
new FileInputStream(new File(path)));
System.out.println(read.available());
String fileName = path.substring(path.lastIndexOf("/") + 1);// 获得文件名加类型 System.out.println(fileName); os = socket.getOutputStream();
in = socket.getInputStream();
os.write((fileName + ";" + read.available())
.getBytes("utf-8"));// 将文件名和文件大小传给接收端
os.flush();
byte[] data = new byte[1024]; int len = in.read(data); String start = new String(data, 0, len); int sendCountLen = 0; if (start.equals("start"))
{ while ((len = read.read(data)) != -1)
{
os.write(data, 0, len);
sendCountLen += len;
}
os.flush();
os.close();
read.close();
} }
catch (Exception e)
{ e.printStackTrace();
}
finally
{ try
{
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
} } }
}).start();
}
catch (IOException e)
// catch (Exception e)
{
e.printStackTrace();
}
} }

android wifi 热点、socket通讯的更多相关文章

  1. android wifi热点 socket通信

    1.首先建立wifi热点服务器  wifi客户端连接 2.开启一个子线程循环监听某个端口,进行数据流输入输出 /* 服务器 接收数据 */ class Receiver extends Thread ...

  2. Android WiFi热点7.1以上版本适配

    代码地址如下:http://www.demodashi.com/demo/13907.html 一.准备工作 开发环境:  jdk1.8  AS(3.0.1) 运行环境:  华为V10(Android ...

  3. Android WiFi热点完全研究(自定义创建、跳转系统界面设置、读取配置、切换,Android6.0适配)

    前言: WiFi热点设置页面的安全性选项在Android 4.x上有“无”.“WPA PSK”.“WPA2 PSK”三个选项,在Android 5.0(含)之后去掉了WPA PSK选项(部分手机厂家会 ...

  4. Android笔记:Socket通讯常见问题

    经验证的socket通讯问题 1.如果是模拟器和本机PC直接通讯,需要使用本机IP地址 而不是 10.0.2.2  如本机的静态地址为192.168.1.2 则直接使用该地址 2.接收和连接代码不能在 ...

  5. Android WiFi开发教程(三)——WiFi热点数据传输

    在上一篇文章中介绍了WiFi的搜索和连接,如果你还没阅读过,建议先阅读上一篇Android WiFi开发教程(二)——WiFi的搜索和连接.本篇接着简单介绍手机上如何通过WiFi热点进行数据传输. 跟 ...

  6. android 代码设置、打开wifi热点及热点的连接(转)

      用过快牙的朋友应该知道它们在两天设备之间传输文件的时候使用的是wifi热点,然后另一台便连接这个热点再进行传输.快牙传输速度惊人应该跟它的这种机制有关系吧.不知道它的搜索机制是怎样的,但我想应该可 ...

  7. Android WiFi开发教程(一)——WiFi热点的创建与关闭

    相对于BlueTooth,WiFi是当今使用最广的一种无线网络传输技术, 几乎所有智能手机.平板电脑和笔记本电脑都支持Wi-Fi上网.因此,掌握基本的WiFI开发技术是非常必要的.本教程将围绕一个小D ...

  8. Android连接热点的Socket文件传输

    最近把测试丢过来的种种BUG解决后,终于有时间去研究研究Socket通信,再加上以前做的WiFi连接和热点开启,于是有了现在的这篇博文:创建热点发送文件,让另一台手机连接热点接收文件. 效果图: 两台 ...

  9. android源码中修改wifi热点默认始终开启

    在项目\frameworks\base\wifi\java\android\net\wifi\WifiStateMachine.java里面,有如下的代码,是设置wifi热点保持状态的:如下: pri ...

随机推荐

  1. 20包含min函数的栈

      题目描述 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数.   建一个辅助栈,把每次最小最小的元素(之前最小元素,与当前新入栈的元素比较)放在辅助栈里.   import j ...

  2. SqlHelper简单实现(通过Expression和反射)8.Sql Server数据处理类

    这个类基本上就是调用EntityHelper,ExpressionHelper和ObjectHelper来进行各种完整SQL的拼接操作. using System; using System.Conf ...

  3. ASP.NET WebAPI2 发布之后404 Not Found

    方法一:首先确保服务器安装.Net FrameWork 4.0 并且注册IIS 方法二:对应应用程序池版本为v4.0,模式为集成 方法三:在web.config中加入 <system.webSe ...

  4. Python面试题之Python的Super方法

    我们最常见的,可以说几乎唯一能见到的使用super的形式是: class SubClass(BaseClass): def method(self): super(SubClass, self).me ...

  5. WINDOWS和UNIX换行符的理解

    # WINDOWS和UNIX换行符的理解 **file1.txt**17.143.161.37   其他    美国54.163.255.40   其他    美国 弗吉尼亚州 亚马逊公司 **[ro ...

  6. maven私服客户端配置

    <?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://mav ...

  7. CSS3小图标菜单导航

    在线演示 本地下载

  8. Linux系统基本的内存管理知识讲解

    内存是Linux内核所管理的最重要的资源之一.内存管理系统是操作系统中最为重要的部分,因为系统的物理内存总是少于系统所需要的内存数量.虚拟内存就是为了克服这个矛盾而采用的策略.系统的虚拟内存通过在各个 ...

  9. SSL证书是“盾牌“还是”鸡肋“?

    德国联邦安全与IT办公室(BSI,职能相当于美国的国家安全与信息技术局)近日发布公告警告:网络攻击者冒充其发布了“关于Meltdown与Spectre攻击信息”的垃圾邮件,该邮件中包含指向修复补丁的页 ...

  10. Java值传递还是引用传递?

    回顾: 在程序设计语言中,将参数传递分为按值调用和按引用调用.按值调用:表示方法接收的是调用者提供的值.而按引用调用表示方法接收的是调用者提供的变量地址.一个方法可以修改传递引用所对应的变量值,而不能 ...