码迷,mamicode.com
首页 > 移动开发 > 详细

Android实现WiFi列表显示与连接

时间:2015-07-06 10:11:49      阅读:609      评论:0      收藏:0      [点我收藏+]

标签:wifi   显示   android   设置   

项目需要定制一下Android 4.4的设置界面,今天看一下WiFi部分的实现,首先是效果图:
技术分享

技术分享

代码比较简单,主要的功能在WiFiAdmin帮助类中,先看一下WiFiListActivity,代码中做了注释,就不细致说了:

package com.tchip.carlauncher.ui.activity;

import java.util.ArrayList;
import java.util.List;

import com.tchip.carlauncher.Constant;
import com.tchip.carlauncher.R;
import com.tchip.carlauncher.adapter.WiFiInfoAdapter;
import com.tchip.carlauncher.model.WifiInfo;
import com.tchip.carlauncher.ui.dialog.WifiPswDialog;
import com.tchip.carlauncher.ui.dialog.WifiPswDialog.OnCustomDialogListener;
import com.tchip.carlauncher.util.WifiAdmin;
import com.tchip.carlauncher.view.SwitchButton;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

public class WifiListActivity extends Activity {

    private ArrayList<WifiInfo> wifiArray;
    private WiFiInfoAdapter wifiInfoAdapter;
    private ListView listWifi;

    private ProgressBar updateProgress;
    private Button updateButton;
    private String wifiPassword = null;

    private WifiManager wifiManager;
    private WifiAdmin wiFiAdmin;
    private List<ScanResult> list;
    private ScanResult mScanResult;
    private StringBuffer sb = new StringBuffer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_wifi_list);

        wiFiAdmin = new WifiAdmin(WifiListActivity.this);
        initLayout();

        getAllNetWorkList();
    }

    public void initLayout() {
        listWifi = (ListView) findViewById(R.id.listWiFi);
        RelativeLayout btnToSettingFromWiFi = (RelativeLayout) findViewById(R.id.btnToSettingFromWiFi);
        btnToSettingFromWiFi.setOnClickListener(new MyOnClickListener());

        // 刷新按钮和进度条
        updateProgress = (ProgressBar) findViewById(R.id.updateProgress);
        updateProgress.setVisibility(View.INVISIBLE);
        updateButton = (Button) findViewById(R.id.updateButton);
        updateButton.setVisibility(View.VISIBLE);
        updateButton.setOnClickListener(new MyOnClickListener());

        SwitchButton switchWifi = (SwitchButton) findViewById(R.id.switchWifi);
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        switchWifi.setChecked(wifiManager.isWifiEnabled());
        switchWifi.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                wifiManager.setWifiEnabled(isChecked);
                // 更新WiFi列表
                if (isChecked) {
                    listWifi.setVisibility(View.VISIBLE);
                    updateProgress.setVisibility(View.VISIBLE);
                    updateButton.setVisibility(View.INVISIBLE);
                    new Thread(new refreshWifiThread()).start();
                } else {
                    listWifi.setVisibility(View.GONE);
                }
            }
        });

    }

    final Handler refreshWifiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 1:
                getAllNetWorkList();
                updateProgress.setVisibility(View.INVISIBLE);
                updateButton.setVisibility(View.VISIBLE);
                break;

            default:
                break;
            }
        }
    };

    public class refreshWifiThread implements Runnable {

        @Override
        public void run() {
            try {
                Thread.sleep(3000);
                Message message = new Message();
                message.what = 1;
                refreshWifiHandler.sendMessage(message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private class MyOnClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnToSettingFromWiFi:
                finish();
                break;
            case R.id.updateButton:
                updateButton.setVisibility(View.INVISIBLE);
                updateProgress.setVisibility(View.VISIBLE);
                new Thread(new refreshWifiThread()).start();
                break;
            default:
                break;
            }
        }

    }

    public void getAllNetWorkList() {

        wifiArray = new ArrayList<WifiInfo>();
        if (sb != null) {
            sb = new StringBuffer();
        }
        wiFiAdmin.startScan();
        list = wiFiAdmin.getWifiList();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                mScanResult = list.get(i);
                WifiInfo wifiInfo = new WifiInfo(mScanResult.BSSID,
                        mScanResult.SSID, mScanResult.capabilities,
                        mScanResult.level);
                wifiArray.add(wifiInfo);
            }

            wifiInfoAdapter = new WiFiInfoAdapter(getApplicationContext(),
                    wifiArray);
            listWifi.setAdapter(wifiInfoAdapter);

            //
            wiFiAdmin.getConfiguration();

            listWifi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                String wifiItemSSID = null;

                public void onItemClick(android.widget.AdapterView<?> parent,
                        android.view.View view, int position, long id) {

                    Log.d(Constant.TAG, "BSSID:" + list.get(position).BSSID);

                    // 连接WiFi
                    wifiItemSSID = list.get(position).SSID;
                    int wifiItemId = wiFiAdmin.IsConfiguration("\""
                            + list.get(position).SSID + "\"");
                    if (wifiItemId != -1) {
                        if (wiFiAdmin.ConnectWifi(wifiItemId)) {
                            // 连接已保存密码的WiFi
                            Toast.makeText(getApplicationContext(), "正在连接",
                                    Toast.LENGTH_SHORT).show();
                            updateButton.setVisibility(View.INVISIBLE);
                            updateProgress.setVisibility(View.VISIBLE);
                            new Thread(new refreshWifiThread()).start();
                        }
                    } else {
                        // 没有配置好信息,配置
                        WifiPswDialog pswDialog = new WifiPswDialog(
                                WifiListActivity.this,
                                new OnCustomDialogListener() {
                                    @Override
                                    public void back(String str) {
                                        wifiPassword = str;
                                        if (wifiPassword != null) {
                                            int netId = wiFiAdmin
                                                    .AddWifiConfig(list,
                                                            wifiItemSSID,
                                                            wifiPassword);
                                            if (netId != -1) {
                                                wiFiAdmin.getConfiguration();// 添加了配置信息,要重新得到配置信息
                                                if (wiFiAdmin
                                                        .ConnectWifi(netId)) {
                                                    // 连接成功,刷新UI
                                                    updateProgress
                                                            .setVisibility(View.VISIBLE);
                                                    updateButton
                                                            .setVisibility(View.INVISIBLE);
                                                    new Thread(
                                                            new refreshWifiThread())
                                                            .start();
                                                }
                                            } else {
                                                // 网络连接错误
                                            }
                                        } else {
                                        }
                                    }
                                });
                        pswDialog.show();
                    }
                }
            });
        }
    }

}

然后是WiFiAdmin:

package com.tchip.carlauncher.util;

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;
import android.util.Log;

public class WifiAdmin {
    /**
     * 定义一个WifiManager对象,提供Wifi管理的各种主要API,主要包含wifi的扫描、建立连接、配置信息等
     */
    private WifiManager mWifiManager;

    // WIFIConfiguration描述WIFI的链接信息,包括SSID、SSID隐藏、password等的设置
    private List<WifiConfiguration> wifiConfigList;

    // 定义一个WifiInfo对象
    private WifiInfo mWifiInfo;

    // 扫描出的网络连接列表
    private List<ScanResult> mWifiList;

    // 网络连接列表
    private List<WifiConfiguration> mWifiConfigurations;

    WifiLock mWifiLock;

    public static final int TYPE_NO_PASSWD = 0x11;
    public static final int TYPE_WEP = 0x12;
    public static final int TYPE_WPA = 0x13;

    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状态
     * 
     * @return
     */
    public int checkState() {
        return mWifiManager.getWifiState();
    }

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

    /**
     * 解锁wifiLock
     */
    public void releaseWifiLock() {
        // 判断是否锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    /**
     * 创建一个wifiLock
     */
    public void createWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("test");
    }

    /**
     * 得到配置好的网络
     * 
     * @return
     */
    public List<WifiConfiguration> getWiFiConfiguration() {
        return mWifiConfigurations;
    }

    /**
     * 指定配置好的网络进行连接
     * 
     * @param index
     */
    public void connetionConfiguration(int index) {
        if (index > mWifiConfigurations.size()) {
            return;
        }
        // 连接配置好指定ID的网络
        mWifiManager.enableNetwork(mWifiConfigurations.get(index).networkId,
                true);
    }

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

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

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

    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    public int getIpAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

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

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

    /**
     * 添加一个网络并连接
     * 
     * @param configuration
     */
    public void addNetwork(WifiConfiguration configuration) {
        int wcgId = mWifiManager.addNetwork(configuration);
        mWifiManager.enableNetwork(wcgId, true);
    }

    public WifiConfiguration createWifiInfo(String SSID, String Password,
            int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";

        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) {
        WifiConfiguration config = new WifiConfiguration();

        if (mWifiList.size() > 0) {
            for (int i = 0; i < mWifiList.size(); i++) {
                if (mWifiList.get(i).SSID.equals(ssid)) {

                    config = mWifiConfigurations.get(i);
                }
            }
        }
        return config;
    }

    /**
     * 断开指定ID的网络
     * 
     * @param netId
     */
    public void disConnectionWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

    // ============
    /**
     * 连接指定Id的WIFI
     * 
     * @param wifiId
     * @return
     */
    public boolean ConnectWifi(int wifiId) {
        for (int i = 0; i < wifiConfigList.size(); i++) {
            WifiConfiguration wifi = wifiConfigList.get(i);
            if (wifi.networkId == wifiId) {
                while (!(mWifiManager.enableNetwork(wifiId, true))) {// 激活该Id,建立连接
                    Log.i("ConnectWifi",
                            String.valueOf(wifiConfigList.get(wifiId).status));// status:0--已经连接,1--不可连接,2--可以连接
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 得到Wifi配置好的信息
     */
    public void getConfiguration() {
        wifiConfigList = mWifiManager.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
     * 
     * @param SSID
     * @return
     */
    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
     * 
     * @param wifiList
     * @param ssid
     * @param pwd
     * @return
     */
    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 = mWifiManager.addNetwork(wifiCong);// 将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态,成功返回ID,否则为-1
                if (wifiId != -1) {
                    return wifiId;
                }
            }
        }
        return wifiId;
    }
}

密码对话框比较简单:

package com.tchip.carlauncher.ui.dialog;

import com.tchip.carlauncher.R;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class WifiPswDialog extends Dialog {
    private Button cancelButton;
    private Button okButton;
    private EditText pswEdit;
    private OnCustomDialogListener customDialogListener;

    public WifiPswDialog(Context context, OnCustomDialogListener customListener) {
        super(context);
        customDialogListener = customListener;

    }

    /**
     * 定义dialog的回调事件
     */
    public interface OnCustomDialogListener {
        void back(String str);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        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) {
            if (view.getId() == R.id.wifiDialogCancel) {
                pswEdit = null;
                customDialogListener.back(null);
                cancel();// 自动调用dismiss();
            } else {
                customDialogListener.back(pswEdit.getText().toString());
                dismiss();
            }
        }
    };

}

版权声明:本文原创,转载请注明出处:http://blog.csdn.net/zhoumushui

Android实现WiFi列表显示与连接

标签:wifi   显示   android   设置   

原文地址:http://blog.csdn.net/zhoumushui/article/details/46770943

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!