欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android 生成wifi热点以及扫描连接wifi

程序员文章站 2023-01-06 09:34:27
前段时间,有个朋友找我。做个小项目,就是可以生成wifi热点,然后给二维码给其他手机连接。那么这个项目就包括功能有:wifi连接,生成wifi热点,生成二维码,扫描二维码进行wifi连接。里面用到...

前段时间,有个朋友找我。做个小项目,就是可以生成wifi热点,然后给二维码给其他手机连接。那么这个项目就包括功能有:wifi连接,生成wifi热点,生成二维码,扫描二维码进行wifi连接。里面用到了zxing这个库。

1,图片展示

android 生成wifi热点以及扫描连接wifi

android 生成wifi热点以及扫描连接wifi2,生成wifi热点

/**
 * 创建热点
 */
public class wifiapadmin {
    public static final string tag = "show";

    public static void closewifiap(context context) {
        wifimanager wifimanager = (wifimanager) context.getsystemservice(context.wifi_service);
        closewifiap(wifimanager);
    }

    private wifimanager mwifimanager = null;

    private context mcontext = null;

    public wifiapadmin(context context) {
        mcontext = context;

        mwifimanager = (wifimanager) mcontext.getsystemservice(context.wifi_service);

        closewifiap(mwifimanager);
    }

    private string mssid = "";
    private string mpasswd = "";

    public void startwifiap(string ssid, string passwd) {
        mssid = ssid;
        mpasswd = passwd;

        if (mwifimanager.iswifienabled()) {
            mwifimanager.setwifienabled(false);
        }

        stratwifiap();

        mytimercheck timercheck = new mytimercheck() {

            @override
            public void dotimercheckwork() {
                // todo auto-generated method stub

                if (iswifiapenabled(mwifimanager)) {
                    log.i(tag, "wifi enabled success!");
                    this.exit();
                } else {
                    log.i(tag, "wifi enabled failed!");
                }
            }

            @override
            public void dotimeoutwork() {
                // todo auto-generated method stub
                this.exit();
            }
        };
        timercheck.start(15, 1000);

    }

    public void stratwifiap() {
        method method1 = null;
        try {
            method1 = mwifimanager.getclass().getmethod("setwifiapenabled",
                    wificonfiguration.class, boolean.class);
            wificonfiguration netconfig = new wificonfiguration();

            netconfig.ssid = mssid;
            netconfig.presharedkey = mpasswd;
            netconfig.status =  wificonfiguration.status.enabled;
            netconfig.allowedauthalgorithms
                    .set(wificonfiguration.authalgorithm.open);
            netconfig.allowedprotocols.set(wificonfiguration.protocol.rsn);
            netconfig.allowedprotocols.set(wificonfiguration.protocol.wpa);
            netconfig.allowedkeymanagement
                    .set(wificonfiguration.keymgmt.wpa_psk);
            netconfig.allowedpairwiseciphers
                    .set(wificonfiguration.pairwisecipher.ccmp);
            netconfig.allowedpairwiseciphers
                    .set(wificonfiguration.pairwisecipher.tkip);
            netconfig.allowedgroupciphers
                    .set(wificonfiguration.groupcipher.ccmp);
            netconfig.allowedgroupciphers
                    .set(wificonfiguration.groupcipher.tkip);

            //6.0以上手机需要设置权限write_settings 动态返回
            method1.invoke(mwifimanager, netconfig, true);

        } catch (illegalargumentexception e) {
            e.printstacktrace();
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (invocationtargetexception e) {
            log.i("show", e.tostring());
            e.printstacktrace();
        } catch (securityexception e) {
            e.printstacktrace();
        } catch (nosuchmethodexception e) {
            e.printstacktrace();
        }
    }

    private static void closewifiap(wifimanager wifimanager) {
        if (iswifiapenabled(wifimanager)) {
            try {
                method method = wifimanager.getclass().getmethod("getwifiapconfiguration");
                method.setaccessible(true);

                wificonfiguration config = (wificonfiguration) method.invoke(wifimanager);

                method method2 = wifimanager.getclass().getmethod("setwifiapenabled", wificonfiguration.class, boolean.class);
                method2.invoke(wifimanager, config, false);
            } catch (nosuchmethodexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            } catch (illegalargumentexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            } catch (illegalaccessexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            } catch (invocationtargetexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            }
        }
    }

    private static boolean iswifiapenabled(wifimanager wifimanager) {
        try {
            method method = wifimanager.getclass().getmethod("iswifiapenabled");
            method.setaccessible(true);
            return (boolean) method.invoke(wifimanager);

        } catch (nosuchmethodexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        } catch (exception e) {
            e.printstacktrace();
        }

        return false;
    }

}

3,扫描wifi,wifi连接类

public abstract class wifiadmin {

    private static final string tag = "show";

    private wifimanager mwifimanager;
    private wifiinfo mwifiinfo;
    // 扫描出的网络连接列表
    private list mwifilist;
    private list mwificonfiguration;

    private wifilock mwifilock;

    private string mpasswd = "";
    private string mssid = "";

    private context mcontext = null;

    public wifiadmin(context context) {

        mcontext = context;

        // 取得wifimanager对象
        mwifimanager = (wifimanager) context.getsystemservice(context.wifi_service);
        // 取得wifiinfo对象
        mwifiinfo = mwifimanager.getconnectioninfo();

        log.v(tag, "getipaddress = " + mwifiinfo.getipaddress());
    }

    // 打开wifi
    public void openwifi() {
        if (!mwifimanager.iswifienabled()) {
            mwifimanager.setwifienabled(true);
        }
    }

    // 关闭wifi
    public void closewifi() {
        if (mwifimanager.iswifienabled()) {
            mwifimanager.setwifienabled(false);
        }
    }

    public abstract intent myregisterreceiver(broadcastreceiver receiver, intentfilter filter);

    public abstract void myunregisterreceiver(broadcastreceiver receiver);

    public abstract void onnotifywificonnected();

    public abstract void onnotifywificonnectfailed();

    // 添加一个网络并连接
    public void addnetwork(wificonfiguration wcg) {

        register();

        wifiapadmin.closewifiap(mcontext);

        int wcgid = mwifimanager.addnetwork(wcg);
        boolean b = mwifimanager.enablenetwork(wcgid, true);
    }

    public static final int type_no_passwd = 0x11;
    public static final int type_wep = 0x12;
    public static final int type_wpa = 0x13;

    public void addnetwork(string ssid, string passwd, int type) {
        if (ssid == null || passwd == null || ssid.equals("")) {
            log.e(tag, "addnetwork() ## nullpointer error!");
            return;
        }

        if (type != type_no_passwd && type != type_wep && type != type_wpa) {
            log.e(tag, "addnetwork() ## unknown type = " + type);
        }

        stoptimer();
        unregister();

        addnetwork(createwifiinfo(ssid, passwd, type));
    }

    private broadcastreceiver mbroadcastreceiver = new broadcastreceiver() {

        @override
        public void onreceive(context context, intent intent) {
            // todo auto-generated method stub
            if (intent.getaction().equals(wifimanager.rssi_changed_action)) {
                log.d(tag, "rssi changed");

                //有可能是正在获取,或者已经获取了
                log.d(tag, " intent is " + wifimanager.rssi_changed_action);

                if (iswificontected(mcontext) == wifi_connected) {
                    stoptimer();
                    onnotifywificonnected();
                    unregister();
                } else if (iswificontected(mcontext) == wifi_connect_failed) {
                    stoptimer();
                    closewifi();
                    onnotifywificonnectfailed();
                    unregister();
                } else if (iswificontected(mcontext) == wifi_connecting) {

                }
            }
        }
    };

    private final int state_registring = 0x01;
    private final int state_registered = 0x02;
    private final int state_unregistering = 0x03;
    private final int state_unregistered = 0x04;

    private int mhaveregister = state_unregistered;
    private synchronized void register() {
        log.v(tag, "register() ##mhaveregister = " + mhaveregister);

        if (mhaveregister == state_registring
                || mhaveregister == state_registered) {
            return ;
        }

        mhaveregister = state_registring;
        myregisterreceiver(mbroadcastreceiver, new intentfilter(wifimanager.rssi_changed_action));
        mhaveregister = state_registered;

        starttimer();
    }

    private synchronized void unregister() {
        log.v(tag, "unregister() ##mhaveregister = " + mhaveregister);

        if (mhaveregister == state_unregistered
                || mhaveregister == state_unregistering) {
            return ;
        }

        mhaveregister = state_unregistering;
        myunregisterreceiver(mbroadcastreceiver);
        mhaveregister = state_unregistered;
    }

    private timer mtimer = null;
    private void starttimer() {
        if (mtimer != null) {
            stoptimer();
        }

        mtimer = new timer(true);
//		mtimer.schedule(mtimertask, 0, 20 * 1000);// 20s
        mtimer.schedule(mtimertask, 30 * 1000);
    }

    private timertask mtimertask = new timertask() {

        @override
        public void run() {
            // todo auto-generated method stub
            log.e(tag, "timer out!");
            onnotifywificonnectfailed();
            unregister();
        }
    };

    private void stoptimer() {
        if (mtimer != null) {
            mtimer.cancel();
            mtimer = null;
        }
    }

    @override
    protected void finalize() {
        try {
            super.finalize();
            unregister();
        } catch (throwable e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }

    public wificonfiguration createwifiinfo(string ssid, string password, int type) {

        log.v(tag, "ssid = " + ssid + "## password = " + password + "## type = " + 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);
        }

        // 分为三种情况:1没有密码2用wep加密3用wpa加密
        if (type == type_no_passwd) {// wificipher_nopass
            config.wepkeys[0] = "";
            config.allowedkeymanagement.set(wificonfiguration.keymgmt.none);
            config.weptxkeyindex = 0;

        } else if (type == type_wep) {  //  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;
        } else if (type == type_wpa) {   // 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;
    }

    public static final int wifi_connected = 0x01;
    public static final int wifi_connect_failed = 0x02;
    public static final int wifi_connecting = 0x03;
    /**
     * 判断wifi是否连接成功,不是network
     *
     * @param context
     * @return
     */
    public int iswificontected(context context) {
        connectivitymanager connectivitymanager = (connectivitymanager) context
                .getsystemservice(context.connectivity_service);
        networkinfo wifinetworkinfo = connectivitymanager
                .getnetworkinfo(connectivitymanager.type_wifi);

        log.v(tag, "isconnectedorconnecting = " + wifinetworkinfo.isconnectedorconnecting());
        log.d(tag, "wifinetworkinfo.getdetailedstate() = " + wifinetworkinfo.getdetailedstate());
        if (wifinetworkinfo.getdetailedstate() == detailedstate.obtaining_ipaddr
                || wifinetworkinfo.getdetailedstate() == detailedstate.connecting) {
            return wifi_connecting;
        } else if (wifinetworkinfo.getdetailedstate() == detailedstate.connected) {
            return wifi_connected;
        } else {
            log.d(tag, "getdetailedstate() == " + wifinetworkinfo.getdetailedstate());
            return wifi_connect_failed;
        }
    }

    private wificonfiguration isexsits(string ssid) {
        list existingconfigs = mwifimanager.getconfigurednetworks();
        if(existingconfigs == null)   return null;
        for (wificonfiguration existingconfig : existingconfigs) {
            if (existingconfig.ssid.equals("\"" + ssid + "\"") /*&& existingconfig.presharedkey.equals("\"" + password + "\"")*/) {
                return existingconfig;
            }
        }
        return null;
    }



    // 断开指定id的网络
    public void disconnectwifi(int netid) {
        mwifimanager.disablenetwork(netid);
        mwifimanager.disconnect();
    }

    // 检查当前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 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 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();
    }
}

4,生成二维码

 private void showproductcode(string string) {
        multiformatwriter formatwriter = new multiformatwriter();
        bitmap bitmap = null;
        try {
            // 按照指定的宽度,高度和附加参数对字符串进行编码
            bitmatrix bitmatrix = formatwriter.encode(string, barcodeformat.qr_code, 300, 300);
            bitmap = stringutil.bitmatrix2bitmap(bitmatrix);
        } catch (writerexception e) {
            e.printstacktrace();
        }

        imageview imageviewpointproductcode = (imageview) findviewbyid(r.id.imageviewpointproductcode);
        if (imageviewpointproductcode != null && bitmap != null) {
            imageviewpointproductcode.setimagebitmap(bitmap);
        }
    }

5,权限

    
    
    
    
    
    
    
    

    
  

这边博客以及编译环境是21,对应5.1。拿5.0以下手机测试问题不大。

测试时候:发现6.0以上手机,开启wifi热点属于操作系统权限。代码开启权限有时会不成功的。

wifi还没开启,连接时候要弹出是否开启wifi。

扫描二维码时候,要调用摄像头。

就是好多权限要处理好。就是有可能6.0没有崩溃,7.0以上崩溃。做多点机型的测试。