在Android中检查互联网连接的最佳方法是什么?

Saj*_*our 0 android

我正在使用这些代码AsyncTask检查Internet连接:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnected()) {
                try {
                    URL url = new URL("http://www.google.com");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(3000);
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) {
                        return true;
                    }
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            else {
    //toast show
            }
Run Code Online (Sandbox Code Playgroud)

此代码不适用于大多数华为型号和三星Galaxy Note 3等设备.

此外,如果用户与GPRS,EDGE,3G,4G等数据进行互联网连接...

在所有设备和所有类型的连接上检查互联网连接以支持的最佳代码是什么?

S.M*_*ian 5

你可以使用这个类:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

   private Context _context;

   public ConnectionDetector(Context context){
       this._context = context;
   }

   public boolean isConnectingToInternet(){
       ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
         if (connectivity != null)
         {
             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;
   }

}
Run Code Online (Sandbox Code Playgroud)

现在,在你的课堂上:

ConnectionDetector  con = new ConnectionDetector ();

if(con.isConnectingToInternet()){
.
.
.
}
Run Code Online (Sandbox Code Playgroud)

在你的manifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Run Code Online (Sandbox Code Playgroud)