博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【移动开发】Android中WIFI开发总结(二)
阅读量:5457 次
发布时间:2019-06-15

本文共 23649 字,大约阅读时间需要 78 分钟。

搞了好几天终于有点眉目了,这里接着总结一下Android中WiFi的使用,在前面()我们已经简单了解了Wifi实际操作中所用到的几个主要类,今天就剖析一个WIFI搜索、创建、关闭、连接及一些简单的动画的综合案例。

 

首先,我们还是看一下我们项目的框架

MainActivity类:(处理wifi消息,加载UI)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/**
 
* 主界面
 
* @author ZHF
 
*
 
*/
public 
class 
MainActivity 
extends 
Activity 
implements 
EventHandler{
    
//消息事件
    
public 
static 
final 
int 
m_nWifiSearchTimeOut = 
0
;
// 搜索超时
    
public 
static 
final 
int 
m_nWTScanResult = 
1
;
// 搜索到wifi返回结果
    
public 
static 
final 
int 
m_nWTConnectResult = 
2
;
// 连接上wifi热点
    
public 
static 
final 
int 
m_nCreateAPResult = 
3
;
// 创建热点结果
    
public 
static 
final 
int 
m_nUserResult = 
4
;
// 用户上线人数更新命令(待定)
    
public 
static 
final 
int 
m_nWTConnected = 
5
;
// 点击连接后断开wifi,3.5秒后刷新adapter
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
//一些常量
    
public 
static 
final 
String PACKAGE_NAME = 
"com.zhf.wifidemo.wifi"
;  
//应用包名
    
public 
static 
final 
String FIRST_OPEN_KEY = 
"version"
;  
//版本号信息
    
public 
static 
final 
String WIFI_AP_HEADER = 
"zhf_"
;
    
public 
static 
final 
String WIFI_AP_PASSWORD =
"zhf12345"
;
    
//wifi操作事件(枚举)-->方便弹出对话框处理事件
    
private 
int 
wFOperateEnum = WFOperateEnum.NOTHING;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
//三个重要的类
    
public 
WFSearchProcess m_wtSearchProcess; 
//WiFi搜索进度条线程
    
public 
WifiAdmin m_wiFiAdmin; 
//Wifi管理类
    
public 
CreateAPProcess m_createAPProcess; 
//创建Wifi热点线程
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
//相关控件
    
private 
WFSearchAnimationFrameLayout m_FrameLWTSearchAnimation;  
//自定义雷达动画布局
    
private 
GifView m_gifRadar;  
//wifi信号动画布局
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                                                                                              
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
private 
LinearLayout m_linearLCreateAP; 
//创建热点View
    
private 
ProgressBar m_progBarCreatingAP; 
//创建热点进度条
    
private 
TextView m_textVPromptAP; 
//创建热点进度条文字
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
private 
Button m_btnBack; 
//左上角返回按钮
    
private 
Button m_btnSearchWF; 
//右上角wifi搜索按钮
    
private 
Button m_btnCreateWF; 
//创建wifi热点
    
private 
ListView m_listVWT; 
//显示信息
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
private 
LinearLayout m_LinearLDialog; 
//提醒对话框
    
private 
TextView m_textVContentDialog;  
//对话框文本内容
    
private 
Button m_btnConfirmDialog, m_btnCancelDialog; 
//提醒对话框上的按钮
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
private 
TextView m_textVWTPrompt; 
//中间文字提示
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
private 
boolean 
m_isFirstOpen = 
true
;  
//标记是否是第一次打开
    
ArrayList<ScanResult> m_listWifi = 
new 
ArrayList();
//检测到热点信息列表
    
private 
WTAdapter m_wTAdapter; 
//网络列表适配器
    
public 
Handler mHandler = 
new 
Handler() {
        
public 
void 
handleMessage(android.os.Message msg) {
            
switch 
(msg.what) {
            
case 
m_nWifiSearchTimeOut: 
// 搜索超时
                
m_wtSearchProcess.stop();
                
m_FrameLWTSearchAnimation.stopAnimation();
                
m_listWifi.clear();  
//网络列表
                
//设置控件
                
m_textVWTPrompt.setVisibility(View.VISIBLE);
                
m_textVWTPrompt.setText(
"需要重新搜索,点右上角重新搜索或创建新的热点..."
);
                
break
;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
            
case 
m_nWTScanResult:  
//扫描到结果
                
m_listWifi.clear();
                
if
(m_wiFiAdmin.mWifiManager.getScanResults() != 
null
) {
                    
for 
(
int 
i = 
0
; i < m_wiFiAdmin.mWifiManager.getScanResults().size(); i++) {
                        
ScanResult scanResult = m_wiFiAdmin.mWifiManager.getScanResults().get(i);
                        
//和指定连接热点比较,将其他的过滤掉!
                        
if
(scanResult.SSID.startsWith(WIFI_AP_HEADER)) {
                            
m_listWifi.add(scanResult);
                        
}
                    
}
                    
if
(m_listWifi.size() > 
0
) {
                        
m_wtSearchProcess.stop();
                        
m_FrameLWTSearchAnimation.stopAnimation();
                        
m_textVWTPrompt.setVisibility(View.GONE);
                        
//更新列表,显示出搜索到的热点
                        
m_wTAdapter.setData(m_listWifi);
                        
m_wTAdapter.notifyDataSetChanged();
                    
}
                
}
                
break
;
            
case 
m_nWTConnectResult:  
//连接结果
                
m_wTAdapter.notifyDataSetChanged(); 
//刷新适配器数据
                
break
;
            
case 
m_nCreateAPResult:  
//创建wifi热点结果
                
m_createAPProcess.stop();
                
m_progBarCreatingAP.setVisibility(View.GONE); 
//旋转进度条
                
if
((m_wiFiAdmin.getWifiApState() == 
3 
|| m_wiFiAdmin.getWifiApState() == 
13
) && (m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER))) {
                    
//设置控件
                    
m_textVWTPrompt.setVisibility(View.GONE);
                    
m_linearLCreateAP.setVisibility(View.VISIBLE);
                    
m_btnCreateWF.setVisibility(View.VISIBLE);
                    
m_gifRadar.setVisibility(View.VISIBLE);
                    
m_btnCreateWF.setBackgroundResource(R.drawable.x_ap_close);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
                    
m_textVPromptAP.setText(
"热点创建成功!"
"\n热点名:"
+ m_wiFiAdmin.getApSSID()+ 
"\n连接密码:zhf12345"
);
                
else 
{
                    
m_btnCreateWF.setVisibility(View.VISIBLE);
                    
m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create);
                    
m_textVPromptAP.setText(
"热点创建失败,您可以重新创建或者搜索其它热点"
);
                
}
                
break
;
            
case 
m_nUserResult :
                
//更新用户上线人数
                
break
;
            
case 
m_nWTConnected:  
//点击连接后断开wifi,3.5s后刷新
                
m_wTAdapter.notifyDataSetChanged();
                
break
;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
            
}
        
};
    
};
    
@Override
    
public 
void 
onCreate(Bundle savedInstanceState) {
        
super
.onCreate(savedInstanceState);
        
setContentView(R.layout.wt_main);
        
//搜索Wifi
        
m_wtSearchProcess = 
new 
WFSearchProcess(
this
);
        
//创建Wifi热点
        
m_createAPProcess = 
new 
CreateAPProcess(
this
);
        
//wifi管理类
        
m_wiFiAdmin  = WifiAdmin.getInstance(
this
);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        
//初始化View
        
initView();
    
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
/**初始化View**/
    
private 
void 
initView() {
        
// 监听广播
        
WIFIBroadcast.ehList.add(
this
);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        
/******************************实例化布局**************************************/
        
m_linearLCreateAP = (LinearLayout) findViewById(R.id.create_ap_llayout_wt_main);  
//创建热点View
        
m_progBarCreatingAP = (ProgressBar) findViewById(R.id.creating_progressBar_wt_main);  
//创建热点进度条
        
m_textVPromptAP = (TextView) findViewById(R.id.prompt_ap_text_wt_main); 
//创建热点进度条文字
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        
m_FrameLWTSearchAnimation = ((WFSearchAnimationFrameLayout) findViewById(R.id.search_animation_wt_main));
// 搜索时的动画
        
m_listVWT = ((ListView) findViewById(R.id.wt_list_wt_main));
// 搜索到的热点listView
        
//注意此处
        
m_wTAdapter = 
new 
WTAdapter(
this
, m_listWifi);
        
m_listVWT.setAdapter(m_wTAdapter);
        
m_textVWTPrompt = (TextView) findViewById(R.id.wt_prompt_wt_main); 
//中间提醒文字
        
m_gifRadar = (GifView) findViewById(R.id.radar_gif_wt_main); 
//gif动画
        
//提醒对话框布局
        
m_LinearLDialog = (LinearLayout) findViewById(R.id.dialog_layout_wt_main);
        
m_textVContentDialog = (TextView) findViewById(R.id.content_text_wtdialog);
        
m_btnConfirmDialog = (Button) findViewById(R.id.confirm_btn_wtdialog);
        
m_btnCancelDialog = (Button) findViewById(R.id.cancel_btn_wtdialog);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        
//左上角返回键
        
m_btnBack = (Button) findViewById(R.id.back_btn_wt_main);
        
m_btnBack.setOnClickListener(
new 
OnClickListener() {
            
@Override
            
public 
void 
onClick(View v) {
                
onBackPressed(); 
//相当于调用系统返回键,结束当前Activity
            
}
        
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        
//右上角搜索热点按钮
        
m_btnSearchWF = (Button) findViewById(R.id.search_btn_wt_main);
        
m_btnSearchWF.setOnClickListener(
new 
OnClickListener() {
            
@Override
            
public 
void 
onClick(View v) {
                
if
(!m_wtSearchProcess.running) { 
//搜索线程没有开启
                    
//1.当前热点或wifi连接着    WIFI_STATE_ENABLED 3 //WIFI_AP_STATE_ENABLED  13
                    
if
(m_wiFiAdmin.getWifiApState() == 
3 
|| m_wiFiAdmin.getWifiApState() == 
13
) {
                        
wFOperateEnum = WFOperateEnum.SEARCH; 
//搜索wifi事件
                        
m_LinearLDialog.setVisibility(View.VISIBLE); 
///wifi提示对话框显示
                        
m_textVContentDialog.setText(
"是否关闭当前热点去搜索其他热点?"
);
                        
return
;  
//跳出此方法,交由对话框来处理事件
                    
}
                    
//2.当前没有热点或wifi连接着
                    
if
(!m_wiFiAdmin.mWifiManager.isWifiEnabled()) { 
//如果wifi没打开
                        
m_wiFiAdmin.OpenWifi();
                    
}
                    
m_textVWTPrompt.setVisibility(View.VISIBLE); 
//中间提示文字
                    
m_textVWTPrompt.setText(
"正在搜索附近的热点..."
);
                    
m_linearLCreateAP.setVisibility(View.GONE); 
//创建wifi热点布局消失
                    
m_gifRadar.setVisibility(View.GONE); 
//热点连接动画消失
                    
m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create); 
//更改按钮文字“创建”
                    
//开始搜索wifi
                    
m_wiFiAdmin.startScan();
                    
m_wtSearchProcess.start(); 
//开启搜索线程
                    
m_FrameLWTSearchAnimation.startAnimation(); 
//开启波纹动画
                
}
else 
{
//搜索线程开启着,再次点击按钮
                    
//重新启动
                    
m_wtSearchProcess.stop();
                    
m_wiFiAdmin.startScan();    
//开始搜索wifi
                    
m_wtSearchProcess.start();
                
}
            
}
        
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
        
//中间创建wifi热点按钮
        
m_btnCreateWF = (Button) findViewById(R.id.create_btn_wt_main);
        
m_btnCreateWF.setOnClickListener(
new 
OnClickListener() {
            
@Override
            
public 
void 
onClick(View v) {
                
if
(m_wiFiAdmin.getWifiApState() == 
4
) { 
// WIFI_STATE_UNKNOWN
                    
Toast.makeText(getApplicationContext(),
"您的设备不支持热点创建!"
, Toast.LENGTH_SHORT).show();
                    
return
;
                
}
                
if
(m_wiFiAdmin.mWifiManager.isWifiEnabled()) { 
//目前连着wifi
                    
wFOperateEnum = WFOperateEnum.CREATE;  
//wifi热点创建事件
                    
m_LinearLDialog.setVisibility(View.VISIBLE); 
//对话框可用
                    
m_textVContentDialog.setText(
"创建热点会关闭当前的WiFi,确认继续?"
);
                    
return
;
                
}
                
if
((m_wiFiAdmin.getWifiApState() == 
3 
|| m_wiFiAdmin.getWifiApState() == 
13
)
                        
&& (!m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER))) {
//目前连接着其他热点名
                    
wFOperateEnum = WFOperateEnum.CREATE;  
//wifi热点创建事件
                    
m_LinearLDialog.setVisibility(View.VISIBLE);
                    
m_textVContentDialog.setText(
"系统热点被占用,点确定开启热点以传输文件!"
);
                    
return
;
                
}
                
if 
(((m_wiFiAdmin.getWifiApState() == 
3
) || (m_wiFiAdmin.getWifiApState() == 
13
))
                        
&& (m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER))) {
//目前连接着自己指定的Wifi热点
                    
wFOperateEnum = WFOperateEnum.CLOSE;  
//wifi热点关闭事件
                    
m_LinearLDialog.setVisibility(View.VISIBLE);
                    
m_textVContentDialog.setText(
"关闭热点会中断当前传输,您确定这么做?"
);
                    
return
;
                
}
                
if
(m_wtSearchProcess.running) {
                    
m_wtSearchProcess.stop(); 
//停止线程
                    
m_FrameLWTSearchAnimation.stopAnimation(); 
//停止动画
                
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
                
/******************点击创建热点时没有连接wifi或热点的情况*****************************/
                
//关闭Wifi
                
m_wiFiAdmin.closeWifi();
                
//创建热点(名字,密码,加密类型,wifi/ap类型)
                
m_wiFiAdmin.createWifiAP(m_wiFiAdmin.createWifiInfo(WIFI_AP_HEADER + getLocalHostName(), WIFI_AP_PASSWORD, 
3
"ap"
), 
true
);
                
m_createAPProcess.start(); 
//开启创建热点线程
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
                
//将wifi信息列表设置到listview中
                
m_listWifi.clear();
                
m_wTAdapter.setData(m_listWifi);
                
m_wTAdapter.notifyDataSetChanged();
                
//设置布局
                
m_linearLCreateAP.setVisibility(View.VISIBLE); 
//热点布局可用
                
m_progBarCreatingAP.setVisibility(View.VISIBLE);
                
m_textVPromptAP.setText(
"正在创建热点"
); 
//进度条文字
                
m_btnCreateWF.setVisibility(View.GONE); 
//点击一次不可再点
                
m_textVWTPrompt.setVisibility(View.GONE);
            
}
        
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
        
//对话框确认按钮
        
m_btnConfirmDialog.setOnClickListener(
new 
OnClickListener() {
            
@Override
            
public 
void 
onClick(View v) {
                
m_LinearLDialog.setVisibility(View.GONE); 
//让对话框布局消失
                
switch 
(wFOperateEnum) { 
//根据wifi操作事件
                
case 
WFOperateEnum.CLOSE:  
//关闭wifi热点
                    
//设置布局
                    
m_textVWTPrompt.setVisibility(View.VISIBLE);
                    
m_textVWTPrompt.setText(
"热点已关闭!可以进行其他操作了!"
); 
//中间提醒文字
                    
m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create); 
//按钮文字改回“创建”
                    
m_gifRadar.setVisibility(View.GONE); 
//热点动画停止
                    
m_linearLCreateAP.setVisibility(View.GONE); 
//下部创建热点布局不可用
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
                    
//关闭热点
                    
m_wiFiAdmin.createWifiAP(m_wiFiAdmin.createWifiInfo(m_wiFiAdmin.getApSSID(), 
"zhf123456"
3
"ap"
), 
false
);
                    
break
;
                
case 
WFOperateEnum.CREATE:  
//创建wifi热点
                    
if
(m_wtSearchProcess.running) {
                        
m_wtSearchProcess.stop();  
//搜索wifi线程停止
                        
m_FrameLWTSearchAnimation.stopAnimation(); 
//搜索wifi动画停止
                    
}
                    
//关闭wifi
                    
m_wiFiAdmin.closeWifi();
                    
//创建WiFi热点
                    
m_wiFiAdmin.createWifiAP(m_wiFiAdmin.createWifiInfo(WIFI_AP_HEADER + getLocalHostName(), WIFI_AP_PASSWORD, 
3
"ap"
),
true
);
                    
m_createAPProcess.start();
                    
//刷新listView布局
                    
m_listWifi.clear();
                    
m_wTAdapter.setData(m_listWifi);
                    
m_wTAdapter.notifyDataSetChanged();
                    
//设置布局
                    
m_linearLCreateAP.setVisibility(View.VISIBLE);
                    
m_progBarCreatingAP.setVisibility(View.VISIBLE); 
//旋转进度条
                    
m_btnCreateWF.setVisibility(View.GONE);
                    
m_textVWTPrompt.setVisibility(View.GONE);
                    
m_textVPromptAP.setText(
"正在创建热点..."
); 
//进度条文字
                    
break
;
                
case 
WFOperateEnum.SEARCH:  
//搜索可用热点
                    
//设置布局
                    
m_textVWTPrompt.setVisibility(View.VISIBLE);
                    
m_textVWTPrompt.setText(
"正在搜索附近的热点..."
);
                    
m_linearLCreateAP.setVisibility(View.GONE); 
//创建热点布局不可用
                    
m_btnCreateWF.setVisibility(View.VISIBLE);
                    
m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create); 
//按钮文字改回“创建”
                    
m_gifRadar.setVisibility(View.GONE); 
//热点动画停止
                    
m_linearLCreateAP.setVisibility(View.GONE); 
//下部创建热点布局不可用
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
                    
//搜索热点线程关闭
                    
if 
(m_createAPProcess.running)
                        
m_createAPProcess.stop();
                    
//关闭热点
                    
m_wiFiAdmin.createWifiAP(m_wiFiAdmin.createWifiInfo(m_wiFiAdmin.getApSSID(), WIFI_AP_PASSWORD, 
3
"ap"
),
false
);
                    
//打开wifi
                    
m_wiFiAdmin.OpenWifi();
                    
m_wtSearchProcess.start();
                    
m_FrameLWTSearchAnimation.startAnimation();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
                    
break
;
                
}
            
}
        
});
        
//对话框取消按钮事件
        
m_btnCancelDialog.setOnClickListener(
new 
OnClickListener() {
            
@Override
            
public 
void 
onClick(View v) {
                
//对话框布局消失
                
m_LinearLDialog.setVisibility(View.GONE);
            
}
        
});
    
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
/**Wifi是否连接**/
    
private 
boolean 
isWifiConnect() {
        
boolean 
isConnect = 
true
;
        
//用于网络连接状态的检测
        
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        
if
(!cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected())
            
isConnect = 
false
;
        
return 
isConnect;
    
}
    
/**获取wifi热点状态**/
    
public 
boolean 
getWifiApState() {
        
try 
{
            
WifiManager localWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            
Method m = localWifiManager.getClass().getMethod(
"getWifiApState"
new 
Class[
0
]);
            
int 
i = (Integer)(m.invoke(localWifiManager, 
new 
Object[
0
]));
            
return 
(
3 
== i) || (
13 
== i);  
//WIFI_STATE_ENABLED 3  //WIFI_AP_STATE_ENABLED  13
        
catch 
(Exception e) {
            
e.printStackTrace();
        
}
        
return 
false
;
    
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
/**获取手机信息**/
    
public 
String getLocalHostName() {
        
String str1 = Build.BRAND; 
//主板
        
String str2 = Build.MODEL;  
//机型
        
if 
(-
1 
== str2.toUpperCase().indexOf(str1.toUpperCase()))
            
str2 = str1 + 
"_" 
+ str2;
        
return 
str2;
    
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
private 
void 
init() {
        
//线程是否在运行
        
if
(
this
.m_wtSearchProcess.running || 
this
.m_createAPProcess.running) {
            
return
;
        
}
        
//没有连接上wifi或者是wifi热点
        
if
(!isWifiConnect() && !getWifiApState()) {
            
m_wiFiAdmin.OpenWifi();
            
m_wtSearchProcess.start(); 
//开启搜索wifi超时检测线程
            
m_wiFiAdmin.startScan(); 
//开启搜索wifi
            
//开启搜索动画
            
m_FrameLWTSearchAnimation.startAnimation();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
            
//设置控件
            
m_textVWTPrompt.setVisibility(View.VISIBLE);
            
m_textVWTPrompt.setText(
" 正在搜索附近的热点..."
);
            
m_linearLCreateAP.setVisibility(View.GONE);
            
m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create);
        
}
        
//连接上wifi
        
if
(isWifiConnect()) {
            
this
.m_wiFiAdmin.startScan();
            
this
.m_wtSearchProcess.start();
            
this
.m_FrameLWTSearchAnimation.startAnimation();
            
//设置控件
            
this
.m_textVWTPrompt.setVisibility(
0
);
            
this
.m_textVWTPrompt.setText(
"正在搜索附近的热点..."
);
            
this
.m_linearLCreateAP.setVisibility(View.GONE);
            
this
.m_btnCreateWF.setBackgroundResource(R.drawable.x_wt_create);
            
this
.m_gifRadar.setVisibility(View.GONE);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
            
m_listWifi.clear();
            
if
(m_wiFiAdmin.mWifiManager.getScanResults() != 
null
) {
                
for 
(
int 
i = 
0
; i < m_wiFiAdmin.mWifiManager.getScanResults().size(); i++) {
                    
//识别出自己自定连接的wifi
                    
if
(m_wiFiAdmin.mWifiManager.getScanResults().get(i).SSID.startsWith(WIFI_AP_HEADER)) {
                        
m_listWifi.add(m_wiFiAdmin.mWifiManager.getScanResults().get(i)); 
//将指定wifi添加进去
                    
}
                
}
                
m_wTAdapter.setData(m_listWifi); 
//将连接的信息添加到listView中
                
m_wTAdapter.notifyDataSetChanged();
            
}
            
//连接上wifi热点
            
if
(getWifiApState()){
                
if
(m_wiFiAdmin.getApSSID().startsWith(WIFI_AP_HEADER)) {
                    
//设置控件
                    
m_textVWTPrompt.setVisibility(View.GONE);
                    
m_linearLCreateAP.setVisibility(View.VISIBLE);
                    
m_progBarCreatingAP.setVisibility(View.GONE);
                    
m_btnCreateWF.setVisibility(View.VISIBLE);
                    
m_gifRadar.setVisibility(View.VISIBLE);
                    
m_btnCreateWF.setBackgroundResource(R.drawable.x_ap_close);
                    
m_textVPromptAP.setText(
"\n热点名:"
+ m_wiFiAdmin.getApSSID() + 
"\n连接密码:zhf12345"
);
                
}
            
}
        
}
    
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
@Override
    
protected 
void 
onDestroy() {
        
// TODO Auto-generated method stub
        
super
.onDestroy();
        
WIFIBroadcast.ehList.remove(
this
);
    
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
    
@Override
    
public 
void 
handleConnectChange() {
        
Message msg = mHandler.obtainMessage(m_nWTConnectResult);
        
mHandler.sendMessage(msg);
    
}
    
@Override
    
public 
void 
scanResultsAvaiable() {
        
Message msg = mHandler.obtainMessage(m_nWTScanResult);
        
mHandler.sendMessage(msg);
    
}
    
@Override
    
public 
void 
wifiStatusNotification() {
        
m_wiFiAdmin.mWifiManager.getWifiState(); 
//获取当前wifi状态
    
}
}

 

貌似有点长。。。简单说明一下:

   1.首先,初始化主界面(xml有些复杂,慢慢理一下就好了,不是什么大问题)接下来,处理三个重要的按钮事件:右上角的搜索wifi按钮、中间创建或关闭热点按钮、对话框中确定按钮。处理前两者事件时,需关注当前wifi状态,若为占用,需弹出提醒对话框来根据当前WiFi操作(WFOperateEnum类中定义好了)事件,来创建、关闭、搜索等具体事务。

   2.之所以定义广播接收者,是为了监听当wifi状态发生变化时,能够及时更新界面

 

广播接收者WIFIBroadcast类:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package 
com.zhf.wifidemo.broadcast;
import 
java.util.ArrayList;
import 
android.content.BroadcastReceiver;
import 
android.content.Context;
import 
android.content.Intent;
import 
android.net.wifi.WifiManager;
import 
android.util.Log;
/**
 
* 监听wifi热点变化
 
* @author ZHF
 
*
 
*/
public 
class 
WIFIBroadcast 
extends 
BroadcastReceiver{
    
public 
static 
ArrayList<EventHandler> ehList = 
new 
ArrayList<EventHandler>();
                                                                                                                                                                                                                                                                                                                                                 
    
@Override
    
public 
void 
onReceive(Context context, Intent intent) {
        
//搜索到wifi热点结果的广播:  "android.net.wifi.SCAN_RESULTS"
        
if
(intent.getAction().endsWith(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            
Log.i(
"WTScanResults---->扫描到了可用网络---->"
"android.net.wifi.SCAN_RESULTS"
);
            
//遍历通知各个监听接口
            
for
(
int 
i = 
0
; i < ehList.size(); i++) {
                
((EventHandler)ehList.get(i)).scanResultsAvaiable();
            
}
                                                                                                                                                                                                                                                                                                                                                         
        
//wifi打开或关闭状态变化   "android.net.wifi.WIFI_STATE_CHANGED"
        
}
else 
if
(intent.getAction().endsWith(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
            
Log.i(
"WTScanResults----->wifi状态变化--->"
"android.net.wifi.WIFI_STATE_CHANGED"
);
            
//这里不需要连接一个SSID(wifi名称)
            
for
(
int 
j = 
0
; j < ehList.size(); j++) {
                
((EventHandler)ehList.get(j)).wifiStatusNotification();
            
}
                                                                                                                                                                                                                                                                                                                                                         
        
//连接上一个SSID后发出的广播,(注:与android.net.wifi.WIFI_STATE_CHANGED的区别)
        
}
else 
if
(intent.getAction().endsWith(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            
Log.i(
"WTScanResults----->网络状态变化---->"
"android.net.wifi.STATE_CHANGE"
);
            
for
(
int 
m = 
0
; m < ehList.size(); m++) {
                
((EventHandler)ehList.get(m)).handleConnectChange();
            
}
        
}
    
}
    
/**
     
* 事件监听接口
     
* @author ZHF
     
*
     
*/
    
public 
static 
abstract 
interface 
EventHandler {
        
/**处理连接变化事件**/
        
public 
abstract 
void 
handleConnectChange();
        
/**扫描结果是有效事件**/
        
public 
abstract 
void 
scanResultsAvaiable();
        
/**wifi状态变化事件**/
        
public 
abstract 
void 
wifiStatusNotification();
    
}
                                                                                                                                                                                                                                                                                                                                                 
}

 

说明:监听系统wifi状态变化,内部定义了一个事件处理接口,当wifi状态发生变化时,让其实现类去发送消息更新界面。

 

CreateAPProcess类:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package 
com.zhf.wifidemo.ui;
import 
android.net.wifi.WifiManager;
import 
android.os.Message;
import 
com.zhf.wifidemo.wifi.MainActivity;
/**
 
* 创建Wifi热点
 
* @author ZHF
 
*
 
*/
public 
class 
CreateAPProcess 
implements 
Runnable{
                                                                                                                                                                                              
    
public 
MainActivity context;
                                                                                                                                                                                              
    
public 
boolean running = 
false
;
    
private 
long startTime = 0L;
    
private 
Thread thread = 
null
;
    
public 
CreateAPProcess(MainActivity context) {
        
super
();
        
this
.context = context;
    
}
    
@Override
    
public 
void 
run() {
        
while
(
true
) {
            
if
(!running)  
return
;
            
//WIFI_STATE_ENABLED 3
            
//WIFI_AP_STATE_ENABLED  13
            
if
((context.m_wiFiAdmin.getWifiApState() == WifiManager.WIFI_STATE_ENABLED)
                    
|| (context.m_wiFiAdmin.getWifiApState() == 
13
)
                    
|| (System.currentTimeMillis() - 
this
.startTime >= 30000L)){
                
//wifi可用 或 热点可用
                
Message msg = context.mHandler.obtainMessage(context.m_nCreateAPResult);
                
context.mHandler.sendMessage(msg);
            
}
            
try 
{
                
Thread.sleep(5L);
            
catch 
(Exception e) {
                
e.printStackTrace();
            
}
        
}
                                                                                                                                                                                                  
    
}
                                                                                                                                                                                              
    
public 
void 
start() {
        
try 
{
            
thread = 
new 
Thread(
this
);
            
running = 
true
;
            
startTime = System.currentTimeMillis();
            
thread.start(); 
//开启线程
        
catch 
(Exception e) {
            
e.printStackTrace();
        
}
    
}
                                                                                                                                                                                              
    
public 
void 
stop() {
        
try 
{
            
running = 
false
;
            
thread = 
null
;
            
startTime = 0L;
        
catch 
(Exception e) {
            
// TODO: handle exception
        
}
    
}
}

 

其他类文件具体看源码,当创建一个热点成功后,等待其他客户端搜索

上图:

 

154705667.png

 

WIFIAdapte类:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
 
* 网络列表适配器
 
* @author ZHF
 
*
 
*/
public 
class 
WTAdapter 
extends 
BaseAdapter {
    
private 
LayoutInflater mInflater;
    
private 
List<ScanResult> mList;  
//扫描到的网络结果列表
    
private 
MainActivity mContext;
    
public 
WTAdapter(MainActivity context, List<ScanResult> list) {
        
// TODO Auto-generated constructor stub
        
this
.mContext = context;
        
this
.mList = list;
        
this
.mInflater = LayoutInflater.from(context);
    
}
    
//新加的一个函数,用来更新数据
    
public 
void 
setData(List<ScanResult> list) {
        
this
.mList = list;
        
notifyDataSetChanged();
    
}
                                                                 
    
@Override
    
public 
int 
getCount() {
        
return 
mList.size();
    
}
    
@Override
    
public 
Object getItem(
int 
position) {
        
return 
mList.get(position);
    
}
    
@Override
    
public 
long 
getItemId(
int 
position) {
        
return 
position;
    
}
    
@Override
    
public 
View getView(
final 
int 
position, View convertView, ViewGroup parent) {
        
//获取点击向的扫描结果
        
final 
ScanResult localScanResult = mList.get(position);
        
//获取wifi类
//      final WifiAdmin wifiAdmin = WifiAdmin.getInstance(mContext);
        
final 
WifiAdmin wifiAdmin = mContext.m_wiFiAdmin;
        
final 
ViewHolder viewHolder;
        
if 
(convertView == 
null
) {
            
viewHolder = 
new 
ViewHolder();
            
convertView = mInflater.inflate(R.layout.wtitem, 
null
);
            
//加载布局模板控件
            
viewHolder.textVName = ((TextView) convertView.findViewById(R.id.name_text_wtitem));
            
viewHolder.textConnect = ((TextView) convertView.findViewById(R.id.connect_text_wtitem));
            
viewHolder.linearLConnectOk = ((LinearLayout) convertView.findViewById(R.id.connect_ok_layout_wtitem));
            
viewHolder.progressBConnecting = ((ProgressBar) convertView.findViewById(R.id.connecting_progressBar_wtitem));
            
convertView.setTag(viewHolder);
        
else 
{
            
viewHolder = (ViewHolder) convertView.getTag();
        
}
        
//点击连接处理事件
        
viewHolder.textConnect.setOnClickListener(
new 
OnClickListener() {
            
@Override
            
public 
void 
onClick(View v) {
                
//创建wifi网络
                
WifiConfiguration localWifiConfiguration = wifiAdmin.createWifiInfo(localScanResult.SSID, MainActivity.WIFI_AP_PASSWORD, 
3
,
"wt"
);
                
//添加到网络
                
wifiAdmin.addNetwork(localWifiConfiguration);
                
//"点击链接"消失,显示进度条,
                
viewHolder.textConnect.setVisibility(View.GONE);
                
viewHolder.progressBConnecting.setVisibility(View.VISIBLE);
                
viewHolder.linearLConnectOk.setVisibility(View.GONE);
                
//点击后3.5s发送消息
                
mContext.mHandler.sendEmptyMessageDelayed(mContext.m_nWTConnected, 3500L);
            
}
        
});
        
// 点击断开处理事件
        
viewHolder.linearLConnectOk.setOnClickListener(
new 
OnClickListener() {
            
@Override
            
public 
void 
onClick(View v) {
                
//断开指定wifi热点
                
wifiAdmin.disconnectWifi(wifiAdmin.getWifiInfo().getNetworkId());
                
//"断开连接"消失,进度条显示
                
viewHolder.textConnect.setVisibility(View.GONE);
                
viewHolder.progressBConnecting.setVisibility(View.VISIBLE);
                
viewHolder.linearLConnectOk.setVisibility(View.GONE);
                
//点击后3.5s发送消息
                
mContext.mHandler.sendEmptyMessageDelayed(mContext.m_nWTConnected, 3500L);
            
}
        
});
        
//初始化布局
        
viewHolder.textConnect.setVisibility(View.GONE);
        
viewHolder.progressBConnecting.setVisibility(View.GONE);
        
viewHolder.linearLConnectOk.setVisibility(View.GONE);
        
viewHolder.textVName.setText(localScanResult.SSID); 
//显示热点名称
                                                                     
        
// 正连接的wifi信息
        
WifiInfo localWifiInfo = wifiAdmin.getWifiInfo();
        
if 
(localWifiInfo != 
null
) {
            
try 
{
//正在连接
                
if 
((localWifiInfo.getSSID() != 
null
)&& (localWifiInfo.getSSID().equals(localScanResult.SSID))) {
                    
viewHolder.linearLConnectOk.setVisibility(View.VISIBLE);
                    
return 
convertView;
                
}
            
catch 
(NullPointerException e) {
                
e.printStackTrace();
                
return 
convertView;
            
}
            
viewHolder.textConnect.setVisibility(View.VISIBLE);
        
}
        
return 
convertView;
    
}
    
public 
final 
class 
ViewHolder {
        
public 
LinearLayout linearLConnectOk;
        
public 
ProgressBar progressBConnecting;
        
public 
TextView textConnect;
        
public 
TextView textVName;
    
}
}

 

   点击连接,实现客户连接,此时他们将处于同一网段内,接下来就可以自己实现传输数据,操控等一系列操作了。 在下一篇中我会继实现一个基于wif热点的多人聊天室,希望能帮助到大家!

 

源码:

转载于:https://www.cnblogs.com/dongweiq/p/4742140.html

你可能感兴趣的文章
数据劫持,订阅者模式,双向绑定
查看>>
关于使用别人方法的效率问题
查看>>
svn第一篇----入门指南
查看>>
按钮 是否可用 的控制
查看>>
隐马尔科夫模型(HMM) 举例讲解
查看>>
JedisUtils工具类模板
查看>>
NOIP2011题解
查看>>
[Python] 文科生零基础学编程系列二——数据类型、变量、常量的基础概念
查看>>
[唐胡璐]QTP技巧 - ALT+G快捷键
查看>>
P2746 [USACO5.3]校园网Network of Schools
查看>>
java中使用队列:java.util.Queue
查看>>
随笔记录(2019.7.16)
查看>>
clang代替gcc
查看>>
【Shell】基础正则表示法及grep用法
查看>>
Demo整合
查看>>
Android基础——JSON数据的全方位解析
查看>>
Derek解读Bytom源码-持久化存储LevelDB
查看>>
规范化-数据库设计原则
查看>>
BASIC-24_蓝桥杯_龟兔赛跑预测
查看>>
C# 中使用Linq和Lambda表达式对List<T>进行排序
查看>>