小編給大家分享一下Android WiFi開發(fā)教程之WiFi熱點(diǎn)的創(chuàng)建與關(guān)閉示例,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
創(chuàng)新互聯(lián)公司專業(yè)提供四川服務(wù)器托管服務(wù),為用戶提供五星數(shù)據(jù)中心、電信、雙線接入解決方案,用戶可自行在線購(gòu)買四川服務(wù)器托管服務(wù),并享受7*24小時(shí)金牌售后服務(wù)。
/** * 創(chuàng)建Wifi熱點(diǎn) */ private void createWifiHotspot() { if (wifiManager.isWifiEnabled()) { //如果wifi處于打開狀態(tài),則關(guān)閉wifi, wifiManager.setWifiEnabled(false); } WifiConfiguration config = new WifiConfiguration(); config.SSID = WIFI_HOTSPOT_SSID; config.preSharedKey = "123456789"; config.hiddenSSID = true; config.allowedAuthAlgorithms .set(WifiConfiguration.AuthAlgorithm.OPEN);//開放系統(tǒng)認(rèn)證 config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); config.allowedPairwiseCiphers .set(WifiConfiguration.PairwiseCipher.TKIP); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); config.allowedPairwiseCiphers .set(WifiConfiguration.PairwiseCipher.CCMP); config.status = WifiConfiguration.Status.ENABLED; //通過(guò)反射調(diào)用設(shè)置熱點(diǎn) try { Method method = wifiManager.getClass().getMethod( "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE); boolean enable = (Boolean) method.invoke(wifiManager, config, true); if (enable) { textview.setText("熱點(diǎn)已開啟 SSID:" + WIFI_HOTSPOT_SSID + " password:123456789"); } else { textview.setText("創(chuàng)建熱點(diǎn)失敗"); } } catch (Exception e) { e.printStackTrace(); textview.setText("創(chuàng)建熱點(diǎn)失敗"); } }
This class provides the primary API for managing all aspects of Wi-Fi connectivity. Get an instance of this class by calling {@link android.content.Context#getSystemService(String) Context.getSystemService(Context.WIFI_SERVICE)}.
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
/** * 關(guān)閉WiFi熱點(diǎn) */ public void closeWifiHotspot() { 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(); } }
WiFi的搜索
/* 搜索wifi熱點(diǎn) */ private void search() { if (!wifiManager.isWifiEnabled()) { //開啟wifi wifiManager.setWifiEnabled(true); } wifiManager.startScan(); }
private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { // wifi已成功掃描到可用wifi。 List wifiListAdapter.clear(); wifiListAdapter.addAll(scanResults); } };
@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate(mResource, parent, false); } TextView name = (TextView) convertView.findViewById(R.id.wifi_name); TextView signl = (TextView) convertView.findViewById(R.id.wifi_signal); ScanResult scanResult = getItem(position); name.setText(scanResult.SSID); int level = scanResult.level; if (level signl.setText("信號(hào)很好"); } else if (level < -50 && level >= -70) { signl.setText("信號(hào)較好"); } else if (level < -70 && level >= -80) { signl.setText("信號(hào)一般"); } else if (level < -80 && level >= -100) { signl.setText("信號(hào)較差"); } else { signl.setText("信號(hào)很差"); } return convertView; }
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView wifiManager.disconnect(); final ScanResult scanResult = wifiListAdapter.getItem(position); String capabilities = scanResult.capabilities; int type = WIFICIPHER_WPA; if (!TextUtils.isEmpty(capabilities)) { if (capabilities.contains("WPA") || capabilities.contains("wpa")) { type = WIFICIPHER_WPA; } else if (capabilities.contains("WEP") || capabilities.contains("wep")) { type = WIFICIPHER_WEP; } else { type = WIFICIPHER_NOPASS; } } config = isExsits(scanResult.SSID); });
private WifiConfiguration isExsits(String SSID) { List for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("\"" + SSID + "\"")) { return existingConfig; } } return null; }
if (config == null) { if (type != WIFICIPHER_NOPASS) {//需要密碼 final EditText editText = new EditText(MainActivity.this); final int finalType = type; new AlertDialog.Builder(MainActivity.this).setTitle("請(qǐng)輸入Wifi密碼").setIcon( android.R.drawable.ic_dialog_info).setView( editText).setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.w("AAA", "editText.getText():" + editText.getText()); config = createWifiInfo(scanResult.SSID, editText.getText().toString(), finalType); connect(config); } }) .setNegativeButton("取消", null).show(); return; } else { config = createWifiInfo(scanResult.SSID, "", type); connect(config); } } else { connect(config); }
private void connect(WifiConfiguration config) { int wcgID = wifiManager.addNetwork(config); wifiManager.enableNetwork(wcgID, true); }
if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) { text_state.setText("連接已斷開"); } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final WifiInfo wifiInfo = wifiManager.getConnectionInfo(); text_state.setText("已連接到網(wǎng)絡(luò):" + wifiInfo.getSSID()); } } else { NetworkInfo.DetailedState state = info.getDetailedState(); if (state == state.CONNECTING) { text_state.setText("連接中..."); } else if (state == state.AUTHENTICATING) { text_state.setText("正在驗(yàn)證身份信息..."); } else if (state == state.OBTAINING_IPADDR) { text_state.setText("正在獲取IP地址..."); } else if (state == state.FAILED) { text_state.setText("連接失敗"); } } }
NetworkInfo.State.DISCONNECTED //連接已斷開 NetworkInfo.State.CONNECTED //已成功連接
NetworkInfo.DetailedState state = info.getDetailedState(); if (state == state.CONNECTING) { text_state.setText("連接中..."); } else if (state == state.AUTHENTICATING) { text_state.setText("正在驗(yàn)證身份信息..."); } else if (state == state.OBTAINING_IPADDR) { text_state.setText("正在獲取IP地址..."); } else if (state == state.FAILED) { text_state.setText("連接失敗"); }
IDLE:空閑 SCANNING:正在掃描 CONNECTING:連接中 AUTHENTICATING:正在進(jìn)行身份驗(yàn)證 OBTAINING_IPADDR:正在獲取Ip地址 CONNECTED:已連接 SUSPENDED:已暫停 DISCONNECTING:正在斷開連接 DISCONNECTED:已斷開 FAILED:失敗 BLOCKED:已阻止 VERIFYING_POOR_LINK:暫時(shí)關(guān)閉(網(wǎng)絡(luò)狀況不佳) CAPTIVE_PORTAL_CHECK:判斷是否需要瀏覽器二次登錄
** * 連接線程 * Created by 坤 on 2016/9/7. */ public class ConnectThread extends Thread{ private final Socket socket; private Handler handler; private InputStream inputStream; private OutputStream outputStream; public ConnectThread(Socket socket, Handler handler){ setName("ConnectThread"); this.socket = socket; this.handler = handler; } @Override public void run() { if(socket==null){ return; } handler.sendEmptyMessage(MainActivity.DEVICE_CONNECTED); try { //獲取數(shù)據(jù)流 inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); byte[] buffer = new byte[1024]; int bytes; while (true){ //讀取數(shù)據(jù) bytes = inputStream.read(buffer); if (bytes > 0) { final byte[] data = new byte[bytes]; System.arraycopy(buffer, 0, data, 0, bytes); Message message = Message.obtain(); message.what = MainActivity.GET_MSG; Bundle bundle = new Bundle(); bundle.putString("MSG",new String(data)); message.setData(bundle); handler.sendMessage(message); } } } catch (IOException e) { e.printStackTrace(); } } /** * 發(fā)送數(shù)據(jù) */ public void sendData(String msg){ if(outputStream!=null){ try { outputStream.write(msg.getBytes()); Message message = Message.obtain(); message.what = MainActivity.SEND_MSG_SUCCSEE; Bundle bundle = new Bundle(); bundle.putString("MSG",new String(msg)); message.setData(bundle); handler.sendMessage(message); } catch (IOException e) { e.printStackTrace(); Message message = Message.obtain(); message.what = MainActivity.SEND_MSG_ERROR; Bundle bundle = new Bundle(); bundle.putString("MSG",new String(msg)); message.setData(bundle); handler.sendMessage(message); } } } }
private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case DEVICE_CONNECTING: connectThread = new ConnectThread(listenerThread.getSocket(),handler); connectThread.start(); break; ... ... } } };
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ... ... listenerThread = new ListenerThread(PORT, handler); listenerThread.start(); }
if (info.getState().equals(NetworkInfo.State.CONNECTED)) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final WifiInfo wifiInfo = wifiManager.getConnectionInfo(); text_state.setText("已連接到網(wǎng)絡(luò):" + wifiInfo.getSSID()); if (wifiInfo.getSSID().equals(WIFI_HOTSPOT_SSID)) { //如果當(dāng)前連接到的wifi是熱點(diǎn),則開啟連接線程 new Thread(new Runnable() { @Override public void run() { try { ArrayList for (String ip : connectedIP) { if (ip.contains(".")) { Socket socket = new Socket(ip, PORT); connectThread = new ConnectThread(socket, handler); connectThread.start(); } } } catch (IOException e) { e.printStackTrace(); } } }).start(); } } else { ... } }
private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case DEVICE_CONNECTING: connectThread = new ConnectThread(listenerThread.getSocket(),handler); connectThread.start(); break; case DEVICE_CONNECTED: textview.setText("設(shè)備連接成功"); break; case SEND_MSG_SUCCSEE: textview.setText("發(fā)送消息成功:" + msg.getData().getString("MSG")); break; case SEND_MSG_ERROR: textview.setText("發(fā)送消息失敗:" + msg.getData().getString("MSG")); break; case GET_MSG: textview.setText("收到消息:" + msg.getData().getString("MSG")); break; } } };
以上是Android WiFi開發(fā)教程之WiFi熱點(diǎn)的創(chuàng)建與關(guān)閉示例的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!