Saturday, 6 April 2013

Android Network How to make sure the network is available?


This function will return true if the network is available, false if it is not (airplane mode, out of reach, etc.). IMPORTANT : Don't forget to add [HTML_REMOVED] in your manifest, or the line NetworkInfo[] info = connectivity.getAllNetworkInfo(); will crash ! 


      public boolean isNetworkAvailable() {
                   Context context = getApplicationContext();
                   ConnectivityManager connectivity = (ConnectivityManager)
                   context.getSystemService(Context.CONNECTIVITY_SERVICE);

                   if (connectivity == null) {
                        boitealerte(this.getString(R.string.alert),"getSystemService rend null");
                   } else {
                               NetworkInfo[] info = connectivity.getAllNetworkInfo();
                               if (info != null) {
                                                 for (int i = 0; i < info.length; i++)
                                                {
                                                              if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                                                              return true;
                                                               }
                                                }
                               }
               }
         return false;
        }




No comments:

Post a Comment

Disqus for Android