WIFI管理类

class WifiConnector {
private ExecutorService executors;
Handler mHandler;
WifiManager wifiManager; WifiConnector(WifiManager wifiManager, Handler handler) {
this.wifiManager = wifiManager;
executors= Executors.newSingleThreadExecutor();
mHandler=handler;
} private void sendMsg(String info) {
if (mHandler != null) {
Message msg = new Message();
msg.obj = info;
mHandler.sendMessage(msg);
}
} //WIFICIPHER_WEP是WEP ,WIFICIPHER_WPA是WPA,WIFICIPHER_NOPASS没有密码
public enum WifiCipherType {
WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
} // 打开wifi
public boolean openWifi() {
return !wifiManager.isWifiEnabled() && wifiManager.setWifiEnabled(true);
}
// 关闭wifi
public void closeWifi() {
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false); }
}
//断开当前连接
public boolean disconnectWifi() {
return wifiManager.disconnect();
} //扫描wifi信息
public void scanWifi(){
if(wifiManager.isWifiEnabled()){
//扫描热点 如果扫描不到热点 把targetSdkVersion改成22
wifiManager.startScan();
}
} //获取热点信息 ScanResult.SSID 获取热点名字 ScanResult.level 获取热点信号强度
public List<ScanResult> scanResultsWifi(){
if(wifiManager.isWifiEnabled()){
//扫描热点 如果扫描不到热点 把targetSdkVersion改成22
return wifiManager.getScanResults();
}
return null;
} // 连接指定wifi
public void connect(String ssid, String password, WifiCipherType type) {
executors.execute(new Thread(new ConnectRunnable(ssid, password, type)));
} // 查看以前是否也配置过这个网络
public WifiConfiguration isExsits(String SSID) {
List<WifiConfiguration> existingConfigs = wifiManager .getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
return null;
} //配置wifi信息
private WifiConfiguration createWifiInfo(String SSID, String Password,
WifiCipherType Type) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\""; WifiConfiguration tempConfig =isExsits(SSID); // nopass
if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
// wep
if (Type == WifiCipherType.WIFICIPHER_WEP) {
if (!TextUtils.isEmpty(Password)) {
if (isHexWepKey(Password)) {
config.wepKeys[0] = Password;
} else {
config.wepKeys[0] = "\"" + Password + "\"";
}
}
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
// wpa
if (Type == WifiCipherType.WIFICIPHER_WPA) {
config.preSharedKey = "\"" + Password + "\"";
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;
}
return config;
} class ConnectRunnable implements Runnable {
private String ssid;
private String password;
private WifiCipherType type; private ConnectRunnable(String ssid, String password, WifiCipherType type) {
this.ssid = ssid;
this.password = password;
this.type = type;
} @Override
public void run() {
try {
// 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi
// 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
WifiConfiguration wifiConfig = createWifiInfo(ssid, password,type);
if (wifiConfig == null) {
return;
}
WifiConfiguration tempConfig = isExsits(ssid);
if (tempConfig != null) {
wifiManager.removeNetwork(tempConfig.networkId);
}
int netID = wifiManager.addNetwork(wifiConfig);
boolean enabled = wifiManager.enableNetwork(netID, true);
Thread.sleep(1000);
if(enabled){
sendMsg("0");
}else{
sendMsg("1");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
} private static boolean isHexWepKey(String wepKey) {
final int len = wepKey.length();
// WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
return !(len != 10 && len != 26 && len != 58) && isHex(wepKey);
} private static boolean isHex(String key) {
for (int i = key.length() - 1; i >= 0; i--) {
final char c = key.charAt(i);
if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
&& c <= 'f')) {
return false;
}
}
return true;
}
}

连接指定WIFI

public class MainActivity extends AppCompatActivity implements ICheckDialogListener{
private ListView listview;
private CheckDialog dialg;
private Button scranButton;
private WifiManager mainWifi;
private WifiReceiver receiverWifi;
private WifiConnector wifycon; // 连接WIFI
private ScanResult scanRet;
//扫描出的wifi列表
public List<ScanResult> wifiList;
//选中的wifi项
private int wifiPosition; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scranButton=findViewById(R.id.scranButton);
listview=findViewById(R.id.listview);
dialg=new CheckDialog(this,R.style.AppTheme,this); //初始化wifi管理器 这里如果用this可能会造成内存泄漏
mainWifi = (WifiManager) getApplicationContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//监听wifi的广播,必须动态注册
receiverWifi = new WifiReceiver();
//初始化wifi连接类
wifycon=new WifiConnector(mainWifi,handler); scranButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//判断wifi是否打开,否则打开
wifycon.openWifi();
//扫描热点 如果扫描不到热点 把targetSdkVersion改成22
//mainWifi.startScan();
Toast.makeText(MainActivity.this,"扫描WIFI热点,请稍候", Toast.LENGTH_SHORT).show();
}
}); }
protected void onResume(){
super.onResume();
//注册广播
registerReceiver(receiverWifi, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
} class WifiReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent){
//扫描完毕接受到的广播
if (intent.getAction().equals(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
wifycon.scanWifi();
wifiList=wifycon.scanResultsWifi();
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this,
R.layout.wify_item,
getString(wifiList));
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dialg.show();
wifiPosition=position;
}
});
}
}
} @SuppressLint("HandlerLeak")
Handler handler=new Handler() {
@Override
public void handleMessage(Message msg) {
if("0".equals(msg.obj.toString())){
Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
}else if("1".equals(msg.obj.toString())){
Toast.makeText(MainActivity.this,"密码输入错误!",Toast.LENGTH_SHORT).show();
}
}
}; @Override
public void sendStr(String msg) {
scanRet = wifiList.get(wifiPosition);
wifycon.connect(scanRet.SSID,msg, WifiConnector.WifiCipherType.WIFICIPHER_WPA);
} public String[] getString(List<ScanResult> wifiList){
ArrayList<String> listStr = new ArrayList<>(); for (int i = 0; i < wifiList.size(); i++){
listStr.add(wifiList.get(i).SSID);
}
return listStr.toArray(new String[0]);
}
}

回调接口

public interface ICheckDialogListener {
public void sendStr(String msg) ;
}

弹框验证

public class CheckDialog extends Dialog implements View.OnClickListener {
private EditText tvContent;
private Button butCancel;
private Button but_confirm;
private Activity context;
private ICheckDialogListener dialogListener;
public CheckDialog(Activity context, int theme, ICheckDialogListener dialListener) {
super(context, theme);
this.context = context;
dialogListener=dialListener;
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check_dialog);
tvContent=findViewById(R.id.tv_content);
butCancel=findViewById(R.id.but_cancel);
butCancel.setOnClickListener(this);
but_confirm =findViewById(R.id.but_confirm);
but_confirm.setOnClickListener(this); } @Override
public void onClick(View v) {
if (v.getId() == R.id.but_confirm) {
String key = (tvContent.getText() + "").trim();
if ("".equals(key) | "null".equals(key)) {
Toast.makeText(context, "输入不能为空!", Toast.LENGTH_SHORT).show();
} else if (dialogListener==null) {
context.finish();
System.exit(0);
} else if(dialogListener!=null){
dialogListener.sendStr(key);
} else{
Toast.makeText(context, "密码输入错误!!", Toast.LENGTH_SHORT).show();
}
this.dismiss();
}else if(v.getId() == R.id.but_cancel){
this.dismiss();
}
}
}

Android WIFI的基本操作的更多相关文章

  1. Android Wi-Fi基本操作

    从用户角度看,Android Wi-Fi模块自下向上可以看为5层:硬件驱动程序,wpa_suppplicant,JNI,WiFi API,WifiSettings应用程序. 1.wpa_supplic ...

  2. Android WIFI 分析(一)

    本文基于<深入理解Android WiFi NFC和GPS 卷>和 Android N 代码结合分析   WifiService 是 Frameworks中负责wifi功能的核心服务,它主 ...

  3. android wifi P2P CONNECT, INVITE和JOIN流程选择

    android wifi P2P CONNECT, INVITE和JOIN流程选择

  4. android wifi ANR问题分析总结

    android wifi ANR问题分析总结 1 看看main进程阻塞在那里? 2 调用关系的函数阻塞在那里? 3 最终阻塞函数的阻塞前的log以及状态

  5. android wifi驱动移植详细过程

    转自:http://bbs.imp3.net/thread-10558924-1-1.html 对于刚入手android没多久的人来说,android wifi 驱动的移植确实还是有难度的,不过参考了 ...

  6. Android WIFI 启动流程(TIP^^)

    前几天因为解决一堆Bug,没时间写.我不会每天都写,就是为了存档一些资料. 内容来源:工作中接触到的+高手博客+文档(Books)=自己理解 仅限参考^^ 此博客是上一个<<Android ...

  7. android——wifi系统架构

    1. 系统架构 Android WiFi系统引入了wpa_supplicant,它的整个WiFi系统以wpa_supplicant为核心来定义上层用户接口和下层驱动接口.整个WiFi系统架构如下图所示 ...

  8. Android WiFi管理(WIFI_SERVICE)

    Android WiFi管理(WIFI_SERVICE) 分类: Android2011-11-24 10:52 2000人阅读 评论(1) 收藏 举报 androidservicebuttonlay ...

  9. Android Wi-Fi Display(Miracast)介绍

    地址:http://blog.csdn.net/innost/article/details/8474683 Android Wi-Fi Display(Miracast)介绍 2012年11月中旬, ...

随机推荐

  1. Java学习笔记30(集合框架四:List接口)

    List接口继承自Collection接口 具有重要的三大特点: 1.有序集合:存入和取出的顺序一致 2.此接口的用户可以对列表中每个元素插入位置精确的控制:可以通过索引操作 3.可以存储重复元素 L ...

  2. assembly.xml

    [官网地址]:http://maven.apache.org/plugins/maven-assembly-plugin/assembly.html <assembly xmlns=" ...

  3. c++中的.hpp文件

    http://blog.chinaunix.net/uid-24118190-id-75239.html hpp,其实质就是将.cpp的实现代码混入.h头文件当中,定义与实现都包含在同一文件,则该类的 ...

  4. VS发布 错误 未能将文件 复制到

    在VS内部编译及试运行的时候并为出现错误一切正常 当将项目发布时提示XXX文件无法复制到对应的obj文件夹下 未能将文件 upfile\team\2013\0328\20130328112637296 ...

  5. C# 对密码等数据进行对称性加密解密

    类: /// <summary> /// DESEncrypt加密解密算法. /// </summary> public class DESEncrypt { private ...

  6. odoo开发笔记 -- 传递上下文实现列表视图按照指定条件过滤显示

    按钮传递上下文: <xpath expr="//div[@name='dec_work_sheet_id']" position="after"> ...

  7. VueJs(10)---vue-router(动态路由,嵌套式路由,编程式路由)

    vue-router(动态路由,嵌套式路由,编程式路由) 本文是基于官网学习,官网具体学习目录:vue-router 一.安装 基于vue-cli脚手架安装还是蛮简单的:在文件当前目录下运行: npm ...

  8. 用C#学习数据结构之线性表

    什么是线性表 线性表是最简单.最基本.最常用的数据结构.线性表是线性结构的抽象(Abstract),线性结构的特点是结构中的数据元素之间存在一对一的线性关系.这种一对一的关系指的是数据元素之间的位置关 ...

  9. ckeditor 在dwz里面使用

    在ckeditor的配置的过程中,所有的配置的地方都配置了,但是就是不显示编辑器(编辑器代码如下),很郁闷哦 1 <textarea id="editor1" name=&q ...

  10. 从零开始学 Web 之 CSS(五)可见性、内容移除、精灵图、属性选择器、滑动门

    大家好,这里是「 Daotin的梦呓 」从零开始学 Web 系列教程.此文首发于「 Daotin的梦呓 」公众号,欢迎大家订阅关注.在这里我会从 Web 前端零基础开始,一步步学习 Web 相关的知识 ...