isNetworkReachable

  • Antworten:0
Mac Systems
  • Forum-Beiträge: 1.727

24.07.2010, 17:15:20 via Website

Hier eine Methode die feststellt ob der Netzwerk erreichbar ist. Ebenfalls kann angegeben werden ob im falle von Roaming dies als erreichbar angesehen wird.
Am einfachsten ist das in eine Util Klasse auszulagern und bei bedarf zu benutzen.





1private static final String LOG_TAG = DieKlasse.class.getSimpleName();
2
3
4 /**
5 * Returns <code>true</code> when Network is reachable and connected.
6 *
7 * @param _context
8 * @param useRoaming
9 * @return
10 */
11 public static boolean isNetworkReachable(final Context _context,final boolean _useRoaming)
12 {
13 boolean isNetworkReachable = false;
14 final ConnectivityManager systemService = (ConnectivityManager) _context
15 .getSystemService(Context.CONNECTIVITY_SERVICE);
16
17 /**
18 * Avoid NullPointerException when offline
19 */
20 if (systemService.getActiveNetworkInfo() == null)
21 {
22 Log.i(LOG_TAG, "Network not reachable!");
23 return false;
24 }
25
26 final NetworkInfo[] infos = systemService.getAllNetworkInfo();
27 boolean userWantIOWhileRoaming = useRoaming;
28 for (final NetworkInfo info : infos)
29 {
30 if (info != null)
31 {
32 if (info.isConnectedOrConnecting())
33 {
34 final State networkState = info.getState();
35 final boolean isRoamingNow = info.isRoaming();
36 if (State.CONNECTED == networkState || State.CONNECTING == networkState)
37 {
38 //if (Logging.isEnabled)
39 {
40 Log.i(LOG_TAG, "Using: ");
41 Log.i(LOG_TAG, "NetworkInfo.extraInfo : " + info.getExtraInfo());
42 Log.i(LOG_TAG, "NetworkInfo.reason : " + info.getReason());
43 Log.i(LOG_TAG, "NetworkInfo.subtypeName : " + info.getSubtypeName());
44 Log.i(LOG_TAG, "NetworkInfo.state : " + info.getState());
45 Log.i(LOG_TAG, "NetworkInfo.detailedState : " + info.getDetailedState());
46 Log.i(LOG_TAG, "NetworkInfo.isAvailable : " + info.isAvailable());
47 Log.i(LOG_TAG, "NetworkInfo.isConnected : " + info.isConnected());
48 Log.i(LOG_TAG, "NetworkInfo.isConnectedOrConnecting : " + info.isConnectedOrConnecting());
49 Log.i(LOG_TAG, "NetworkInfo.isFailover : " + info.isFailover());
50 Log.i(LOG_TAG, "NetworkInfo.isRoaming : " + info.isRoaming());
51 }
52 if (userWantIOWhileRoaming)
53 {
54 isNetworkReachable = true;
55 break;
56 }
57 else
58 {
59 isNetworkReachable = isRoamingNow ? false : true;
60 break;
61 }
62 }
63 }
64 }
65 }
66 return isNetworkReachable;
67
68 }
hth,
Mac

Windmate HD, See you @ IO 14 , Worked on Wundercar, Glass V3, LG G Watch, Moto 360, Android TV

Antworten