Android WIFI的基本操作
程序员文章站
2022-03-29 19:50:36
WIFI管理类 连接指定WIFI实例 回调接口 弹框验证 ......
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(); } } }
上一篇: 向日葵甘特图左侧标题栏名称“解密”
下一篇: 浅谈小程序中的请求封装