android.net.wifi 中常用的类有:
ScanResult, 主要用来描述已经检测出的接入点,包括接入点的地址、接入点的名称、身份认证、频率、信号强度等。
WifiConfiguration, wifi网络配置,包括安全配置等。
WifiInfo, Wifi无线连接的描述,包括接入点、网络连接状态、隐藏的接入点、IP地址、连接速度、MAC地址、网络ID、信号强度等。
WifiManager, 提供管理wifi连接的大部分API。
WifiManager.WifiLock, 通过WifiLock来锁定wifi网络,使其一直保持连接,直到这个锁定被释放。如果app需要下载很大的文件,就需要保持wifi锁,来确保app有足够的时间下载完成。wifi锁不能超越wifi-enabled设置,也没有飞行模式。
WifiManager提供的方法
1、开启WIFI
public void WifiOpen(){
if(!localWifiManager.isWifiEnabled()){
localWifiManager.setWifiEnabled(true);
}
}
2.扫描WIFI信号
public void WifiStartScan(){
localWifiManager.startScan();
}
3.得到扫描WIFI结果
public List<ScanResult> getScanResults(){
return localWifiManager.getScanResults();//得到扫描结果
}
4.得到WIFi的配置好的信息,包含配置好的密码
public void getConfiguration(){
wifiConfigList = localWifiManager.getConfiguredNetworks();//得到配置好的网络信息
for(int i =0;i<wifiConfigList.size();i++){
Log.i("getConfiguration",wifiConfigList.get(i).SSID);
Log.i("getConfiguration",String.valueOf(wifiConfigList.get(i).networkId));
}
}
5.根据WIFI的名称SSID判定指定WIFI是否已经配置好,配置好则返回其networkId,用于连接。之前尝试了BSSID地址没成功,所以只能使用SSID
public int IsConfiguration(String SSID){
Log.i("IsConfiguration",String.valueOf(wifiConfigList.size()));
for(int i = 0; i < wifiConfigList.size(); i++){
Log.i(wifiConfigList.get(i).SSID,String.valueOf( wifiConfigList.get(i).networkId));
if(wifiConfigList.get(i).SSID.equals(SSID)){//地址相同
return wifiConfigList.get(i).networkId;
}
}
return -1;
}
6、如果需要连接的WIFI没有配置好,即没有保存密码。则为指定名称ssid的WIFI添加密码信息psw,添加成功后返回给其分配的networId,同于连接
public int AddWifiConfig(List<ScanResult> wifiList,String ssid,String pwd){
int wifiId = -1;
for(int i = 0;i < wifiList.size(); i++){
ScanResult wifi = wifiList.get(i);
if(wifi.SSID.equals(ssid)){
Log.i("AddWifiConfig","equals");
WifiConfiguration wifiCong = new WifiConfiguration();
wifiCong.SSID = "\""+wifi.SSID+"\"";//\"转义字符,代表"
wifiCong.preSharedKey = "\""+pwd+"\"";//WPA-PSK密码
wifiCong.hiddenSSID = false;
wifiCong.status = WifiConfiguration.Status.ENABLED;
wifiId = localWifiManager.addNetwork(wifiCong);//将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态,成功返回ID,否则为-1
if(wifiId != -1){
return wifiId;
}
}
}
return wifiId;
}
全部代码
public class WifiUtils {
private WifiManager localWifiManager;//提供Wifi管理的各种主要API,主要包含wifi的扫描、建立连接、配置信息等
//private List<ScanResult> wifiScanList;//ScanResult用来描述已经检测出的接入点,包括接入的地址、名称、身份认证、频率、信号强度等
private List<WifiConfiguration> wifiConfigList;//WIFIConfiguration描述WIFI的链接信息,包括SSID、SSID隐藏、password等的设置
private WifiInfo wifiConnectedInfo;//已经建立好网络链接的信息
private WifiLock wifiLock;//手机锁屏后,阻止WIFI也进入睡眠状态及WIFI的关闭
public WifiUtils( Context context){
localWifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
}
//检查WIFI状态
public int WifiCheckState(){
return localWifiManager.getWifiState();
}
//开启WIFI
public void WifiOpen(){
if(!localWifiManager.isWifiEnabled()){
localWifiManager.setWifiEnabled(true);
}
}
//关闭WIFI
public void WifiClose(){
if(!localWifiManager.isWifiEnabled()){
localWifiManager.setWifiEnabled(false);
}
}
//扫描wifi
public void WifiStartScan(){
localWifiManager.startScan();
}
//得到Scan结果
public List<ScanResult> getScanResults(){
return localWifiManager.getScanResults();//得到扫描结果
}
//Scan结果转为Sting
public List<String> scanResultToString(List<ScanResult> list){
List<String> strReturnList = new ArrayList<String>();
for(int i = 0; i < list.size(); i++){
ScanResult strScan = list.get(i);
String str = strScan.toString();
boolean bool = strReturnList.add(str);
if(!bool){
Log.i("scanResultToSting","Addfail");
}
}
return strReturnList;
}
//得到Wifi配置好的信息
public void getConfiguration(){
wifiConfigList = localWifiManager.getConfiguredNetworks();//得到配置好的网络信息
for(int i =0;i<wifiConfigList.size();i++){
Log.i("getConfiguration",wifiConfigList.get(i).SSID);
Log.i("getConfiguration",String.valueOf(wifiConfigList.get(i).networkId));
}
}
//判定指定WIFI是否已经配置好,依据WIFI的地址BSSID,返回NetId
public int IsConfiguration(String SSID){
Log.i("IsConfiguration",String.valueOf(wifiConfigList.size()));
for(int i = 0; i < wifiConfigList.size(); i++){
Log.i(wifiConfigList.get(i).SSID,String.valueOf( wifiConfigList.get(i).networkId));
if(wifiConfigList.get(i).SSID.equals(SSID)){//地址相同
return wifiConfigList.get(i).networkId;
}
}
return -1;
}
//添加指定WIFI的配置信息,原列表不存在此SSID
public int AddWifiConfig(List<ScanResult> wifiList,String ssid,String pwd){
int wifiId = -1;
for(int i = 0;i < wifiList.size(); i++){
ScanResult wifi = wifiList.get(i);
if(wifi.SSID.equals(ssid)){
Log.i("AddWifiConfig","equals");
WifiConfiguration wifiCong = new WifiConfiguration();
wifiCong.SSID = "\""+wifi.SSID+"\"";//\"转义字符,代表"
wifiCong.preSharedKey = "\""+pwd+"\"";//WPA-PSK密码
wifiCong.hiddenSSID = false;
wifiCong.status = WifiConfiguration.Status.ENABLED;
wifiId = localWifiManager.addNetwork(wifiCong);//将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态,成功返回ID,否则为-1
if(wifiId != -1){
return wifiId;
}
}
}
return wifiId;
}
//连接指定Id的WIFI
public boolean ConnectWifi(int wifiId){
for(int i = 0; i < wifiConfigList.size(); i++){
WifiConfiguration wifi = wifiConfigList.get(i);
if(wifi.networkId == wifiId){
while(!(localWifiManager.enableNetwork(wifiId, true))){//激活该Id,建立连接
Log.i("ConnectWifi",String.valueOf(wifiConfigList.get(wifiId).status));//status:0--已经连接,1--不可连接,2--可以连接
}
return true;
}
}
return false;
}
//创建一个WIFILock
public void createWifiLock(String lockName){
wifiLock = localWifiManager.createWifiLock(lockName);
}
//锁定wifilock
public void acquireWifiLock(){
wifiLock.acquire();
}
//解锁WIFI
public void releaseWifiLock(){
if(wifiLock.isHeld()){//判定是否锁定
wifiLock.release();
}
}
//得到建立连接的信息
public void getConnectedInfo(){
wifiConnectedInfo = localWifiManager.getConnectionInfo();
}
//得到连接的MAC地址
public String getConnectedMacAddr(){
return (wifiConnectedInfo == null)? "NULL":wifiConnectedInfo.getMacAddress();
}
//得到连接的名称SSID
public String getConnectedSSID(){
return (wifiConnectedInfo == null)? "NULL":wifiConnectedInfo.getSSID();
}
//得到连接的IP地址
public int getConnectedIPAddr(){
return (wifiConnectedInfo == null)? 0:wifiConnectedInfo.getIpAddress();
}
//得到连接的ID
public int getConnectedID(){
return (wifiConnectedInfo == null)? 0:wifiConnectedInfo.getNetworkId();
}
}
自定义wifi弹出对话框
public class WifiPswDialog extends Dialog{
private Button cancelButton;
private Button okButton;
private EditText pswEdit;
private OnCustomDialogListener customDialogListener;
public WifiPswDialog(Context context,OnCustomDialogListener customListener) {
//OnCancelListener cancelListener) {
super(context);
// TODO Auto-generated constructor stub
customDialogListener = customListener;
}
//定义dialog的回调事件
public interface OnCustomDialogListener{
void back(String str);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi_config_dialog);
setTitle("请输入密码");
pswEdit = (EditText)findViewById(R.id.wifiDialogPsw);
cancelButton = (Button)findViewById(R.id.wifiDialogCancel);
okButton = (Button)findViewById(R.id.wifiDialogCertain);
cancelButton.setOnClickListener(buttonDialogListener);
okButton.setOnClickListener(buttonDialogListener);
}
private View.OnClickListener buttonDialogListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
if(view.getId() == R.id.wifiDialogCancel){
pswEdit = null;
customDialogListener.back(null);
cancel();//自动调用dismiss();
}
else{
customDialogListener.back(pswEdit.getText().toString());
dismiss();
}
}
};
}
具体实现
public classMainActivity extends Activity {
private String wifiPassword = null;
private Button wifiSearchButton;
private WifiUtils localWifiUtils;
private List<ScanResult> wifiResultList;
private List<String> wifiListString = new ArrayList<String>();
private ListView wifiSearchListView;
private ArrayAdapter<String> arrayWifiAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_pcmain);
wifiSearchButton = (Button)findViewById(R.id.wifiSearchButton);
WIFIButtonListener wifiButtonListener = new WIFIButtonListener();
wifiSearchButton.setOnClickListener(wifiButtonListener);
wifiSearchListView = (ListView)findViewById(R.id.wifiListView);
arrayWifiAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,wifiListString);
wifiSearchListView.setAdapter(arrayWifiAdapter);
ListOnItemClickListener wifiListListener = new ListOnItemClickListener();
wifiSearchListView.setOnItemClickListener(wifiListListener);
localWifiUtils = new WifiUtils(ControlPCMainActivity.this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.control_pcmain, menu);
return true;
}
class WIFIButtonListener implements OnClickListener{
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
wifiListString.clear();
localWifiUtils.WifiOpen();
localWifiUtils.WifiStartScan();
//0正在关闭,1WIFi不可用,2正在打开,3可用,4状态不可zhi
while(localWifiUtils.WifiCheckState() != WifiManager.WIFI_STATE_ENABLED){//等待Wifi开启
Log.i("WifiState",String.valueOf(localWifiUtils.WifiCheckState()));
}
try {
Thread.sleep(3000);//休眠3s,不休眠则会在程序首次开启WIFI时候,处理getScanResults结果,wifiResultList.size()发生异常
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wifiResultList = localWifiUtils.getScanResults();
localWifiUtils.getConfiguration();
if(wifiListString != null){
Log.i("WIFIButtonListener","dataChange");
scanResultToString(wifiResultList,wifiListString);
}
}
}
class ListOnItemClickListener implements OnItemClickListener{
String wifiItemSSID = null;
private View selectedItem;
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Log.i("ListOnItemClickListener","start");
selectedItem = arg1;
arg1.setBackgroundResource(R.color.gray);//点击的Item项背景设置
String wifiItem = arrayWifiAdapter.getItem(arg2);//获得选中的设备
String []ItemValue = wifiItem.split("--");
wifiItemSSID = ItemValue[0];
Log.i("ListOnItemClickListener",wifiItemSSID);
int wifiItemId = localWifiUtils.IsConfiguration("\""+wifiItemSSID+"\"");
Log.i("ListOnItemClickListener",String.valueOf(wifiItemId));
if(wifiItemId != -1){
if(localWifiUtils.ConnectWifi(wifiItemId)){//连接指定WIFI
arg1.setBackgroundResource(R.color.green);
}
}
else{//没有配置好信息,配置
WifiPswDialog pswDialog = new WifiPswDialog(ControlPCMainActivity.this,new OnCustomDialogListener() {
@Override
public void back(String str) {
// TODO Auto-generated method stub
wifiPassword = str;
if(wifiPassword != null){
int netId = localWifiUtils.AddWifiConfig(wifiResultList,wifiItemSSID, wifiPassword);
Log.i("WifiPswDialog",String.valueOf(netId));
if(netId != -1){
localWifiUtils.getConfiguration();//添加了配置信息,要重新得到配置信息
if(localWifiUtils.ConnectWifi(netId)){
selectedItem.setBackgroundResource(R.color.green);
}
}
else{
Toast.makeText(ControlPCMainActivity.this, "网络连接错误", Toast.LENGTH_SHORT).show();
selectedItem.setBackgroundResource(R.color.burlywood);
}
}
else{
selectedItem.setBackgroundResource(R.color.burlywood);
}
}
});
pswDialog.show();
}
}
}
//ScanResult类型转为String
public void scanResultToString(List<ScanResult> listScan,List<String> listStr){
for(int i = 0; i <listScan.size(); i++){
ScanResult strScan = listScan.get(i);
String str = strScan.SSID+"--"+strScan.BSSID;
boolean bool = listStr.add(str);
if(bool){
arrayWifiAdapter.notifyDataSetChanged();//数据更新,只能单个Item更新,不能够整体List更新
}
else{
Log.i("scanResultToSting","fail");
}
Log.i("scanResultToString",listStr.get(i));
}
}
private BroadcastReceiver WifiBroadcastRec = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String wifiAction = intent.getAction();
if(WifiManager.WIFI_STATE_CHANGED_ACTION.equals(wifiAction)){
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,WifiManager.WIFI_STATE_ENABLED);
if(wifiState == WifiManager.WIFI_STATE_ENABLED){
try {
Thread.sleep(3000);//休眠3s,不休眠则会在程序首次开启WIFI时候,处理getScanResults结果,wifiResultList.size()发生异常
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wifiResultList = localWifiUtils.getScanResults();
localWifiUtils.getConfiguration();
if(wifiListString != null){
scanResultToString(wifiResultList,wifiListString);
}
}
}
}
};
}
相关布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" android:gravity="center_horizontal" android:background="@color/burlywood" tools:context=".ControlPCMainActivity" >
<Button android:id="@+id/wifiSearchButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="搜索WIFI信号"/>
<ListView android:id="@+id/wifiListView" android:layout_width="match_parent" android:layout_height="wrap_content" android:cursorVisible="false" android:singleLine="false"/>
</LinearLayout>
对话框布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" style="@style/DialogStyle">
<EditText android:id="@+id/wifiDialogPsw" android:layout_width="match_parent" android:layout_height="wrap_content" android:password="true" android:singleLine="true"/>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_weight="2">
<Button android:id="@+id/wifiDialogCancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="取消" android:layout_weight="1"/>
<Button android:id="@+id/wifiDialogCertain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="确定" android:layout_weight="1"/>"
</LinearLayout>
</LinearLayout>