相信做网络监听的同学会发现,网络变化时,广播通知会发送多次,至于为什么,自行查阅资料。但多次广播对我们处理业务逻辑很是恼人,其实我们只需要做小小调整就可以避免这种问题
如下代码,记得注释中delay的地方,最好在自己的代码中控制下,以免网络还未真正建立起来,5秒足够。
转自:http://www.eoeandroid.com/forum.php?mod=viewthread&tid=193562
如下代码,记得注释中delay的地方,最好在自己的代码中控制下,以免网络还未真正建立起来,5秒足够。
01 | /** |
02 | *
|
03 | */ |
04 |
05 | package com.ckt.vas.hhl.receiver; |
06 |
07 | import org.slf4j.Logger; |
08 | import org.slf4j.LoggerFactory; |
09 |
10 | import android.content.BroadcastReceiver; |
11 | import android.content.Context; |
12 | import android.content.Intent; |
13 | import android.net.ConnectivityManager; |
14 | import android.net.NetworkInfo; |
15 |
16 | /** |
17 | * @author Gauss |
18 | */ |
19 | public class
NetConnectionReceiver extends
BroadcastReceiver { |
20 | private
final Logger log = LoggerFactory.getLogger(NetConnectionReceiver.class); |
21 |
22 | private
static int
lastType = -1; |
23 |
24 | @Override |
25 | public
void onReceive(Context context, Intent arg1) { |
26 | // log.debug("网络状态改变"); |
27 | String action = arg1.getAction(); |
28 | log.debug("网络状态改变 action="
+ action + " lastType="
+ lastType); |
29 | // 获得网络连接服务 |
30 | ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); |
31 |
32 | NetworkInfo info = connManager.getActiveNetworkInfo(); |
33 |
34 | if
(info == null
|| !connManager.getBackgroundDataSetting()) { |
35 | log.info("您的网络连接已中断"); |
36 | }
else { |
37 | int
netType = info.getType(); |
38 | if
(netType != lastType) { |
39 | if
(info.isConnected()) { |
40 |
//delay 5seconds |
41 |
log.warn("new connection was create.........type:"
+ info.getTypeName() + " status" |
42 | + info.getDetailedState()); |
43 | }
else { |
44 |
//delay 5seconds |
45 |
log.warn("the connection was broken...........type:"
+ info.getTypeName() + " status" |
46 | + info.getDetailedState()); |
47 | } |
48 | lastType = netType; |
49 | } |
50 |
51 | } |
52 | } |
53 |
54 | } |
本文介绍了一种在Android中过滤重复网络变更广播的方法,通过记录上一次网络类型并在网络变化时进行比对,确保只有在网络真正发生变化时才触发业务逻辑。
4877

被折叠的 条评论
为什么被折叠?



