Android 连接Wifi和创建Wifi热点的实例
程序员文章站
2024-03-03 23:19:22
本文实例讲述了连接wifi和创建wifi热点的方法。分享给大家供大家参考,具体如下:
android的热点功能不可见,用了反射的技术搞定之外。
e...
本文实例讲述了连接wifi和创建wifi热点的方法。分享给大家供大家参考,具体如下:
android的热点功能不可见,用了反射的技术搞定之外。
eclipse设置语言为utf-8才能查看中文注释
上代码:
mainactivity.java
package com.widget.hotspot; import android.os.bundle; import android.app.activity; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.util.log; import android.view.menu; import android.view.view; import android.widget.button; public class mainactivity extends activity { public static final string tag = "mainactivity"; private button mbtn1, mbtn2; private wifiadmin mwifiadmin; private context mcontext = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); mcontext = this; setcontentview(r.layout.activity_main); mbtn1 = (button)findviewbyid(r.id.button1); mbtn2 = (button)findviewbyid(r.id.button2); mbtn1.settext("点击连接wifi"); mbtn2.settext("点击创建wifi热点"); mbtn1.setonclicklistener(new button.onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub mwifiadmin = new wifiadmin(mcontext) { @override public void myunregisterreceiver(broadcastreceiver receiver) { // todo auto-generated method stub mainactivity.this.unregisterreceiver(receiver); } @override public intent myregisterreceiver(broadcastreceiver receiver, intentfilter filter) { // todo auto-generated method stub mainactivity.this.registerreceiver(receiver, filter); return null; } @override public void onnotifywificonnected() { // todo auto-generated method stub log.v(tag, "have connected success!"); log.v(tag, "###############################"); } @override public void onnotifywificonnectfailed() { // todo auto-generated method stub log.v(tag, "have connected failed!"); log.v(tag, "###############################"); } }; mwifiadmin.openwifi(); mwifiadmin.addnetwork(mwifiadmin.createwifiinfo("you_wifi", "mm123456", wifiadmin.type_wpa)); } }); mbtn2.setonclicklistener(new button.onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub wifiapadmin wifiap = new wifiapadmin(mcontext); wifiap.startwifiap("\"hotspot\"", "hhhhhh123"); } }); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_main, menu); return true; } @override public void onresume() { super.onresume(); log.d("rssi", "registered"); } @override public void onpause() { super.onpause(); log.d("rssi", "unregistered"); } }
wifiadmin.java
package com.widget.hotspot; import java.util.list; import java.util.timer; import java.util.timertask; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.net.connectivitymanager; import android.net.networkinfo; import android.net.networkinfo.detailedstate; 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 abstract class wifiadmin { private static final string tag = "wifiadmin"; private wifimanager mwifimanager; private wifiinfo mwifiinfo; // 扫描出的网络连接列表 private list<scanresult> mwifilist; private list<wificonfiguration> 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<wificonfiguration> existingconfigs = mwifimanager.getconfigurednetworks(); 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<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(); } }
wifiapadmin.java
package com.widget.hotspot; import java.lang.reflect.invocationtargetexception; import java.lang.reflect.method; import java.util.timer; import java.util.timertask; import android.content.context; import android.net.wifi.wificonfiguration; import android.net.wifi.wifimanager; import android.util.log; /** * 创建热点 * */ public class wifiapadmin { public static final string tag = "wifiapadmin"; 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.v(tag, "wifi enabled success!"); this.exit(); } else { log.v(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.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); method1.invoke(mwifimanager, netconfig, true); } 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(); } catch (securityexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (nosuchmethodexception e) { // todo auto-generated catch block 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; } }
mytimecheck.java
package com.widget.hotspot; public abstract class mytimercheck { private int mcount = 0; private int mtimeoutcount = 1; private int msleeptime = 1000; // 1s private boolean mexitflag = false; private thread mthread = null; /** * do not process ui work in this. */ public abstract void dotimercheckwork(); public abstract void dotimeoutwork(); public mytimercheck() { mthread = new thread(new runnable() { @override public void run() { // todo auto-generated method stub while (!mexitflag) { mcount++; if (mcount < mtimeoutcount) { dotimercheckwork(); try { mthread.sleep(msleeptime); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); exit(); } } else { dotimeoutwork(); } } } }); } /** * start * @param times how many times will check? * @param sleeptime ms, every check sleep time. */ public void start(int timeoutcount, int sleeptime) { mtimeoutcount = timeoutcount; msleeptime = sleeptime; mthread.start(); } public void exit() { mexitflag = true; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。