这两天帮别人做个小玩意,要求由android客户端往指定的wifi路由器上发送指令来控制单片机末端的设备,本来想着在进入客户端后自动连接到指定热点,
这样自动化的用户体验会好些,结果写好了以后人家说不用,就让用户手动连接吧,应为是小活也不是很在意,不过把这段代码共享下吧或者自己以后用的话也方便。
Activity内容如下:
1 package com.shineEye.www; 2 3 import java.util.List; 4 5 import android.Manifest.permission; 6 import android.app.Activity; 7 import android.app.Service; 8 import android.content.BroadcastReceiver; 9 import android.content.Context; 10 import android.content.Intent; 11 import android.content.IntentFilter; 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.os.Bundle; 17 import android.os.Handler; 18 import android.os.Message; 19 import android.util.Log; 20 import android.view.View; 21 import android.view.View.OnClickListener; 22 import android.widget.Button; 23 import android.widget.Toast; 24 25 /** 26 * @Class Name : WifiAutoConnection.java 27 * @Description WIFI自动连接测试类 28 * @Author YuanLiangFeng 袁良锋 lufengdie@126.com 29 * @Date 2013-4-18 - 上午12:09:44 30 */ 31 public class WifiAutoConnection extends Activity implements OnClickListener{ 32 33 34 private final String TAG = getClass().getSimpleName(); 35 /** 指定热点SSID **/ 36 private final String wifiSSID = "\"TP-LINK_585034\""; 37 /** 指定热点名称 **/ 38 private final String wifiName = "TP-LINK_585034"; 39 /** WIFI管理器 **/ 40 private WifiManager wifiManager = null; 41 /** WIFI状态监听广播 **/ 42 private BroadcastReceiver receiver; 43 /** 指定热点网络ID **/ 44 private int networkId; 45 46 /** 指定热点是否已连接 **/ 47 private boolean targetWifiEnable = false; 48 49 /** 打开按钮 **/ 50 private Button openLight; 51 /** 关闭按钮 **/ 52 private Button closeLight; 53 54 55 @Override 56 protected void onCreate(Bundle savedInstanceState) { 57 super.onCreate(savedInstanceState); 58 setContentView(R.layout.main); 59 initUI(); 60 } 61 62 private void initUI(){ 63 openLight = (Button) findViewById(R.id.openLight); 64 closeLight = (Button) findViewById(R.id.closeLight); 65 openLight.setOnClickListener(this); 66 closeLight.setOnClickListener(this); 67 } 68 69 70 @Override 71 protected void onResume() { 72 super.onResume(); 73 initWifiConnection(); 74 } 75 76 private void initWifiConnection(){ 77 wifiManager = (WifiManager) getSystemService(Service.WIFI_SERVICE); 78 WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 79 if (wifiSSID.equals(wifiInfo.getSSID()) ) { 80 targetWifiEnable = true; 81 return; 82 } 83 84 if (targetWifiIsConfig()) { 85 if (!wifiManager.isWifiEnabled()) { 86 if (wifiManager.setWifiEnabled(true)) { 87 registerWifiChangeBoradCast(); 88 }else{ 89 showLongToast("wifi开启失败,请手动打开!"); 90 Log.d(TAG, "WIFI开启失败"); 91 } 92 }else{ 93 if (targetWifiCanScan()) { 94 connectionTargetWifi(); 95 } 96 } 97 } 98 } 99 100 /** 101 * Description 指定WIFI是否可以被扫描到,即是否在可用范围内 102 * @return true表示可用,否则不可用 103 */ 104 private boolean targetWifiCanScan(){ 105 List<ScanResult> scanResultList = wifiManager.getScanResults(); 106 if (scanResultList != null && scanResultList.size() > 0) { 107 for (int i = 0; i < scanResultList.size(); i++) { 108 ScanResult scanResult = scanResultList.get(i); 109 110 StringBuffer str = new StringBuffer() 111 .append("SSID: " + scanResult.SSID).append("\n") 112 .append("BSSID: " + scanResult.BSSID).append("\n") 113 .append("capabilities: " + scanResult.capabilities).append("\n") 114 .append("level: " + scanResult.level).append("\n") 115 .append("frequency: " + scanResult.frequency); 116 Log.i(TAG, str.toString()); 117 118 if (scanResult.SSID.equals(wifiName)) { 119 return true; 120 } 121 } 122 } 123 showLongToast("指定wifi热点暂不可用,稍后可能无法操作照明设备!"); 124 return false; 125 } 126 127 /** 128 * Description 指定热点是否已配置(注册) 129 * @return true表示已注册,否则未注册 130 */ 131 private boolean targetWifiIsConfig(){ 132 List<WifiConfiguration> wifiConfigurationList = wifiManager.getConfiguredNetworks(); 133 for (int i = 0; i < wifiConfigurationList.size(); i++) { 134 WifiConfiguration wifiConfiguration = wifiConfigurationList.get(i); 135 136 // StringBuffer str = new StringBuffer() 137 // .append("SSID: " + wifiConfiguration.SSID).append("\n") 138 // .append("status: " + wifiConfiguration.status).append("\n") 139 // .append("networkId: " + wifiConfiguration.networkId).append("\n") 140 // .append("priority: " + wifiConfiguration.priority).append("\n") 141 // .append("wepTxKeyIndex: " + wifiConfiguration.wepTxKeyIndex); 142 // Log.i(TAG, str); 143 144 if (wifiConfiguration.SSID.equals(wifiSSID)) { 145 networkId = wifiConfiguration.networkId; 146 return true; 147 } 148 } 149 showLongToast("指定wifi热点未注册,请在wifi管理中先注册!"); 150 return false; 151 } 152 153 /** 154 * Description 连接指定热点 155 * @return 156 */ 157 private boolean connectionTargetWifi(){ 158 if (wifiManager.enableNetwork(networkId, true)) { 159 targetWifiEnable = true; 160 Log.i(TAG, "热点连接成功"); 161 return true; 162 }else{ 163 showLongToast("指定wifi热点连接失败,请手动连接!"); 164 Log.d(TAG, "热点连接失败"); 165 return false; 166 } 167 } 168 169 /** 170 * Description 注册WIFI状态改变监听广播 171 */ 172 private void registerWifiChangeBoradCast(){ 173 receiver = new BroadcastReceiver() { 174 175 @Override 176 public void onReceive(Context context, Intent intent) { 177 // WIFI可用时连接到指定热点 178 System.out.println(wifiManager.getWifiState()); 179 if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) { 180 Log.i(TAG, "WIFI成功开启"); 181 unregisterWifiChangeReceiver(); 182 handler.sendEmptyMessageDelayed(0, 10 * 1000); 183 } 184 } 185 }; 186 187 IntentFilter filter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION); 188 String broadcastPermission = permission.ACCESS_WIFI_STATE; 189 registerReceiver(receiver, filter, broadcastPermission, new Handler(){ 190 @Override 191 public void handleMessage(Message msg) { 192 super.handleMessage(msg); 193 } 194 }); 195 } 196 197 /** 198 * Description 注销WIFI状态改变监听广播 199 */ 200 private void unregisterWifiChangeReceiver(){ 201 if (receiver != null) { 202 unregisterReceiver(receiver); 203 } 204 } 205 206 /** 207 * Description 显示短时长显示的Toast 208 * @param text 209 */ 210 @SuppressWarnings("unused") 211 private void showShortToast(String text){ 212 Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); 213 } 214 215 /** 216 * Description 显示久时长显示的Toast 217 * @param text 218 */ 219 private void showLongToast(String text){ 220 if (text != null && !"".equals(text)) { 221 Toast.makeText(this, text, Toast.LENGTH_LONG).show(); 222 } 223 } 224 225 @Override 226 public void onClick(View v) { 227 switch (v.getId()) { 228 229 case R.id.openLight: 230 if (targetWifiEnable) { 231 showLongToast(HttpHelper.sendCommandToServer("A1")); 232 }else{ 233 initWifiConnection(); 234 } 235 break; 236 237 case R.id.closeLight: 238 if (targetWifiEnable) { 239 showLongToast(HttpHelper.sendCommandToServer("B1")); 240 }else{ 241 initWifiConnection(); 242 } 243 break; 244 245 default: 246 break; 247 } 248 } 249 250 private Handler handler = new Handler(){ 251 public void handleMessage(Message msg) { 252 if (targetWifiCanScan()) { 253 connectionTargetWifi(); 254 } 255 } 256 }; 257 258 }
布局文件:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent" 5 android:orientation="vertical" 6 android:gravity="center_horizontal" 7 android:padding="20dp"> 8 9 <TextView android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 android:text="下面两个按钮可以控制序号为1的设备,指令分别为A1和B1."> 12 </TextView> 13 14 <Button android:id="@+id/openLight" 15 android:layout_width="wrap_content" 16 android:layout_height="wrap_content" 17 android:layout_marginTop="50dp" 18 android:text="打开设备"> 19 </Button> 20 21 <Button android:id="@+id/closeLight" 22 android:layout_width="wrap_content" 23 android:layout_height="wrap_content" 24 android:layout_marginTop="20dp" 25 android:text="关闭设备"> 26 </Button> 27 28 </LinearLayout>
mainfest配置文件:
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.shineEye.www" 4 android:versionCode="1" 5 android:versionName="1.0" > 6 7 <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="7"/> 8 9 10 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 11 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> 12 <uses-permission android:name="android.permission.INTERNET"/> 13 14 15 <application 16 android:icon="@drawable/ic_launcher" 17 android:label="@string/app_name" 18 android:description="@string/appDescription"> 19 20 <activity 21 android:name=".WifiAutoConnection" 22 android:label="@string/app_name" 23 android:theme="@android:style/Theme.Light.NoTitleBar" > 24 <intent-filter> 25 <action android:name="android.intent.action.MAIN" /> 26 <category android:name="android.intent.category.LAUNCHER" /> 27 </intent-filter> 28 </activity> 29 30 31 </application> 32 33 </manifest>
csdn资源下载地址审核过后即贴上!