Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 519|回复: 0

[默认分类] Android 连接Wifi和创建Wifi热点 demo

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-5-28 15:12:47 | 显示全部楼层 |阅读模式


      
    1. android的热点功能不可见,用了反射的技术搞定之外。
    复制代码
    1. Eclipse设置语言为utf-8才能查看中文注释
    复制代码

      
    上代码:
    MainActivity.java
      
    1. package com.widget.hotspot;
    2. import android.os.Bundle;
    3. import android.app.Activity;
    4. import android.content.BroadcastReceiver;
    5. import android.content.Context;
    6. import android.content.Intent;
    7. import android.content.IntentFilter;
    8. import android.util.Log;
    9. import android.view.Menu;
    10. import android.view.View;
    11. import android.widget.Button;
    12. public class MainActivity extends Activity {
    13.         public static final String TAG = "MainActivity";
    14.        
    15.         private Button mBtn1, mBtn2;
    16.        
    17.         private WifiAdmin mWifiAdmin;
    18.        
    19.         private Context mContext = null;
    20.         @Override
    21.         protected void onCreate(Bundle savedInstanceState) {
    22.                 super.onCreate(savedInstanceState);
    23.                
    24.                 mContext = this;
    25.                
    26.                 setContentView(R.layout.activity_main);
    27.                
    28.                 mBtn1 = (Button)findViewById(R.id.button1);
    29.                 mBtn2 = (Button)findViewById(R.id.button2);
    30.                 mBtn1.setText("点击连接Wifi");
    31.                 mBtn2.setText("点击创建Wifi热点");
    32.                 mBtn1.setOnClickListener(new Button.OnClickListener() {
    33.                        
    34.                         @Override
    35.                         public void onClick(View v) {
    36.                                 // TODO Auto-generated method stub
    37.                                 mWifiAdmin = new WifiAdmin(mContext) {
    38.                                        
    39.                                         @Override
    40.                                         public void myUnregisterReceiver(BroadcastReceiver receiver) {
    41.                                                 // TODO Auto-generated method stub
    42.                                                 MainActivity.this.unregisterReceiver(receiver);
    43.                                         }
    44.                                        
    45.                                         @Override
    46.                                         public Intent myRegisterReceiver(BroadcastReceiver receiver,
    47.                                                         IntentFilter filter) {
    48.                                                 // TODO Auto-generated method stub
    49.                                                 MainActivity.this.registerReceiver(receiver, filter);
    50.                                                 return null;
    51.                                         }
    52.                                        
    53.                                         @Override
    54.                                         public void onNotifyWifiConnected() {
    55.                                                 // TODO Auto-generated method stub
    56.                                                 Log.v(TAG, "have connected success!");
    57.                                                 Log.v(TAG, "###############################");
    58.                                         }
    59.                                        
    60.                                         @Override
    61.                                         public void onNotifyWifiConnectFailed() {
    62.                                                 // TODO Auto-generated method stub
    63.                                                 Log.v(TAG, "have connected failed!");
    64.                                                 Log.v(TAG, "###############################");
    65.                                         }
    66.                                 };
    67.                                 mWifiAdmin.openWifi();
    68.                                 mWifiAdmin.addNetwork(mWifiAdmin.createWifiInfo("YOU_WIFI", "MM123456", WifiAdmin.TYPE_WPA));
    69.                                
    70.                         }
    71.                 });
    72.                
    73.                 mBtn2.setOnClickListener(new Button.OnClickListener() {
    74.                        
    75.                         @Override
    76.                         public void onClick(View v) {
    77.                                 // TODO Auto-generated method stub
    78.                                
    79.                                 WifiApAdmin wifiAp = new WifiApAdmin(mContext);
    80.                                 wifiAp.startWifiAp(""HotSpot"", "hhhhhh123");
    81.                         }
    82.                 });
    83.                
    84.         }
    85.         @Override
    86.         public boolean onCreateOptionsMenu(Menu menu) {
    87.                 // Inflate the menu; this adds items to the action bar if it is present.
    88.                 getMenuInflater().inflate(R.menu.activity_main, menu);
    89.                 return true;
    90.         }
    91.          @Override
    92.             public void onResume() {
    93.                 super.onResume();
    94.                 
    95.                 Log.d("Rssi", "Registered");
    96.             }
    97.             @Override
    98.             public void onPause() {
    99.                 super.onPause();
    100.                 
    101.                 Log.d("Rssi", "Unregistered");
    102.             }
    103.        
    104. }
    复制代码

      


    WifiAdmin.java
    参考了://http://blog.csdn.net/yuanbohx/article/details/8109042
      
    1. package com.widget.hotspot;
    2. import java.util.List;
    3. import java.util.Timer;
    4. import java.util.TimerTask;
    5. import android.content.BroadcastReceiver;
    6. import android.content.Context;
    7. import android.content.Intent;
    8. import android.content.IntentFilter;
    9. import android.net.ConnectivityManager;
    10. import android.net.NetworkInfo;
    11. import android.net.NetworkInfo.DetailedState;
    12. import android.net.wifi.ScanResult;
    13. import android.net.wifi.WifiConfiguration;
    14. import android.net.wifi.WifiInfo;
    15. import android.net.wifi.WifiManager;
    16. import android.net.wifi.WifiManager.WifiLock;
    17. import android.util.Log;
    18. public abstract class WifiAdmin {
    19.        
    20.         private static final String TAG = "WifiAdmin";
    21.        
    22.         private WifiManager mWifiManager;
    23.         private WifiInfo mWifiInfo;
    24.         // 扫描出的网络连接列表
    25.         private List<ScanResult> mWifiList;
    26.         private List<WifiConfiguration> mWifiConfiguration;
    27.         private WifiLock mWifiLock;
    28.        
    29.         private String mPasswd = "";
    30.         private String mSSID = "";
    31.        
    32.         private Context mContext = null;
    33.         public WifiAdmin(Context context) {
    34.                
    35.                 mContext = context;
    36.                
    37.                 // 取得WifiManager对象
    38.                 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    39.                 // 取得WifiInfo对象
    40.                 mWifiInfo = mWifiManager.getConnectionInfo();
    41.                
    42.                 Log.v(TAG, "getIpAddress = " + mWifiInfo.getIpAddress());
    43.         }
    44.         // 打开WIFI
    45.         public void openWifi() {
    46.                 if (!mWifiManager.isWifiEnabled()) {
    47.                         mWifiManager.setWifiEnabled(true);
    48.                 }
    49.         }
    50.         // 关闭WIFI
    51.         public void closeWifi() {
    52.                 if (mWifiManager.isWifiEnabled()) {
    53.                         mWifiManager.setWifiEnabled(false);
    54.                 }
    55.         }
    56.     public abstract Intent myRegisterReceiver(BroadcastReceiver receiver, IntentFilter filter);
    57.    
    58.     public abstract void myUnregisterReceiver(BroadcastReceiver receiver);
    59.    
    60.     public abstract void onNotifyWifiConnected();
    61.    
    62.     public abstract void onNotifyWifiConnectFailed();
    63.        
    64.         // 添加一个网络并连接
    65.         public void addNetwork(WifiConfiguration wcg) {
    66.                
    67.                 register();
    68.                
    69.                 WifiApAdmin.closeWifiAp(mContext);
    70.                
    71.                 int wcgID = mWifiManager.addNetwork(wcg);
    72.                 boolean b = mWifiManager.enableNetwork(wcgID, true);
    73.         }
    74.        
    75.         public static final int TYPE_NO_PASSWD = 0x11;
    76.         public static final int TYPE_WEP = 0x12;
    77.         public static final int TYPE_WPA = 0x13;
    78.        
    79.         public void addNetwork(String ssid, String passwd, int type) {
    80.                 if (ssid == null || passwd == null || ssid.equals("")) {
    81.                         Log.e(TAG, "addNetwork() ## nullpointer error!");
    82.                         return;
    83.                 }
    84.                
    85.                 if (type != TYPE_NO_PASSWD && type != TYPE_WEP && type != TYPE_WPA) {
    86.                         Log.e(TAG, "addNetwork() ## unknown type = " + type);
    87.                 }
    88.                
    89.                 stopTimer();
    90.                 unRegister();
    91.                
    92.                 addNetwork(createWifiInfo(ssid, passwd, type));
    93.         }
    94.         private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    95.                 @Override
    96.                 public void onReceive(Context context, Intent intent) {
    97.                         // TODO Auto-generated method stub
    98.                         if (intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)) {
    99.                                 Log.d(TAG, "RSSI changed");
    100.                                
    101.                                 //有可能是正在获取,或者已经获取了
    102.                                 Log.d(TAG, " intent is " + WifiManager.RSSI_CHANGED_ACTION);
    103.                                
    104.                                 if (isWifiContected(mContext) == WIFI_CONNECTED) {
    105.                                         stopTimer();
    106.                                         onNotifyWifiConnected();
    107.                                         unRegister();
    108.                                 } else if (isWifiContected(mContext) == WIFI_CONNECT_FAILED) {
    109.                                         stopTimer();
    110.                                         closeWifi();
    111.                                         onNotifyWifiConnectFailed();
    112.                                         unRegister();
    113.                                 } else if (isWifiContected(mContext) == WIFI_CONNECTING) {
    114.                                        
    115.                                 }
    116.                         }
    117.                 }
    118.         };
    119.        
    120.         private final int STATE_REGISTRING = 0x01;
    121.         private final int STATE_REGISTERED = 0x02;
    122.         private final int STATE_UNREGISTERING = 0x03;
    123.         private final int STATE_UNREGISTERED = 0x04;
    124.        
    125.         private int mHaveRegister = STATE_UNREGISTERED;
    126.         private synchronized void register() {
    127.                 Log.v(TAG, "register() ##mHaveRegister = " + mHaveRegister);
    128.                 if (mHaveRegister == STATE_REGISTRING
    129.                                 || mHaveRegister == STATE_REGISTERED) {
    130.                         return ;
    131.                 }
    132.                
    133.                 mHaveRegister = STATE_REGISTRING;
    134.                 myRegisterReceiver(mBroadcastReceiver, new IntentFilter(WifiManager.RSSI_CHANGED_ACTION));
    135.                 mHaveRegister = STATE_REGISTERED;
    136.                
    137.                 startTimer();
    138.         }
    139.        
    140.         private synchronized void unRegister() {
    141.                 Log.v(TAG, "unRegister() ##mHaveRegister = " + mHaveRegister);
    142.                
    143.                 if (mHaveRegister == STATE_UNREGISTERED
    144.                                 || mHaveRegister == STATE_UNREGISTERING) {
    145.                         return ;
    146.                 }
    147.                
    148.                 mHaveRegister = STATE_UNREGISTERING;
    149.                 myUnregisterReceiver(mBroadcastReceiver);
    150.                 mHaveRegister = STATE_UNREGISTERED;
    151.         }
    152.        
    153.         private Timer mTimer = null;
    154.         private void startTimer() {
    155.                 if (mTimer != null) {
    156.                         stopTimer();
    157.                 }
    158.                
    159.                 mTimer = new Timer(true);
    160. //                mTimer.schedule(mTimerTask, 0, 20 * 1000);// 20s
    161.                 mTimer.schedule(mTimerTask, 30 * 1000);
    162.         }
    163.        
    164.         private TimerTask mTimerTask = new TimerTask() {
    165.                
    166.                 @Override
    167.                 public void run() {
    168.                         // TODO Auto-generated method stub
    169.                         Log.e(TAG, "timer out!");
    170.                         onNotifyWifiConnectFailed();
    171.                         unRegister();
    172.                 }
    173.         };
    174.        
    175.         private void stopTimer() {
    176.                 if (mTimer != null) {
    177.                         mTimer.cancel();
    178.                         mTimer = null;
    179.                 }
    180.         }
    181.        
    182.         @Override
    183.         protected void finalize() {
    184.                 try {
    185.                         super.finalize();
    186.                         unRegister();
    187.                 } catch (Throwable e) {
    188.                         // TODO Auto-generated catch block
    189.                         e.printStackTrace();
    190.                 }
    191.         }
    192.        
    193.         public WifiConfiguration createWifiInfo(String SSID, String password, int type) {
    194.                
    195.                 Log.v(TAG, "SSID = " + SSID + "## Password = " + password + "## Type = " + type);
    196.                
    197.                 WifiConfiguration config = new WifiConfiguration();
    198.                 config.allowedAuthAlgorithms.clear();
    199.                 config.allowedGroupCiphers.clear();
    200.                 config.allowedKeyManagement.clear();
    201.                 config.allowedPairwiseCiphers.clear();
    202.                 config.allowedProtocols.clear();
    203.                 config.SSID = """ + SSID + """;
    204.                 WifiConfiguration tempConfig = this.IsExsits(SSID);
    205.                 if (tempConfig != null) {
    206.                         mWifiManager.removeNetwork(tempConfig.networkId);
    207.                 }
    208.                
    209.                 // 分为三种情况:1没有密码2用wep加密3用wpa加密
    210.                 if (type == TYPE_NO_PASSWD) {// WIFICIPHER_NOPASS
    211.                         config.wepKeys[0] = "";
    212.                         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    213.                         config.wepTxKeyIndex = 0;
    214.                        
    215.                 } else if (type == TYPE_WEP) {  //  WIFICIPHER_WEP
    216.                         config.hiddenSSID = true;
    217.                         config.wepKeys[0] = """ + password + """;
    218.                         config.allowedAuthAlgorithms
    219.                                         .set(WifiConfiguration.AuthAlgorithm.SHARED);
    220.                         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    221.                         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    222.                         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    223.                         config.allowedGroupCiphers
    224.                                         .set(WifiConfiguration.GroupCipher.WEP104);
    225.                         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    226.                         config.wepTxKeyIndex = 0;
    227.                 } else if (type == TYPE_WPA) {   // WIFICIPHER_WPA
    228.                         config.preSharedKey = """ + password + """;
    229.                         config.hiddenSSID = true;
    230.                         config.allowedAuthAlgorithms
    231.                                         .set(WifiConfiguration.AuthAlgorithm.OPEN);
    232.                         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    233.                         config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    234.                         config.allowedPairwiseCiphers
    235.                                         .set(WifiConfiguration.PairwiseCipher.TKIP);
    236.                         // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    237.                         config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    238.                         config.allowedPairwiseCiphers
    239.                                         .set(WifiConfiguration.PairwiseCipher.CCMP);
    240.                         config.status = WifiConfiguration.Status.ENABLED;
    241.                 }
    242.                
    243.                 return config;
    244.         }
    245.        
    246.         public static final int WIFI_CONNECTED = 0x01;
    247.         public static final int WIFI_CONNECT_FAILED = 0x02;
    248.         public static final int WIFI_CONNECTING = 0x03;
    249.         /**
    250.          * 判断wifi是否连接成功,不是network
    251.          *
    252.          * @param context
    253.          * @return
    254.          */
    255.         public int isWifiContected(Context context) {
    256.                 ConnectivityManager connectivityManager = (ConnectivityManager) context
    257.                                 .getSystemService(Context.CONNECTIVITY_SERVICE);
    258.                 NetworkInfo wifiNetworkInfo = connectivityManager
    259.                                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    260.                
    261.                 Log.v(TAG, "isConnectedOrConnecting = " + wifiNetworkInfo.isConnectedOrConnecting());
    262.                 Log.d(TAG, "wifiNetworkInfo.getDetailedState() = " + wifiNetworkInfo.getDetailedState());
    263.                 if (wifiNetworkInfo.getDetailedState() == DetailedState.OBTAINING_IPADDR
    264.                                 || wifiNetworkInfo.getDetailedState() == DetailedState.CONNECTING) {
    265.                         return WIFI_CONNECTING;
    266.                 } else if (wifiNetworkInfo.getDetailedState() == DetailedState.CONNECTED) {
    267.                         return WIFI_CONNECTED;
    268.                 } else {
    269.                         Log.d(TAG, "getDetailedState() == " + wifiNetworkInfo.getDetailedState());
    270.                         return WIFI_CONNECT_FAILED;
    271.                 }
    272.         }
    273.        
    274.         private WifiConfiguration IsExsits(String SSID) {
    275.                 List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
    276.                 for (WifiConfiguration existingConfig : existingConfigs) {
    277.                         if (existingConfig.SSID.equals(""" + SSID + """) /*&& existingConfig.preSharedKey.equals(""" + password + """)*/) {
    278.                                 return existingConfig;
    279.                         }
    280.                 }
    281.                 return null;
    282.         }
    283.        
    284.         // 断开指定ID的网络
    285.         public void disconnectWifi(int netId) {
    286.                 mWifiManager.disableNetwork(netId);
    287.                 mWifiManager.disconnect();
    288.         }
    289.        
    290.         // 检查当前WIFI状态
    291.         public int checkState() {
    292.                 return mWifiManager.getWifiState();
    293.         }
    294.         // 锁定WifiLock
    295.         public void acquireWifiLock() {
    296.                 mWifiLock.acquire();
    297.         }
    298.         // 解锁WifiLock
    299.         public void releaseWifiLock() {
    300.                 // 判断时候锁定
    301.                 if (mWifiLock.isHeld()) {
    302.                         mWifiLock.acquire();
    303.                 }
    304.         }
    305.         // 创建一个WifiLock
    306.         public void creatWifiLock() {
    307.                 mWifiLock = mWifiManager.createWifiLock("Test");
    308.         }
    309.         // 得到配置好的网络
    310.         public List<WifiConfiguration> getConfiguration() {
    311.                 return mWifiConfiguration;
    312.         }
    313.         // 指定配置好的网络进行连接
    314.         public void connectConfiguration(int index) {
    315.                 // 索引大于配置好的网络索引返回
    316.                 if (index > mWifiConfiguration.size()) {
    317.                         return;
    318.                 }
    319.                 // 连接配置好的指定ID的网络
    320.                 mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,
    321.                                 true);
    322.         }
    323.         public void startScan() {
    324.                 mWifiManager.startScan();
    325.                 mWifiList = mWifiManager.getScanResults();
    326.                 mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    327.         }
    328.         // 得到网络列表
    329.         public List<ScanResult> getWifiList() {
    330.                 return mWifiList;
    331.         }
    332.         // 查看扫描结果
    333.         public StringBuilder lookUpScan() {
    334.                 StringBuilder stringBuilder = new StringBuilder();
    335.                 for (int i = 0; i < mWifiList.size(); i++) {
    336.                         stringBuilder
    337.                                         .append("Index_" + new Integer(i + 1).toString() + ":");
    338.                         // 将ScanResult信息转换成一个字符串包
    339.                         // 其中把包括:BSSID、SSID、capabilities、frequency、level
    340.                         stringBuilder.append((mWifiList.get(i)).toString());
    341.                         stringBuilder.append("/n");
    342.                 }
    343.                 return stringBuilder;
    344.         }
    345.         // 得到MAC地址
    346.         public String getMacAddress() {
    347.                 return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    348.         }
    349.         // 得到接入点的BSSID
    350.         public String getBSSID() {
    351.                 return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    352.         }
    353.         // 得到IP地址
    354.         public int getIPAddress() {
    355.                 return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    356.         }
    357.         // 得到连接的ID
    358.         public int getNetworkId() {
    359.                 return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    360.         }
    361.         // 得到WifiInfo的所有信息包
    362.         public String getWifiInfo() {
    363.                 return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    364.         }
    365. }
    复制代码




      
    WifiApAdmin.java
    参考了 http://blog.csdn.net/cxlmax/article/details/7827102
      
    1. package com.widget.hotspot;
    2. import java.lang.reflect.InvocationTargetException;
    3. import java.lang.reflect.Method;
    4. import java.util.Timer;
    5. import java.util.TimerTask;
    6. import android.content.Context;
    7. import android.net.wifi.WifiConfiguration;
    8. import android.net.wifi.WifiManager;
    9. import android.util.Log;
    10. /**
    11. * 创建热点
    12. *
    13. */
    14. public class WifiApAdmin {
    15.         public static final String TAG = "WifiApAdmin";
    16.        
    17.         public static void closeWifiAp(Context context) {
    18.                 WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    19.                 closeWifiAp(wifiManager);
    20.         }
    21.        
    22.         private WifiManager mWifiManager = null;
    23.        
    24.         private Context mContext = null;
    25.         public WifiApAdmin(Context context) {
    26.                 mContext = context;
    27.                
    28.                 mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);  
    29.                
    30.                 closeWifiAp(mWifiManager);
    31.         }
    32.        
    33.         private String mSSID = "";
    34.         private String mPasswd = "";
    35.         public void startWifiAp(String ssid, String passwd) {
    36.                 mSSID = ssid;
    37.                 mPasswd = passwd;
    38.                
    39.                 if (mWifiManager.isWifiEnabled()) {
    40.                         mWifiManager.setWifiEnabled(false);
    41.                 }
    42.                
    43.                 stratWifiAp();
    44.                
    45.                 MyTimerCheck timerCheck = new MyTimerCheck() {
    46.                        
    47.                         @Override
    48.                         public void doTimerCheckWork() {
    49.                                 // TODO Auto-generated method stub
    50.                                
    51.                                 if (isWifiApEnabled(mWifiManager)) {
    52.                                         Log.v(TAG, "Wifi enabled success!");
    53.                                         this.exit();
    54.                                 } else {
    55.                                         Log.v(TAG, "Wifi enabled failed!");
    56.                                 }
    57.                         }
    58.                         @Override
    59.                         public void doTimeOutWork() {
    60.                                 // TODO Auto-generated method stub
    61.                                 this.exit();
    62.                         }
    63.                 };
    64.                 timerCheck.start(15, 1000);
    65.                
    66.         }
    67.         public void stratWifiAp() {
    68.                 Method method1 = null;
    69.                 try {
    70.                         method1 = mWifiManager.getClass().getMethod("setWifiApEnabled",
    71.                                         WifiConfiguration.class, boolean.class);
    72.                         WifiConfiguration netConfig = new WifiConfiguration();
    73.                         netConfig.SSID = mSSID;
    74.                         netConfig.preSharedKey = mPasswd;
    75.                         netConfig.allowedAuthAlgorithms
    76.                                         .set(WifiConfiguration.AuthAlgorithm.OPEN);
    77.                         netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    78.                         netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    79.                         netConfig.allowedKeyManagement
    80.                                         .set(WifiConfiguration.KeyMgmt.WPA_PSK);
    81.                         netConfig.allowedPairwiseCiphers
    82.                                         .set(WifiConfiguration.PairwiseCipher.CCMP);
    83.                         netConfig.allowedPairwiseCiphers
    84.                                         .set(WifiConfiguration.PairwiseCipher.TKIP);
    85.                         netConfig.allowedGroupCiphers
    86.                                         .set(WifiConfiguration.GroupCipher.CCMP);
    87.                         netConfig.allowedGroupCiphers
    88.                                         .set(WifiConfiguration.GroupCipher.TKIP);
    89.                         method1.invoke(mWifiManager, netConfig, true);
    90.                 } catch (IllegalArgumentException e) {
    91.                         // TODO Auto-generated catch block
    92.                         e.printStackTrace();
    93.                 } catch (IllegalAccessException e) {
    94.                         // TODO Auto-generated catch block
    95.                         e.printStackTrace();
    96.                 } catch (InvocationTargetException e) {
    97.                         // TODO Auto-generated catch block
    98.                         e.printStackTrace();
    99.                 } catch (SecurityException e) {
    100.                         // TODO Auto-generated catch block
    101.                         e.printStackTrace();
    102.                 } catch (NoSuchMethodException e) {
    103.                         // TODO Auto-generated catch block
    104.                         e.printStackTrace();
    105.                 }
    106.         }
    107.         private static void closeWifiAp(WifiManager wifiManager) {
    108.                 if (isWifiApEnabled(wifiManager)) {
    109.                         try {
    110.                                 Method method = wifiManager.getClass().getMethod("getWifiApConfiguration");
    111.                                 method.setAccessible(true);
    112.                                 WifiConfiguration config = (WifiConfiguration) method.invoke(wifiManager);
    113.                                 Method method2 = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
    114.                                 method2.invoke(wifiManager, config, false);
    115.                         } catch (NoSuchMethodException e) {
    116.                                 // TODO Auto-generated catch block
    117.                                 e.printStackTrace();
    118.                         } catch (IllegalArgumentException e) {
    119.                                 // TODO Auto-generated catch block
    120.                                 e.printStackTrace();
    121.                         } catch (IllegalAccessException e) {
    122.                                 // TODO Auto-generated catch block
    123.                                 e.printStackTrace();
    124.                         } catch (InvocationTargetException e) {
    125.                                 // TODO Auto-generated catch block
    126.                                 e.printStackTrace();
    127.                         }
    128.                 }
    129.         }
    130.         private static boolean isWifiApEnabled(WifiManager wifiManager) {
    131.                 try {
    132.                         Method method = wifiManager.getClass().getMethod("isWifiApEnabled");
    133.                         method.setAccessible(true);
    134.                         return (Boolean) method.invoke(wifiManager);
    135.                 } catch (NoSuchMethodException e) {
    136.                         // TODO Auto-generated catch block
    137.                         e.printStackTrace();
    138.                 } catch (Exception e) {
    139.                         e.printStackTrace();
    140.                 }
    141.                 return false;
    142.         }
    143. }
    复制代码




      
    MyTimeCheck.java
      
    1. package com.widget.hotspot;
    2. public abstract class MyTimerCheck {
    3.         private int mCount = 0;
    4.         private int mTimeOutCount = 1;
    5.         private int mSleepTime = 1000; // 1s
    6.         private boolean mExitFlag = false;
    7.         private Thread mThread = null;
    8.        
    9.         /**
    10.          * Do not process UI work in this.
    11.          */
    12.         public abstract void doTimerCheckWork();
    13.        
    14.         public abstract void doTimeOutWork();
    15.        
    16.         public MyTimerCheck() {
    17.                 mThread = new Thread(new Runnable() {
    18.                        
    19.                         @Override
    20.                         public void run() {
    21.                                 // TODO Auto-generated method stub
    22.                                 while (!mExitFlag) {
    23.                                         mCount++;
    24.                                         if (mCount < mTimeOutCount) {
    25.                                                 doTimerCheckWork();
    26.                                                 try {
    27.                                                         mThread.sleep(mSleepTime);
    28.                                                 } catch (InterruptedException e) {
    29.                                                         // TODO Auto-generated catch block
    30.                                                         e.printStackTrace();
    31.                                                         exit();
    32.                                                 }
    33.                                         } else {
    34.                                                 doTimeOutWork();
    35.                                         }
    36.                                 }
    37.                         }
    38.                 });
    39.         }
    40.        
    41.         /**
    42.          * start
    43.          * @param times  How many times will check?
    44.          * @param sleepTime ms, Every check sleep time.
    45.          */
    46.         public void start(int timeOutCount, int sleepTime) {
    47.                 mTimeOutCount = timeOutCount;
    48.                 mSleepTime = sleepTime;
    49.                
    50.                 mThread.start();
    51.         }
    52.        
    53.         public void exit() {
    54.                 mExitFlag = true;
    55.         }
    56.        
    57. }
    复制代码

    xml布局简单不上了,
      
    效果自己试试看打印就知道了









      

      
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-20 20:24 , Processed in 0.396184 second(s), 47 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表