Android Wifi 连接

Android 连接wif,搜索选择周边wifi,断开清除掉已保存的wifi

WIFI工具类


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");
        }
        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 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)
    {
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs)
        {
            if (existingConfig.SSID.equals("\""+SSID+"\""))
            {
                return existingConfig;
            }
        }
        return null;
    }

    public WifiManager getmWifiManager() {
        return mWifiManager;
    }

    public void setmWifiManager(WifiManager mWifiManager) {
        this.mWifiManager = mWifiManager;
    }

    public WifiInfo getmWifiInfo() {
        return mWifiInfo;
    }

    public void setmWifiInfo(WifiInfo mWifiInfo) {
        this.mWifiInfo = mWifiInfo;
    }
}
//分为三种情况:1没有密码2用wep加密3用wpa加密

选择需要连接的wifi


public class ChooseWifiActivity extends Activity {
    private ListView listView;
    private List<ScanResult> scanResults = new ArrayList<>();
    private ListAdapter listAdapter;
    private Context context;
    private WifiAdmin wifiAdmin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_wifi);
        context = this;
        initView();
        initData();
    }

    private void initView(){
        listView = (ListView)findViewById(R.id.list_ssid);
    }

    private void initData(){
        wifiAdmin = new WifiAdmin(context);
        listAdapter = new ListAdapter(context,R.layout.adapter_wifi_list,scanResults);
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ScanResult scanResult = scanResults.get(position);
                Intent intent = new Intent();
                intent.putExtra("ssid",scanResult.SSID);
                setResult(RESULT_OK,intent);
                finish();
            }
        });
        wifiAdmin.openWifi();

        getChoiceWifiList();

    }

    private void getChoiceWifiList(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                wifiAdmin.startScan();
                scanResults = wifiAdmin.getWifiList();
                listAdapter.refresh(scanResults);
            }
        });
    }

    private class ListAdapter extends BaseAdapter{
        private Context context;
        private int resourceId;
        private List<ScanResult> scanResults;
        private ScanResult result;
        private ViewHolder viewHolder;

        public ListAdapter(Context context, int resourceId, List<ScanResult> objects){
            this.context = context;
            this.resourceId = resourceId;
            this.scanResults = objects;
        }

        public void refresh(List<ScanResult> objects){
            scanResults.clear();
            scanResults.addAll(objects);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return scanResults.size();
        }

        @Override
        public ScanResult getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            result = scanResults.get(position);
            if (itemView == null){
                LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                viewHolder = new ViewHolder();
                itemView = inflater.inflate(resourceId,null);
                viewHolder.ssid = (TextView) itemView.findViewById(R.id.text_ssid);
                itemView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder)itemView.getTag();
            }
            viewHolder.ssid.setText(result.SSID);
            return itemView;
        }

        class ViewHolder{
            TextView ssid;
        }
    }
}

主操作页面


public class MainActivity extends Activity implements View.OnClickListener{
    private EditText edit_ssid;
    private EditText edit_paw;
    private Button btn_ssid;
    private Button btn_remove;
    private Button btn_connect;
    private WifiAdmin wifiAdmin;

    private Context context;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        initView();
        initData();
    }

    private void initView(){
        edit_ssid = (EditText)findViewById(R.id.edit_ssid);
        edit_paw = (EditText)findViewById(R.id.edit_paw);
        btn_ssid = (Button)findViewById(R.id.btn_ssid);
        btn_connect = (Button)findViewById(R.id.btn_connect);
        btn_remove = (Button)findViewById(R.id.btn_remove);
    }

    private void initData(){
        edit_ssid.setOnClickListener(this);
        edit_paw.setOnClickListener(this);
        btn_ssid.setOnClickListener(this);
        btn_connect.setOnClickListener(this);
        btn_remove.setOnClickListener(this);
        wifiAdmin = new WifiAdmin(context);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100){
            if (data != null){
                String ssid = data.getStringExtra("ssid");//wifi
                edit_ssid.setText(ssid);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_ssid:
                Intent intent = new Intent(context,ChooseWifiActivity.class);
                startActivityForResult(intent,100);
                break;
            case R.id.btn_connect:
                //wifiName is the SSID; wifiPass is the password;
                WifiConfiguration wcg=wifiAdmin.CreateWifiInfo(String.valueOf(edit_ssid.getText()), String.valueOf(edit_paw.getText()),3);
                wifiAdmin.addNetwork(wcg);
                break;
            case R.id.btn_remove:
                //wifiName is the SSID; wifiPass is the password;
                wifiAdmin.startScan();
                List<WifiConfiguration> wifiConfigurations = wifiAdmin.getConfiguration();
                for(WifiConfiguration configuration : wifiConfigurations){
                    String editssid = String.valueOf(edit_ssid.getText());
                    String ssid = configuration.SSID.replaceAll("\"","");
                    if(ssid.equals(editssid)){
                        wifiAdmin.getmWifiManager().removeNetwork(configuration.networkId);
                        wifiAdmin.getmWifiManager().saveConfiguration();
                        toastString("清除配置网络" + String.valueOf(edit_ssid.getText()));
                        break;
                    }
                }
                toastString("清除完成");
                break;
        }
    }

    private void toastString(final String str){
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context,str,Toast.LENGTH_SHORT);
            }
        });
    }
}

源码地址:http://download.csdn.net/download/feiniyan4944/10155054

  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论

打赏作者

普通网友

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值