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(); } } }