小编给大家分享一下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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。