我是靠谱客的博主 自然星星,最近开发中收集的这篇文章主要介绍Android之一键连接指定wifi,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

这段时间在做一个项目,需求是点击一个按钮输入密码就能连接到指定的wifi,不需要带设置wifi界面去进行设置,达到简化用户操作的目的。

主要代码:

progressDialog = ProgressDialog.show(context, "请稍候", "搜索中......", true, true);
					new Thread() {
						
						public void run() {
							// 关闭数据
							MobileData.toggleMobileData(context, false);
							wifiAdmin = new WifiAdmin(context);
							wifiAdmin.openWifi();
							String myssid = wifiAdmin.getMySSID(SSID);
							if (myssid == null) {
								sendMsg(1);
							} else {
								mySSID = wifiAdmin.getMySSID(SSID);
								sendMsg(2);								
							}
						}
					}.start();


Handler

private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				progressDialog.dismiss() ;
				// 确定已经打开指定wifi网络????
				MyAlertDialog.myConfirmDialog(context, "请您确认一下您的SSID为ChinaNet-G开头的WiFi热点设备是否已经打开!!!");

				break;
			case 2:
				progressDialog.dismiss() ;
				CommuActivity.this.wifiPasswordSet(mySSID);
				break;
			}
		}
	};

sendMsg方法

public void sendMsg(int flag) {
		Message myMessage = new Message();
		myMessage.what = flag;
		handler.sendMessage(myMessage);
	}


wifiPasswordSet方法

public void wifiPasswordSet(String label) {
		Builder builder = new Builder(context); // 对话框构造器
		builder.setTitle("WiFi密码输入"); // 设置弹出的对话框标题
		LayoutInflater inflater = this.getLayoutInflater();
		final View view = inflater.inflate(R.layout.wifipassword, null, true);
		//
		TextView wifissid = (TextView) view.findViewById(R.id.wifissid);
		wifissid.setText("SSID:" + label);
		EditText wifipassword = (EditText) view
				.findViewById(R.id.wifipasswordtext);
		System.out.println("password==="+wifipassword.getText().toString());
		builder.setView(view)
				.setPositiveButton("连接", new DialogInterface.OnClickListener() {
					// 确认按钮的监听器
					public void onClick(DialogInterface dialog, int which) {
						EditText wifipassword = (EditText) view
								.findViewById(R.id.wifipasswordtext);
						password = wifipassword.getText().toString();
						if (password == null || "".equals(password)) { // 密码为空时
							//密码输入为空处理部分
							
						} else {
							WifiConfiguration wcg = wifiAdmin.CreateWifiInfo(
									SSID, password, 3);
							boolean issuccess = wifiAdmin.addNetwork(wcg) ;
							if(issuccess){
								Toastclass.displayToast(context, "WiFi已经连接成功!") ;
							}else{
								Toastclass.displayToast(context, "WiFi连接失败,请检查密码输入是否正确!") ;
							}
//							while (!wifiAdmin.addNetwork(wcg)) {
//								try {
//									Thread.sleep(100);
//								} catch (InterruptedException e) {
//									// TODO Auto-generated catch block
//									e.printStackTrace();
//								}
//							}
						}
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).show();
	}


最关键的WifiAdmin类

package com.etour.freewalk.useclass;

import java.util.List;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;

public class WifiAdmin {
	// 定义WifiManager对象
	private WifiManager mWifiManager;
	// 定义WifiInfo对象
	private WifiInfo mWifiInfo;
	// 扫描出的网络连接列表
	private List<ScanResult> mWifiList;
	// 网络连接列表
	private List<WifiConfiguration> mWifiConfiguration;
	// 定义一个WifiLock
	WifiLock mWifiLock;

	// 构造器
	public WifiAdmin(Context context) {
		// 取得WifiManager对象
		mWifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		// 取得WifiInfo对象
		mWifiInfo = mWifiManager.getConnectionInfo();
	}

	// 打开WIFI
	public void openWifi() {
		if (!mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(true);
		}
	}

	// 关闭WIFI
	public void closeWifi() {
		if (mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(false);
		}
	}

	// 检查当前WIFI状态
	public int checkState() {
		return mWifiManager.getWifiState();
	}

	// 锁定WifiLock
	public void acquireWifiLock() {
		mWifiLock.acquire();
	}

	// 解锁WifiLock
	public void releaseWifiLock() {
		// 判断时候锁定
		if (mWifiLock.isHeld()) {
			mWifiLock.acquire();
		}
	}

	// 创建一个WifiLock
	public void creatWifiLock() {
		mWifiLock = mWifiManager.createWifiLock("Test");
	}

	// 得到配置好的网络
	public List<WifiConfiguration> getConfiguration() {
		return mWifiConfiguration;
	}

	// 指定配置好的网络进行连接
	public void connectConfiguration(int index) {
		// 索引大于配置好的网络索引返回
		if (index > mWifiConfiguration.size()) {
			return;
		}
		// 连接配置好的指定ID的网络
		mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,
				true);
	}

	public void startScan() {
		mWifiManager.startScan();
		// 得到扫描结果
		mWifiList = mWifiManager.getScanResults();
		// 得到配置好的网络连接
		mWifiConfiguration = mWifiManager.getConfiguredNetworks();
	}

	// 得到网络列表
	public List<ScanResult> getWifiList() {
		return mWifiList;
	}

	// 查看扫描结果
	public StringBuilder lookUpScan() {
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < mWifiList.size(); i++) {
			stringBuilder
					.append("Index_" + new Integer(i + 1).toString() + ":");
			// 将ScanResult信息转换成一个字符串包
			// 其中把包括:BSSID、SSID、capabilities、frequency、level
			stringBuilder.append((mWifiList.get(i)).toString());
			stringBuilder.append("/n");
			System.out.println("WifiList"+i+"->"+mWifiList.get(i).SSID);
		}
		return stringBuilder;
	}

	// 得到MAC地址
	public String getMacAddress() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
	}

	// 得到接入点的BSSID
	public String getBSSID() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
	}

	// 得到IP地址
	public int getIPAddress() {
		return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
	}

	// 得到连接的ID
	public int getNetworkId() {
		return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
	}

	// 得到WifiInfo的所有信息包
	public String getWifiInfo() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
	}

	// 添加一个网络并连接
	public boolean addNetwork(WifiConfiguration wcg) {
		int wcgID = mWifiManager.addNetwork(wcg);
		boolean b = mWifiManager.enableNetwork(wcgID, true);
		System.out.println("a--" + wcgID);
		System.out.println("b--" + b);
		return b;
	}

	// 断开指定ID的网络
	public void disconnectWifi(int netId) {
		mWifiManager.disableNetwork(netId);
		mWifiManager.disconnect();
	}
	
	public String getMySSID(String pSSID){
		
		while(mWifiList == null){ //如果没有扫描结果继续扫描
			startScan();  //开始扫描WIFI列表
			try {
				Thread.sleep(200) ; //500ms之后继续扫描
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		lookUpScan() ; //打印出扫描结果
		
		for (int i = 0; i < mWifiList.size(); i++) {
			if(mWifiList.get(i).SSID.contains(pSSID)){
				System.out.println("我要的SSID:" + mWifiList.get(i).SSID);
				return mWifiList.get(i).SSID; //得到目标SSID则返回结果
			}
		}
		return null ;
	}

	// 然后是一个实际应用方法,只验证过没有密码的情况:
	public WifiConfiguration CreateWifiInfo(String SSID, String Password,
			int Type) {	
		String mySSID = getMySSID(SSID) ;
		if(mySSID == null){
			return null ;
		}		
		
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
//		config.SSID = """ + SSID + """;
		config.SSID = """ + mySSID + """;

		WifiConfiguration tempConfig = this.IsExsits(SSID);
		if (tempConfig != null) {
			mWifiManager.removeNetwork(tempConfig.networkId);
		}

		if (Type == 1) // WIFICIPHER_NOPASS
		{
			config.wepKeys[0] = "";
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		}
		if (Type == 2) // WIFICIPHER_WEP
		{
			config.hiddenSSID = true;
			config.wepKeys[0] = """ + Password + """;
			config.allowedAuthAlgorithms
					.set(WifiConfiguration.AuthAlgorithm.SHARED);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers
					.set(WifiConfiguration.GroupCipher.WEP104);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		}
		if (Type == 3) // 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;
	}

	private WifiConfiguration IsExsits(String SSID) {
		List<WifiConfiguration> existingConfigs = mWifiManager
				.getConfiguredNetworks();
		for (WifiConfiguration existingConfig : existingConfigs) {
			System.out.println("WifiConfiguration--SSID:"+existingConfig.SSID+",preSharedKey:"+existingConfig.preSharedKey);
			System.out.println("WifiConfiguration--preSharedKey:"+existingConfig.preSharedKey);
//			if (existingConfig.SSID.equals(""" + SSID + """)) {
			if (existingConfig.SSID.contains(SSID)) {
				return existingConfig;
			}
		}
		return null;
	}

}
// 分为三种情况:1没有密码2用wep加密3用wpa加密


完毕,代码不是很完整,有需要的朋友我们可以讨论一下

最后

以上就是自然星星为你收集整理的Android之一键连接指定wifi的全部内容,希望文章能够帮你解决Android之一键连接指定wifi所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部