【Android开发】自动连接上wifi的Ap热点

public class MainActivity extends Activity {

	private WifiManager mWifiManager;
	private List configNetworks;
	private HandlerThread ht;
	private MyHandler mHandler;
	private String AssignedWifi = "HiWiFi_014C8E";
	private String Password = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		if (mWifiManager.isWifiEnabled()) {
			Log.i("ntb", "wifi has be enable");
		} else {
			mWifiManager.setWifiEnabled(true);
		}
		ht = new HandlerThread("ht");
		ht.start();
		mHandler = new MyHandler();
		Message msg = mHandler.obtainMessage();
		Bundle bundle = new Bundle();
		bundle.putBoolean("Key1", true);
		msg.setData(bundle);
		msg.sendToTarget();

		//scan wifi
		List scanResult = mWifiManager.getScanResults();
		Log.i("ntb", "scanResult size = " + scanResult.size());
		for (ScanResult res : scanResult) {
			if (AssignedWifi.equals(res.SSID))
				Log.i("ntb", "1111111111111111111");
			else 
				Log.i("ntb", "2222222222222222222" + res.SSID);
			Log.i("ntb", res.toString());
		}

		//get current wifi info
		WifiInfo info = mWifiManager.getConnectionInfo();
		Log.i("ntb", info.getSSID());
		Log.i("ntb", "onCreate finish");
	}
	
	/*这里以Handler去处理耗时操作*/
	private class MyHandler extends Handler {
		public MyHandler() {
			// TODO Auto-generated constructor stub
		}
		
		public MyHandler(Looper looper) {
			// TODO Auto-generated constructor stub
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(500);//做个延时,让主线程先运行一下
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			super.handleMessage(msg);
			Bundle b = msg.getData();
			if (b.getBoolean("Key1") == true) {
				WifiConfiguration wifiConfig = MainActivity.this.CreateWifiInfo(AssignedWifi, Password, 1);//这里创建一个WifiConfiguration
				MainActivity.this.addNetwork(wifiConfig);//假如netWorkId并且使能
			}
			
		}
	}

	///////////////////////
	/*下面分三种情况,分别是没有密码,wep模式,wpa模式,去创建对应的WifiConfiguration对象*/
	private WifiConfiguration CreateWifiInfo (String SSID, String Password, int type) {
		WifiConfiguration config = new WifiConfiguration();
		Log.i("ntb", "108");
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.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;
            if (Password.length() != 0) {
            	int length = Password.length();
            	if ((length == 10 || length == 26 || length == 58) && Password.matches("[0-9A-Fa-f]*")) {
            		config.wepKeys[0] = Password;
            	} else {
            		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;
            config.status = WifiConfiguration.Status.ENABLED;
            config.BSSID = "4c:60:de:3e:e7:b4";

        }  
        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;  
	        config.BSSID = "4c:60:de:3e:e7:b4";
        } 
         return config;
	}
	
	/////////////////////////////////
	public void addNetwork(WifiConfiguration wcg) {
	     int wcgID = mWifiManager.addNetwork(wcg); 
	     if (-1 == wcgID) {
	    	 Log.i("ntb", "wrong net id");
	     }
	     //这里我先断开,再使能,然后重新连接,正常的话android应该会主动去连接我配置好的热点
//	     mWifiManager.disconnect();
	     boolean b =  mWifiManager.enableNetwork(wcgID, true);
	     boolean c = mWifiManager.reassociate();
	     System.out.println("a--" + wcgID); 
	     System.out.println("b--" + b);
	     System.out.println("c--" + c); 
	    }  
	
	/////////////////////////////////
	 private WifiConfiguration IsExsits(String SSID)  {   
        List existingConfigs = mWifiManager.getConfiguredNetworks();  
        Log.i("ntb", "" + existingConfigs.size());
	    for (WifiConfiguration existingConfig : existingConfigs) {   

		    if (existingConfig.SSID != null && existingConfig.SSID.equals("\"" + SSID + "\""))   
		    {   
		        return existingConfig;
		    }
	   }   
       return null;
    } 

	 ////////////////////////////////////////
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

 

你可能感兴趣的:(Android开发及测试)