android学习-仿Wifi模块实现

最近研究android内核-系统关键服务的启动解析,然而我也不知道研究wifi的作用,就当兴趣去做吧(其实是作业-_-)

系统原生WiFI功能大概有:启动WiFI服务,扫描WiFi信息(这个好像已经被封装到WiFiManager中了),显示WiFi,连接WiFi,关闭WiFi......

Android提供WifiManager.java对wifi进行管理

WifiInfo是专门用来表示连接的对象,可以查看当前已连接的wifi信息

WifiConfiguration是保存已配置过了wifi信息

ScanResult是存放扫描到了所有wifi的一些信息,如wifi名,信号强度,是否加锁。。。。

大体步骤:

Context.getSystemService(Context.WIFI_SERVICE)来获取WifiManager对象管理WIFI设备

WifiManager.startScan() 开始扫描

WifiManager.getScanResults() 获取扫描测试的结果

WifiManager.calculateSignalLevel(scanResult.get(i).level,4) 获取信号等级

scanResult.get(i).capabilities 获取wifi是否加锁

linkWifi.IsExsits(SSID) 获取wifi是否已保存配置信息

listView.setAdapter(adapter)显示wifi信息

监听事件处理

end

简单项目结构图

MScanWifi.java是我自己定义了一个Bean类只是定义了一些用到了wifi信息

package com.example.android_wifitest.base;

import android.net.wifi.ScanResult;

public class MScanWifi {
    private int level;//wifi信号强度
    private String WifiName;
        //保存一个引用,在wifi连接时候用到
    public ScanResult scanResult;
    private boolean isLock;//是否是锁定
    private boolean isExsit;//是否是保存过的wifi
    public MScanWifi(){
        
    }
    public MScanWifi(ScanResult scanResult,String WifiName,int level,Boolean isLock){
        this.WifiName=WifiName;
        this.level=level;
        this.isLock=isLock;
        this.scanResult=scanResult;
    }
    public int getLevel() {
        return level;
    }
    public void setLevel(int level) {
        this.level = level;
    }
    public String getWifiName() {
        return WifiName;
    }
    public void setWifiName(String wifiName) {
        WifiName = wifiName;
    }
    public Boolean getIsLock() {
        return isLock;
    }
    public void setIsLock(boolean isLock) {
        this.isLock = isLock;
    }
    public boolean getIsExsit() {
        return isExsit;
    }
    public void setIsExsit(boolean isExsit) {
        this.isExsit = isExsit;
    }
    
}
        
View Code

LinkWifi.java这个封装了一些常用方法(这个类从其他人代码中copy)

package com.example.android_wifitest;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import android.app.Service;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;

public class LinkWifi {
    private WifiManager wifiManager;
    private Context context;
    /** 定义几种加密方式,一种是WEP,一种是WPA/WPA2,还有没有密码的情况 */
    public enum WifiCipherType {
        WIFI_CIPHER_WEP, WIFI_CIPHER_WPA_EAP, WIFI_CIPHER_WPA_PSK, WIFI_CIPHER_WPA2_PSK, WIFI_CIPHER_NOPASS
    }
    public LinkWifi(Context context) {
        this.context = context;
        wifiManager = (WifiManager) context
                .getSystemService(Service.WIFI_SERVICE);
    }
    public boolean ConnectToNetID(int netID) {
        System.out.println("ConnectToNetID netID=" + netID);
        return wifiManager.enableNetwork(netID, true);
    }
    public int CreateWifiInfo2(ScanResult wifiinfo, String pwd) {
        WifiCipherType type;

        if (wifiinfo.capabilities.contains("WPA2-PSK")) {
            // WPA-PSK加密
            type = WifiCipherType.WIFI_CIPHER_WPA2_PSK;
        } else if (wifiinfo.capabilities.contains("WPA-PSK")) {
            // WPA-PSK加密
            type = WifiCipherType.WIFI_CIPHER_WPA_PSK;
        } else if (wifiinfo.capabilities.contains("WPA-EAP")) {
            // WPA-EAP加密
            type = WifiCipherType.WIFI_CIPHER_WPA_EAP;
        } else if (wifiinfo.capabilities.contains("WEP")) {
            // WEP加密
            type = WifiCipherType.WIFI_CIPHER_WEP;
        } else {
            // 无密码
            type = WifiCipherType.WIFI_CIPHER_NOPASS;
        }

        WifiConfiguration config = CreateWifiInfo(wifiinfo.SSID,
                wifiinfo.BSSID, pwd, type);
        if (config != null) {
            return wifiManager.addNetwork(config);
        } else {
            return -1;
        }
    }
    /** 配置一个连接 */
    public WifiConfiguration CreateWifiInfo(String SSID, String BSSID,
            String password, WifiCipherType type) {

        int priority;

        WifiConfiguration config = this.IsExsits(SSID);
        if (config != null) {
            // Log.w("Wmt", "####之前配置过这个网络,删掉它");
            // wifiManager.removeNetwork(config.networkId); // 如果之前配置过这个网络,删掉它

            // 本机之前配置过此wifi热点,调整优先级后,直接返回
            return setMaxPriority(config);
        }

        config = new WifiConfiguration();
        /* 清除之前的连接信息 */
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        config.status = WifiConfiguration.Status.ENABLED;
        // config.BSSID = BSSID;
        // config.hiddenSSID = true;

        priority = getMaxPriority() + 1;
        if (priority > 99999) {
            priority = shiftPriorityAndSave();
        }

        config.priority = priority; // 2147483647;
        /* 各种加密方式判断 */
        if (type == WifiCipherType.WIFI_CIPHER_NOPASS) {
            Log.w("Wmt", "没有密码");
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        } else if (type == WifiCipherType.WIFI_CIPHER_WEP) {
            Log.w("Wmt", "WEP加密,密码" + password);
            config.preSharedKey = "\"" + 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;
        } else if (type == WifiCipherType.WIFI_CIPHER_WPA_EAP) {
            Log.w("Wmt", "WPA_EAP加密,密码" + password);

            config.preSharedKey = "\"" + password + "\"";
            config.hiddenSSID = true;
            config.status = WifiConfiguration.Status.ENABLED;
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);

            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN
                    | WifiConfiguration.Protocol.WPA);

        } else if (type == WifiCipherType.WIFI_CIPHER_WPA_PSK) {
            Log.w("Wmt", "WPA加密,密码" + password);

            config.preSharedKey = "\"" + password + "\"";
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN
                    | WifiConfiguration.Protocol.WPA);

        } else if (type == WifiCipherType.WIFI_CIPHER_WPA2_PSK) {
            Log.w("Wmt", "WPA2-PSK加密,密码=======" + password);

            config.preSharedKey = "\"" + password + "\"";
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

        } else {
            return null;
        }

        return config;
    }
    /** 查看以前是否也配置过这个网络 */
    public WifiConfiguration IsExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = wifiManager
                .getConfiguredNetworks();

        for (WifiConfiguration existingConfig : existingConfigs) {

            if (existingConfig.SSID.toString().equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }
    public WifiConfiguration setMaxPriority(WifiConfiguration config) {
        int priority = getMaxPriority() + 1;
        if (priority > 99999) {
            priority = shiftPriorityAndSave();
        }

        config.priority = priority; // 2147483647;
        System.out.println("priority=" + priority);

        wifiManager.updateNetwork(config);

        // 本机之前配置过此wifi热点,直接返回
        return config;
    }
    private int getMaxPriority() {
        List<WifiConfiguration> localList = this.wifiManager
                .getConfiguredNetworks();
        int i = 0;
        Iterator<WifiConfiguration> localIterator = localList.iterator();
        while (true) {
            if (!localIterator.hasNext())
                return i;
            WifiConfiguration localWifiConfiguration = (WifiConfiguration) localIterator
                    .next();
            if (localWifiConfiguration.priority <= i)
                continue;
            i = localWifiConfiguration.priority;
        }
    }

    private int shiftPriorityAndSave() {
        List<WifiConfiguration> localList = this.wifiManager
                .getConfiguredNetworks();
        sortByPriority(localList);
        int i = localList.size();
        for (int j = 0;; ++j) {
            if (j >= i) {
                this.wifiManager.saveConfiguration();
                return i;
            }
            WifiConfiguration localWifiConfiguration = (WifiConfiguration) localList
                    .get(j);
            localWifiConfiguration.priority = j;
            this.wifiManager.updateNetwork(localWifiConfiguration);
        }
    }

    private void sortByPriority(List<WifiConfiguration> paramList) {
        Collections.sort(paramList, new WifiManagerCompare());
    }

    class WifiManagerCompare implements Comparator<WifiConfiguration> {
        public int compare(WifiConfiguration paramWifiConfiguration1,
                WifiConfiguration paramWifiConfiguration2) {
            return paramWifiConfiguration1.priority
                    - paramWifiConfiguration2.priority;
        }
    }
}
View Code

上主代码之前先上xml布局

activity_main.xml

<?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:orientation="vertical" >
    
<LinearLayout 
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal"
     android:background="#cccccc"
     >
     <TextView 
        android:id="@+id/switch_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="关"
         />
    <!--wifi开关按钮-->
     <Switch
        android:id="@+id/switch_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="OFF"
        android:textOn="ON"
        android:thumb="@drawable/thumb_selector"
        android:track="@drawable/track_selector" />

    
</LinearLayout>
<LinearLayout 
    android:id="@+id/ListView_LinearLayout"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:background="#000000"
    >
</LinearLayout>

</LinearLayout>
View Code

<LinearLayout android:id="@+id/ListView_LinearLayout"。。。这个是为了加载listview准备了

android:thumb="@drawable/thumb_selector" thumb属性指的是:switch上面滑动的滑块

android:track="@drawable/track_selector"  track是滑道德背景图片显示

上面的两个资源文件

thumb_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"  android:drawable="@drawable/press" />
    <item android:state_pressed="false" android:drawable="@drawable/switch_enable"/>
</selector>
View Code

track_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/switch_track_default"/>
    <item android:state_checked="false" android:drawable="@drawable/switch_check_on"/>
</selector>
View Code

my_listview.xml这是为了实现动态加载XML布局使用

<?xml version="1.0" encoding="utf-8"?>

  <ListView
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/mlistview"
      android:divider="#cccccc"
      android:dividerHeight="1dp"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      />
View Code

listitems.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#666666"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/img_wifi_level"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:contentDescription="@string/hello_world"
        android:layout_marginLeft="20dp"
        android:src="@drawable/wifi_signal" />
    <LinearLayout
        android:layout_toRightOf="@id/img_wifi_level"
        android:layout_height="30dp"
        android:layout_width="wrap_content"
        android:layout_marginLeft="20dp"
        android:orientation="vertical" >
    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textSize="12sp"
        android:textStyle="bold"
        android:text="11111"
        />
    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textSize="12sp"
        android:visibility="gone"
         android:text="11111"
        />
   </LinearLayout>
</RelativeLayout>
View Code

dialog_inputpwd.xml弹出对话框显示的Content

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/dialognum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvPassWord"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:text="密码:"
            android:textColor="#19B2CC" />

        <EditText
            android:id="@+id/etPassWord"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="200dip"
            android:password="true" />
    </LinearLayout>

</RelativeLayout>
View Code

 

MainActivity.java是程序入口(有点累赘了)

  1 package com.example.android_wifitest;
  2 
  3 import android.os.Bundle;
  4 import android.os.Handler;
  5 import android.os.Message;
  6 import android.util.Log;
  7 
  8 import java.lang.ref.WeakReference;
  9 import java.util.ArrayList;
 10 import java.util.List;
 11 
 12 import com.example.android_wifitest.base.CommonAdapter;
 13 import com.example.android_wifitest.base.MScanWifi;
 14 import com.example.android_wifitest.base.ViewHolder;
 15 
 16 import android.app.Activity;
 17 import android.app.AlertDialog;
 18 import android.app.Service;
 19 import android.content.BroadcastReceiver;
 20 import android.content.Context;
 21 import android.content.DialogInterface;
 22 import android.content.Intent;
 23 import android.content.IntentFilter;
 24 import android.net.wifi.ScanResult;
 25 import android.net.wifi.WifiConfiguration;
 26 import android.net.wifi.WifiManager;
 27 import android.view.LayoutInflater;
 28 import android.view.Menu;
 29 import android.view.View;
 30 import android.widget.AdapterView;
 31 import android.widget.AdapterView.OnItemClickListener;
 32 import android.widget.CompoundButton;
 33 import android.widget.EditText;
 34 import android.widget.LinearLayout;
 35 import android.widget.ListView;
 36 import android.widget.Switch;
 37 import android.widget.TextView;
 38 import android.widget.CompoundButton.OnCheckedChangeListener;
 39 
 40 public class MainActivity extends Activity {
 41     public WifiManager mWifiManager;
 42     public List<MScanWifi> mScanWifiList;//自定义类存放用到的wifi信息
 43     public List<ScanResult> mWifiList;//存放系统扫描到了wifi信息
 44     public List<WifiConfiguration> mWifiConfiguration;//wifi配置信息
 45     public Context context = null;
 46     public Scanner mScanner;//自定义handler类每隔10秒自动扫描wifi信息
 47     public View view;
 48     public TextView wifi_status_txt;
 49     public Switch wifiSwitch;
 50     public ListView listView;
 51     private IntentFilter mFilter;
 52     private LinkWifi linkWifi;
 53     public LayoutInflater Inflater;
 54     private LinearLayout layout;
 55     
 56     @Override
 57     protected void onCreate(Bundle savedInstanceState) {
 58         super.onCreate(savedInstanceState);
 59         setContentView(R.layout.activity_main);
 60         context=this;
 61         Inflater=LayoutInflater.from(context);
 62         mWifiManager=(WifiManager) context.getSystemService(Service.WIFI_SERVICE);
 63         mScanner = new Scanner(this);
 64         linkWifi=new LinkWifi(context);
 65         initView();
 66         initIntentFilter();
 67         registerListener();
 68         registerBroadcast();
 69     }
 70     public void initIntentFilter() {
 71         // TODO Auto-generated method stub
 72         mFilter = new IntentFilter();
 73         mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
 74         mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
 75     }
 76     @Override
 77     protected void onResume() {
 78         // TODO Auto-generated method stub
 79         super.onResume();
 80         //用户操作activity时更新UI
 81         mScanner.forceScan();
 82     }
 83     /*@Override
 84     protected void onPause() {
 85         // TODO Auto-generated method stub
 86         super.onPause();
 87         //设备激进入休眠状态时执行
 88         unregisterBroadcast();
 89     }*/
 90     @Override
 91     protected void onDestroy() {
 92         super.onDestroy();
 93         context.unregisterReceiver(mReceiver); // 注销此广播接收器
 94     }
 95     public void initView() {
 96         // TODO Auto-generated method stub
 97         //获得要加载listview的布局
 98         layout=(LinearLayout) findViewById(R.id.ListView_LinearLayout);
 99         //动态获得listview布局
100          listView = (ListView) Inflater.inflate(
101                 R.layout.my_listview, null).findViewById(R.id.mlistview);
102         wifi_status_txt=(TextView) findViewById(R.id.switch_txt);
103         wifiSwitch=(Switch)findViewById(R.id.switch_status);
104         layout.addView(listView);
105     }
106     public void registerListener() {
107         // TODO Auto-generated method stub
108         wifiSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
109             
110             @Override
111             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
112                 // TODO Auto-generated method stub
113                 if (buttonView.isChecked()){
114                     wifi_status_txt.setText("开启"); 
115                     
116                     if (!mWifiManager.isWifiEnabled()) { // 当前wifi不可用  
117                         mWifiManager.setWifiEnabled(true);  
118                     }
119                     mWifiManager.startScan();
120                     
121                 }
122                 else{
123                     wifi_status_txt.setText("关闭");
124                     if (mWifiManager.isWifiEnabled()) {  
125                         mWifiManager.setWifiEnabled(false);
126                     }
127                     
128                 }
129             }
130         });
131         //给item添加监听事件
132         listView.setOnItemClickListener(new OnItemClickListener() {
133 
134             @Override
135             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
136                 // TODO Auto-generated method stub
137                 // 本机已经配置过的wifi
138                 final ScanResult wifi=mScanWifiList.get(position).scanResult;
139                 final WifiConfiguration wifiConfig=linkWifi.IsExsits(wifi.SSID);
140                 if(wifiConfig!= null){
141                     final int netID = wifiConfig.networkId;
142                     String actionStr;
143                     // 如果目前连接了此网络
144                     if (mWifiManager.getConnectionInfo().getNetworkId() == netID) {
145                         actionStr = "断开";
146                     } else {
147                         actionStr = "连接";
148                     }
149                     android.app.AlertDialog.Builder builder=new AlertDialog.Builder(context);
150                             builder.setTitle("提示");
151                             builder.setMessage("请选择你要进行的操作?");
152                             builder.setPositiveButton(actionStr,
153                             new DialogInterface.OnClickListener() {
154                                 public void onClick(DialogInterface dialog,
155                                         int whichButton) {
156 
157                                     if (mWifiManager.getConnectionInfo()
158                                             .getNetworkId() == netID) {
159                                         mWifiManager.disconnect();
160                                     } else {
161                                         
162                                         linkWifi.setMaxPriority(wifiConfig);
163                                         linkWifi.ConnectToNetID(wifiConfig.networkId);
164                                     }
165 
166                                 }
167                             });
168                             builder.setNeutralButton("忘记",
169                             new DialogInterface.OnClickListener() {
170                                 public void onClick(DialogInterface dialog,
171                                         int whichButton) {
172                                     mWifiManager.removeNetwork(netID);
173                                     return;
174                                 }
175                             });
176                             builder.setNegativeButton("取消",
177                             new DialogInterface.OnClickListener() {
178                                 public void onClick(DialogInterface dialog,
179                                         int whichButton) {
180                                     return;
181                                 }
182                             });
183                             builder.show();
184 
185             return;
186                     
187                 }
188                 if (mScanWifiList.get(position).getIsLock()) {
189                     // 有密码,提示输入密码进行连接
190 
191                     // final String encryption = capabilities;
192 
193                     LayoutInflater factory = LayoutInflater.from(context);
194                     final View inputPwdView = factory.inflate(R.layout.dialog_inputpwd,
195                             null);
196                     new AlertDialog.Builder(context)
197                             .setTitle("请输入该无线的连接密码")
198                             .setMessage("无线SSID:" + wifi.SSID)
199                             .setIcon(android.R.drawable.ic_dialog_info)
200                             .setView(inputPwdView)
201                             .setPositiveButton("确定",
202                                     new DialogInterface.OnClickListener() {
203                                         public void onClick(DialogInterface dialog,
204                                                 int which) {
205                                             EditText pwd = (EditText) inputPwdView
206                                                     .findViewById(R.id.etPassWord);
207                                             String wifipwd = pwd.getText().toString();
208 
209                                             // 此处加入连接wifi代码
210                                             int netID = linkWifi.CreateWifiInfo2(
211                                                     wifi, wifipwd);
212 
213                                             linkWifi.ConnectToNetID(netID);
214                                         }
215                                     })
216                             .setNegativeButton("取消",
217                                     new DialogInterface.OnClickListener() {
218                                         @Override
219                                         public void onClick(DialogInterface dialog,
220                                                 int which) {
221                                         }
222                                     }).setCancelable(false).show();
223 
224                 } else {
225                     // 无密码
226                     new AlertDialog.Builder(context)
227                             .setTitle("提示")
228                             .setMessage("你选择的wifi无密码,可能不安全,确定继续连接?")
229                             .setPositiveButton("确定",
230                                     new DialogInterface.OnClickListener() {
231                                         public void onClick(DialogInterface dialog,
232                                                 int whichButton) {
233 
234                                             // 此处加入连接wifi代码
235                                             int netID = linkWifi.CreateWifiInfo2(
236                                                     wifi, "");
237 
238                                             linkWifi.ConnectToNetID(netID);
239                                         }
240                                     })
241                             .setNegativeButton("取消",
242                                     new DialogInterface.OnClickListener() {
243                                         public void onClick(DialogInterface dialog,
244                                                 int whichButton) {
245                                             return;
246                                         }
247                                     }).show();
248 
249                 }
250 
251             }
252 
253         });
254     }
255     
256     /**
257      * 获取到自定义的ScanResult
258      **/
259     public void initScanWifilist(){
260         MScanWifi mScanwifi;
261         mScanWifiList=new ArrayList<MScanWifi>();
262         for(int i=0; i<mWifiList.size();i++){
263             int level=WifiManager.calculateSignalLevel(mWifiList.get(i).level,4);
264             String mwifiName=mWifiList.get(i).SSID;
265             boolean boolean1=false;
266             if(mWifiList.get(i).capabilities.contains("WEP")||mWifiList.get(i).capabilities.contains("PSK")||
267                     mWifiList.get(i).capabilities.contains("EAP")){
268                 boolean1=true;
269             }else{
270                 boolean1=false;
271             }
272             mScanwifi=new MScanWifi(mWifiList.get(i),mwifiName,level,boolean1);
273             if(linkWifi.IsExsits(mwifiName)!=null){
274                 mScanwifi.setIsExsit(true);
275                 }
276             else {mScanwifi.setIsExsit(false);
277                 }
278             mScanWifiList.add(mScanwifi);
279         }
280     }

281 public void registerBroadcast() { 282 context.registerReceiver(mReceiver, mFilter); 283 } 284 public void unregisterBroadcast(){ 285 context.unregisterReceiver(mReceiver); 286 } 287 288 /** 289 * 广播接收,监听网络 290 */ 291 private BroadcastReceiver mReceiver = new BroadcastReceiver() { 292 293 @Override 294 public void onReceive(Context context, Intent intent) { 295 handleEvent(context, intent); 296 } 297 }; 298 public void handleEvent(Context context, Intent intent) { 299 // TODO Auto-generated method stub 300 final String action = intent.getAction(); 301 // wifi状态发生改变。 302 if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) 303 { 304 /*int wifiState = intent.getIntExtra( 305 WifiManager.EXTRA_WIFI_STATE, 0);*/ 306 int wifiState=intent.getIntExtra( 307 WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN); 308 updateWifiStateChanged(wifiState); 309 } 310 else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { 311 updateWifiList(); 312 313 } 314 } 315 /** 316 * 更新WiFi列表UI 317 **/ 318 public void updateWifiList(){ 319 320 final int wifiState = mWifiManager.getWifiState(); 321 //获取WiFi列表并显示 322 switch (wifiState) { 323 case WifiManager.WIFI_STATE_ENABLED: 324 //wifi处于开启状态 325 initWifiData(); 326 listView.setAdapter(new CommonAdapter<MScanWifi>(context, 327 mScanWifiList,R.layout.listitems) { 328 @Override 329 public void convert(ViewHolder helper, MScanWifi item) { 330 // TODO Auto-generated method stub 331 helper.setText(R.id.tv1, item.getWifiName()); 332 //Log.i("1111111", item.getWifiName()+"是否开放"+item.getIsLock()); 333 if(item.getIsLock()){ 334 helper.setImageResource(R.id.img_wifi_level, R.drawable.wifi_signal_lock, item.getLevel()); 335 }else 336 {helper.setImageResource(R.id.img_wifi_level, R.drawable.wifi_signal_open, item.getLevel()); 337 } 338 if(item.getIsExsit()){ 339 TextView view=helper.getView(R.id.tv2); 340 view.setText("已保存"); 341 view.setVisibility(View.VISIBLE); 342 } 343 } 344 }); 345 break; 346 case WifiManager.WIFI_STATE_ENABLING: 347 listView.setAdapter(null); 348 break;//如果WiFi处于正在打开的状态,则清除列表 349 } 350 } 351 /** 352 * 初始化wifi信息 353 * mWifiList和mWifiConfiguration 354 **/ 355 public void initWifiData() { 356 // TODO Auto-generated method stub 357 mWifiList=mWifiManager.getScanResults(); 358 mWifiConfiguration=mWifiManager.getConfiguredNetworks(); 359 initScanWifilist(); 360 } 361 private void updateWifiStateChanged(int state) { 362 switch (state) { 363 case WifiManager.WIFI_STATE_ENABLING://正在打开WiFi 364 wifiSwitch.setEnabled(false); 365 Log.i("aaaaaa", "正在打开WiFi"); 366 break; 367 case WifiManager.WIFI_STATE_ENABLED://WiFi已经打开 368 //setSwitchChecked(true); 369 wifiSwitch.setEnabled(true); 370 wifiSwitch.setChecked(true); 371 layout.removeAllViews(); 372 layout.addView(listView); 373 mScanner.resume(); 374 Log.i("aaaaaa", "WiFi已经打开"); 375 break; 376 case WifiManager.WIFI_STATE_DISABLING://正在关闭WiFi 377 wifiSwitch.setEnabled(false); 378 Log.i("aaaaaa", "正在关闭WiFi"); 379 break; 380 case WifiManager.WIFI_STATE_DISABLED://WiFi已经关闭 381 //setSwitchChecked(false); 382 wifiSwitch.setEnabled(true); 383 wifiSwitch.setChecked(false); 384 layout.removeAllViews(); 385 Log.i("aaaaaa", "WiFi已经关闭 "); 386 break; 387 default: 388 //setSwitchChecked(false); 389 wifiSwitch.setEnabled(true); 390 break; 391 } 392 mScanner.pause();//移除message通知 393 } 394 @Override 395 public boolean onCreateOptionsMenu(Menu menu) { 396 // Inflate the menu; this adds items to the action bar if it is present. 397 getMenuInflater().inflate(R.menu.main, menu); 398 return true; 399 } 400 /** 401 * 这个类使用startScan()方法开始扫描wifi 402 * WiFi扫描结束时系统会发送该广播, 403 * 用户可以监听该广播通过调用WifiManager 404 * 的getScanResults方法来获取到扫描结果 405 * @author zwh 406 * 407 */ 408 public static class Scanner extends Handler { 409 private final WeakReference<MainActivity> mActivity; 410 private int mRetry = 0; 411 public Scanner(MainActivity activity){ 412 mActivity = new WeakReference<MainActivity>(activity); 413 } 414 void resume(){ 415 if (!hasMessages(0)) { 416 sendEmptyMessage(0); 417 } 418 } 419 420 void forceScan() { 421 removeMessages(0); 422 sendEmptyMessage(0); 423 } 424 425 void pause() { 426 mRetry = 0; 427 removeMessages(0); 428 } 429 430 @Override 431 public void handleMessage(Message message) { 432 if (mActivity.get().mWifiManager.startScan()) { 433 mRetry = 0; 434 } else if (++mRetry >= 3) { 435 mRetry = 0; 436 return; 437 } 438 sendEmptyMessageDelayed(0, 10*1000);//10s后再次发送message 439 } 440 } 441 442 }

 

CommonAdapter.java和ViewHolder.java是关于ListView适配器部分

项目总结:

  这里不得不说下,我代码可读性真的太差了,一个MainActivity代码那么多,bug还有一大堆没有处理,而且这个switch要限定我的这个apkminSdkVersion="14"手机版本至少14以上,还有弹出对话框其实可以修改成新建一个dialog类减少MainActivity代码达到代码复用。但这些不影响基本功能使用,学到了一些没有接触过了。如判别wifi是否加开放

item.getIsLock()
如果开放显示无锁的wifi信号强度否则相反

显示不同wifi信号强度

如开关切换-样式变化

动态加载xml布局addView(),哦!还有一点改善之处,在非UI线程进行数据处理,当数据处理完后发送消息给ui线程进行数据显示这个不知道可不可以(纸上谈兵)

缺点处处可见,不要介意欢迎提出宝贵意见

源码下载wifiTest

 

posted @ 2017-04-10 21:42  海绵般汲取  阅读(2250)  评论(0编辑  收藏  举报