收听网络状态广播

 1 package com.jingle.networkbroadcast.receiver;

 2 

 3 import com.jingle.networkbroadcast.util.LogUtil;

 4 

 5 import android.content.BroadcastReceiver;

 6 import android.content.Context;

 7 import android.content.Intent;

 8 import android.net.ConnectivityManager;

 9 import android.net.NetworkInfo;

10 import android.os.Bundle;

11 

12 public class NetworkStateReceiver extends BroadcastReceiver {

13 

14     @Override

15     public void onReceive(Context context, Intent intent) {

16         // TODO Auto-generated method stub

17         Bundle bundle = intent.getExtras();

18         String content;

19         //打印传进来的bundle信息

20         for (String key : bundle.keySet()) {

21             if ((content = bundle.getString(key)) != null) {

22                 LogUtil.getDebugLog("key: " + key + " content: " + content);

23                 LogUtil.getDevider();

24             }

25         }

26         LogUtil.getInfoLog("network state changed");

27         if (!isNetworkAvailable(context)) {

28             LogUtil.getInfoLog("网络失去连接");

29         }

30 

31     }

32 

33     public static boolean isNetworkAvailable(Context context) {

34         ConnectivityManager connMng = (ConnectivityManager) context

35                 .getSystemService(Context.CONNECTIVITY_SERVICE);

36         NetworkInfo infos[] = connMng.getAllNetworkInfo();

37         if (infos != null) {

38             for (NetworkInfo info : infos) {

39                 //只要networkinfo中有状态为connected就返回true,否则返回false

40                 if (info.getState() == NetworkInfo.State.CONNECTED) {

41                     return true;

42                 }

43             }

44         }

45         return false;

46     }

47 

48 }

 

你可能感兴趣的:(网络)