您好,登錄后才能下訂單哦!
小編給大家分享一下Android WiFi開發教程之WiFi熱點的創建與關閉示例,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
/** * 創建Wifi熱點 */ private void createWifiHotspot() { if (wifiManager.isWifiEnabled()) { //如果wifi處于打開狀態,則關閉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);//開放系統認證 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; //通過反射調用設置熱點 try { Method method = wifiManager.getClass().getMethod( "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE); boolean enable = (Boolean) method.invoke(wifiManager, config, true); if (enable) { textview.setText("熱點已開啟 SSID:" + WIFI_HOTSPOT_SSID + " password:123456789"); } else { textview.setText("創建熱點失敗"); } } catch (Exception e) { e.printStackTrace(); textview.setText("創建熱點失敗"); } }
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);
/** * 關閉WiFi熱點 */ 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熱點 */ 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("信號很好"); } else if (level < -50 && level >= -70) { signl.setText("信號較好"); } else if (level < -70 && level >= -80) { signl.setText("信號一般"); } else if (level < -80 && level >= -100) { signl.setText("信號較差"); } else { signl.setText("信號很差"); } 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("請輸入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("已連接到網絡:" + wifiInfo.getSSID()); } } else { NetworkInfo.DetailedState state = info.getDetailedState(); if (state == state.CONNECTING) { text_state.setText("連接中..."); } else if (state == state.AUTHENTICATING) { text_state.setText("正在驗證身份信息..."); } 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("正在驗證身份信息..."); } else if (state == state.OBTAINING_IPADDR) { text_state.setText("正在獲取IP地址..."); } else if (state == state.FAILED) { text_state.setText("連接失敗"); }
IDLE:空閑 SCANNING:正在掃描 CONNECTING:連接中 AUTHENTICATING:正在進行身份驗證 OBTAINING_IPADDR:正在獲取Ip地址 CONNECTED:已連接 SUSPENDED:已暫停 DISCONNECTING:正在斷開連接 DISCONNECTED:已斷開 FAILED:失敗 BLOCKED:已阻止 VERIFYING_POOR_LINK:暫時關閉(網絡狀況不佳) 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 { //獲取數據流 inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); byte[] buffer = new byte[1024]; int bytes; while (true){ //讀取數據 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(); } } /** * 發送數據 */ 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("已連接到網絡:" + wifiInfo.getSSID()); if (wifiInfo.getSSID().equals(WIFI_HOTSPOT_SSID)) { //如果當前連接到的wifi是熱點,則開啟連接線程 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("設備連接成功"); break; case SEND_MSG_SUCCSEE: textview.setText("發送消息成功:" + msg.getData().getString("MSG")); break; case SEND_MSG_ERROR: textview.setText("發送消息失敗:" + msg.getData().getString("MSG")); break; case GET_MSG: textview.setText("收到消息:" + msg.getData().getString("MSG")); break; } } };
以上是Android WiFi開發教程之WiFi熱點的創建與關閉示例的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。