android 代码设置、打开/关闭wifi热点及热点的连接、状态查询监听

转载:https://blog.csdn.net/luoboo525/article/details/7883998


  创建热点

[html]  view plain  copy
  1. package com.tel.lajoin.wifi.hotspot;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. import android.app.Activity;  
  6. import android.content.Context;  
  7. import android.net.wifi.WifiConfiguration;  
  8. import android.net.wifi.WifiManager;  
  9. import android.os.Bundle;  
  10. import android.view.View;  
  11. import android.widget.Button;  
  12.   
  13. public class HotspotActivity extends Activity {  
  14.     private WifiManager wifiManager;  
  15.     private Button open;  
  16.     private boolean flag=false;  
  17.   
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         // TODO Auto-generated method stub  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.main);  
  23.         //获取wifi管理服务  
  24.         wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
  25.         open=(Button)findViewById(R.id.open_hotspot);  
  26.         //通过按钮事件设置热点  
  27.         open.setOnClickListener(new View.OnClickListener() {  
  28.             @Override  
  29.             public void onClick(View v) {  
  30.                 //如果是打开状态就关闭,如果是关闭就打开  
  31.                 flag=!flag;  
  32.                 setWifiApEnabled(flag);  
  33.             }  
  34.         });  
  35.     }  
  36.   
  37.     // wifi热点开关  
  38.     public boolean setWifiApEnabled(boolean enabled) {  
  39.         if (enabled) { // disable WiFi in any case  
  40.             //wifi和热点不能同时打开,所以打开热点的时候需要关闭wifi  
  41.             wifiManager.setWifiEnabled(false);  
  42.         }  
  43.         try {  
  44.             //热点的配置类  
  45.             WifiConfiguration apConfig = new WifiConfiguration();  
  46.             //配置热点的名称(可以在名字后面加点随机数什么的)  
  47.             apConfig.SSID = "YRCCONNECTION";  
  48.             //配置热点的密码  
  49.             apConfig.preSharedKey="12122112";  
  50.                 //通过反射调用设置热点  
  51.             Method method = wifiManager.getClass().getMethod(  
  52.                     "setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);  
  53.             //返回热点打开状态  
  54.             return (Boolean) method.invoke(wifiManager, apConfig, enabled);  
  55.         } catch (Exception e) {  
  56.             return false;  
  57.         }  
  58.     }  
  59. }  
  布局就不写了吧,就一按钮,人人都知道的东西,写了也没啥意思。要实现文件传输,当然我们还需要写一个连接热点的客户端吧。连接热点的流程首先是搜索热点然后再判断热点是否符合规则然后再进行连接。

   

[html]  view plain  copy
  1. package com.tel.lajoin.wifiscan;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import android.app.Activity;  
  7. import android.content.BroadcastReceiver;  
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.content.IntentFilter;  
  11. import android.net.wifi.ScanResult;  
  12. import android.net.wifi.WifiConfiguration;  
  13. import android.net.wifi.WifiManager;  
  14. import android.os.Bundle;  
  15.   
  16. public class MainActivity extends Activity {  
  17.     private List<ScanResult> wifiList;  
  18.     private WifiManager wifiManager;  
  19.     private List<String> passableHotsPot;  
  20.     private WifiReceiver wifiReceiver;  
  21.     private boolean isConnected=false;  
  22.     private Button connect;  
  23.   
  24.     @Override  
  25.     public void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         init();  
  28.     }  
  29.   
  30.     /* 初始化参数 */  
  31.     public void init() {  
  32.         setContentView(R.layout.main);  
  33.         connect=(Button)findViewById(R.id.connect);  
  34.         wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);  
  35.         wifiReceiver = new WifiReceiver();  
  36.         //通过按钮事件搜索热点  
  37.         connect.setOnClickListener(new View.OnClickListener() {  
  38.             @Override  
  39.             public void onClick(View v) {  
  40.                 wifiManager.startScan();  
  41.             }  
  42.         });       
  43.     }  
  44.   
  45.     /* 监听热点变化 */  
  46.     private final class WifiReceiver extends BroadcastReceiver {  
  47.         @Override  
  48.         public void onReceive(Context context, Intent intent) {  
  49.             wifiList = wifiManager.getScanResults();  
  50.             if (wifiList == null || wifiList.size() == 0 || isConnected)  
  51.                 return;  
  52.             onReceiveNewNetworks(wifiList);  
  53.         }  
  54.     }  
  55.       
  56.     /*当搜索到新的wifi热点时判断该热点是否符合规格*/  
  57.     public void onReceiveNewNetworks(List<ScanResult> wifiList){  
  58.         passableHotsPot=new ArrayList<String>();  
  59.         for(ScanResult result:wifiList){  
  60.             System.out.println(result.SSID);  
  61.             if((result.SSID).contains("YRCCONNECTION"))  
  62.                 passableHotsPot.add(result.SSID);  
  63.         }  
  64.         synchronized (this) {  
  65.             connectToHotpot();  
  66.         }  
  67.     }  
  68.       
  69.     /*连接到热点*/  
  70.     public void connectToHotpot(){  
  71.         if(passableHotsPot==null || passableHotsPot.size()==0)  
  72.             return;  
  73.         WifiConfiguration wifiConfig=this.setWifiParams(passableHotsPot.get(0));  
  74.         int wcgID = wifiManager.addNetwork(wifiConfig);  
  75.         boolean flag=wifiManager.enableNetwork(wcgID, true);  
  76.         isConnected=flag;  
  77.         System.out.println("connect success? "+flag);  
  78.     }  
  79.       
  80.     /*设置要连接的热点的参数*/  
  81.     public WifiConfiguration setWifiParams(String ssid){  
  82.         WifiConfiguration apConfig=new WifiConfiguration();  
  83.         apConfig.SSID="\""+ssid+"\"";  
  84.         apConfig.preSharedKey="\"12122112\"";  
  85.         apConfig.hiddenSSID = true;  
  86.         apConfig.status = WifiConfiguration.Status.ENABLED;  
  87.         apConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);  
  88.         apConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);  
  89.         apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);  
  90.         apConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);  
  91.         apConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);  
  92.         apConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);  
  93.         return apConfig;  
  94.     }  
  95.       
  96.     @Override  
  97.     protected void onDestroy() {  
  98.         super.onDestroy();  
  99.         /*销毁时注销广播*/  
  100.         unregisterReceiver(wifiReceiver);  
  101.     }  
  102. }  

   代码很简单,而且都有注释的,相信大伙儿能够看明白。  那就这样吧,至于文件传输建议还是去看看socket相关的文章吧。



/**
     * 关闭WiFi热点
     */
    public void closeWifiHotspot() {
        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) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }



   /*获取热点的状态*/

public static boolean isWifiApOpen(Context context) {
    try {
      WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
      //通过放射获取 getWifiApState()方法
      Method method = manager.getClass().getDeclaredMethod( "getWifiApState" );
      //调用getWifiApState() ,获取返回值
      int state = ( int ) method.invoke(manager);
      //通过放射获取 WIFI_AP的开启状态属性
      Field field = manager.getClass().getDeclaredField( "WIFI_AP_STATE_ENABLED" );
      //获取属性值
      int value = ( int ) field.get(manager);
      //判断是否开启
      if (state == value) {
        return true ;
      } else {
        return false ;
      }
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    }
    return false ;
  }



状态监听

mIntentFilter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");
registerReceiver(mReceiver, mIntentFilter);

  1. private BroadcastReceiver wifiReceiver = new BroadcastReceiver(){  
  2.         public void onReceive(Context context, Intent intent) {  
  3.             String action = intent.getAction();  
  4.             if ("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(action)) {  
  5.                 //便携式热点的状态为:10---正在关闭;11---已关闭;12---正在开启;13---已开启  
  6.                 int state = intent.getIntExtra("wifi_state",  0);  
  7.                 Log.i(TAG, "state= "+state);  
  8.                 wiFiAPObserver.stateChanged(state);  
  9.             }  
  10.         }  
  11. };  

你可能感兴趣的:(Android)