Wifi连接+列表展示+防苹果弹窗输入密码连接

本人在这个项目中用到wifi扫描+连接,本想着偷懒省事去网上找,始终没有找到合适的就自己写了一篇,有不足请大神指出!

话不多说,上代码!

MainActivity主页面:

public class MainActivity extends AppCompatActivity {



    private WifiAdmin wifiManager;
    private List<ScanResult> wifiList;
    private ListView listView;
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==0){
                if(MainActivity.this.wifiList == null){
                    Toast.makeText(MainActivity.this, "wifi未打开!", Toast.LENGTH_LONG).show();
                    handler.sendEmptyMessageDelayed(0,1000);
                }else {
                    wifiManager.startScan();
                    wifiList = wifiManager.getWifiList();

                    for (int i = 0; i < wifiList.size()-1; i++) {
                        for (int j = wifiList.size()-1; j > i; j--) {
                            if (wifiList.get(j).SSID.equals(wifiList.get(i).SSID)) {
                                wifiList.remove(j);
                            }
                        }
                    }
                    myAdapter.setData(wifiList);
                    myAdapter.notifyDataSetChanged();
                    listView.setAdapter(myAdapter);
                    handler.sendEmptyMessageDelayed(0,500);
                }
            }
        }
    };
    private MyAdapter myAdapter;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        WifiScanList();
        handler.sendEmptyMessageDelayed(0,200);

    }
    public void WifiScanList(){
        wifiManager.startScan();
        wifiList = wifiManager.getWifiList();

        for (int i = 0; i < wifiList.size()-1; i++) {
            for (int j = wifiList.size()-1; j > i; j--) {
                if (wifiList.get(j).SSID.equals(wifiList.get(i).SSID)) {
                    wifiList.remove(j);
                }
            }
        }
        if (MainActivity.this.wifiList == null) {
            Toast.makeText(MainActivity.this, "wifi未打开!", Toast.LENGTH_LONG).show();
        } else {
            myAdapter.setData(MainActivity.this.wifiList);
            listView.setAdapter(myAdapter);
        }
    }

    private void init() {
        listView = (ListView) findViewById(R.id.listView);
        wifiManager = new WifiAdmin(this);
        wifiManager.openWifi();
        myAdapter = new MyAdapter(MainActivity.this);
    }


    public class MyAdapter extends BaseAdapter {

        LayoutInflater inflater;

        List<ScanResult> list;

        public MyAdapter(Context context) {
            // TODO Auto-generated constructor stub
            this.inflater = LayoutInflater.from(context);
        }
        public void setData(List<ScanResult> list){
            this.list = list;
        }


        @Override

        public int getCount() {

            // TODO Auto-generated method stub

            return list.size();

        }


        @Override

        public Object getItem(int position) {

            // TODO Auto-generated method stub

            return position;

        }


        @Override

        public long getItemId(int position) {

            // TODO Auto-generated method stub

            return position;

        }


        @Override

        public View getView(int position, View convertView, ViewGroup parent) {

            // TODO Auto-generated method stub

            View view = null;

            view = inflater.inflate(R.layout.item_wifi_list, null);

            final ScanResult scanResult = list.get(position);

            TextView textView = (TextView) view.findViewById(R.id.textView);

            textView.setText(scanResult.SSID);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    WifiConnectDialog(scanResult.SSID);
                }
            });
            return view;
        }

    }

    /**
     * 身份验证dialog
     */
    public void WifiConnectDialog(final String SSID) {
        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawable(new BitmapDrawable());
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_wificonnect_page, null);
        dialog.addContentView(dialogView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams
                .WRAP_CONTENT));
        final EditText et = (EditText) dialogView.findViewById(R.id.et_dialog_wifi_password);

        dialogView.findViewById(R.id.btn_cancel_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialogView.findViewById(R.id.btn_affirm_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String password = et.getText().toString().trim();
                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(MainActivity.this,"请输入密码",Toast.LENGTH_SHORT).show();
                } else {
                    boolean b = wifiManager.addNetwork(wifiManager.CreateWifiInfo(SSID, password, 3));
                    if(b){
                        Toast.makeText(MainActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }else {
                        Toast.makeText(MainActivity.this,"密码错误,请重新输入",Toast.LENGTH_SHORT).show();
                        et.setText("");
                    }

                }
            }
        });
    }

}

非常实用的WiFi工具类:

public class WifiAdmin {
    // 定义WifiManager对象
    private WifiManager mWifiManager;
    // 定义WifiInfo对象
    private WifiInfo mWifiInfo;
    // 扫描出的网络连接列表
    private List<ScanResult> mWifiList;
    // 网络连接列表
    private List<WifiConfiguration> mWifiConfiguration;
    // 定义一个WifiLock
    WifiManager.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) {
        mWifiManager.disconnect();
        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();
        if(existingConfigs!=null){
            for (WifiConfiguration existingConfig : existingConfigs)
            {
                if (existingConfig.SSID.equals("\""+SSID+"\""))
                {
                    return existingConfig;
                }
            }
        }
        return null;
    }
}

主MainActivity布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
                tools:context=".MainActivity" >

    <ListView

        android:id="@+id/listView"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" >

    </ListView>



</RelativeLayout>

列表item布局:

<?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">


    <TextView
        android:layout_centerInParent="true"
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="21sp"
        android:padding="15dp"/>

</RelativeLayout>

仿苹果弹窗布局,可用于其他地方:

<?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="wrap_content"
    android:background="@null"
    android:gravity="center">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@drawable/dialog_wifi_bg"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:gravity="center"
            android:text="请输入WiFi密码"
            android:textColor="#000"
            android:textSize="22sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <View
                android:layout_width="0dp"
                android:layout_height="1dp"
                android:layout_weight="1" />

            <EditText
                android:id="@+id/et_dialog_wifi_password"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:layout_weight="2"
                android:gravity="center"
                android:hint="请输入密码"
                android:inputType="textPassword"
                android:maxLines="1"
                android:textColor="#000"
                android:textSize="18sp" />

            <View
                android:layout_width="0dp"
                android:layout_height="1dp"
                android:layout_weight="1" />
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#ccc" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:gravity="center"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/btn_cancel_delete"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#00000000"
                android:gravity="center"
                android:padding="14dp"
                android:text="取消"
                android:textColor="#29b7f2"
                android:textSize="19sp" />

            <View
                android:layout_width="0.5dp"
                android:layout_height="match_parent"
                android:background="#ccc" />

            <TextView
                android:id="@+id/btn_affirm_delete"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#00000000"
                android:gravity="center"
                android:padding="14dp"
                android:text="确定"
                android:textColor="#29b7f2"
                android:textSize="19sp" />
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

猜你喜欢

转载自blog.csdn.net/Duanmuyang/article/details/80735687
今日推荐