首页 文章

如何检查Android手机没有连接到互联网?

提问于
浏览
0

我正在android中开发一个从数据库中获取数据的应用程序 . 我已经开发了代码来查找WIFI或Mobile数据是打开还是关闭,如下所示:

protected boolean isNetworkAvailable()
{
    boolean connection=true;
    ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] activeNetworkInfo=connectivityManager.getAllNetworkInfo();
    for(NetworkInfo ni:activeNetworkInfo)
    {
        if(ni.getTypeName().equalsIgnoreCase("WIFI"))
            if(ni.isConnected())    
                haveConnectedWifi=true;
        if(ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if(ni.isConnected())
                haveConnectedMobile=true;

    }
    if(haveConnectedWifi==false && haveConnectedMobile==false)
    {

    connection=false;
    }
        return connection;

    }

现在假设我的WIFI或移动数据网络已打开,但我根本没有连接到互联网(WIFI没有连接到任何接入点) . 如何在Android中显示这个?

谢谢,

7 回答

  • 0

    你可以简单地使用这个:

    public boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        // if no network is available networkInfo will be null
        // otherwise check if we are connected
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
    
  • 1

    这个课程非常完整:

    public class ConnexionDetector extends BroadcastReceiver {
        /**
         * ATTRIBUTES
         */
        private Context         _context;
        private boolean         _noConnectivity;
        private String          _reason;
        private boolean         _isFailover;
        private static boolean  _isConnected        = false;
        private static boolean  _isConnectivityGood = true;
    
        public ConnexionDetector(Context context) {
    
            this._context = context;
        }
    
    public void registerReceivers() {
    
        _context.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
    
    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;
    }
    
    public static NetworkInfo getNetworkInfo(Context context) {
    
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }
    
    public static boolean isConnected(Context context) {
    
        NetworkInfo info = getNetworkInfo(context);
        return (info != null && info.isConnected());
    }
    
    public static boolean isConnectedWifi(Context context) {
    
        NetworkInfo info = getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
    }
    
    public static boolean isConnectedMobile(Context context) {
    
        NetworkInfo info = getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
    }
    
    public static boolean isConnectedFast(Context context) {
    
        NetworkInfo info = getNetworkInfo(context);
        return (info != null && info.isConnected() && isConnectionFast(info.getType(), info.getSubtype()));
    }
    
    private static boolean isConnectionFast(int type, int subType) {
    
        if (type == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        else if (type == ConnectivityManager.TYPE_MOBILE) {
            switch (subType) {
                case TelephonyManager.NETWORK_TYPE_1xRTT:
                    return false; // ~ 50-100 kbps
                case TelephonyManager.NETWORK_TYPE_CDMA:
                    return false; // ~ 14-64 kbps
                case TelephonyManager.NETWORK_TYPE_EDGE:
                    return false; // ~ 50-100 kbps
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    return true; // ~ 400-1000 kbps
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    return true; // ~ 600-1400 kbps
                case TelephonyManager.NETWORK_TYPE_GPRS:
                    return false; // ~ 100 kbps
                case TelephonyManager.NETWORK_TYPE_HSDPA:
                    return true; // ~ 2-14 Mbps
                case TelephonyManager.NETWORK_TYPE_HSPA:
                    return true; // ~ 700-1700 kbps
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                    return true; // ~ 1-23 Mbps
                case TelephonyManager.NETWORK_TYPE_UMTS:
                    return true; // ~ 400-7000 kbps
                case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                default:
                    return false;
            }
        }
        else {
            return false;
        }
    }
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
        _noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        _reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
        _isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
        //
        if (_noConnectivity) {
            _isConnected = false;
        }
        else {
            if (isConnectedFast(_context)) {
                _isConnectivityGood = true;
            }
            else {
                _isConnectivityGood = false;
            }
            _isConnected = true;
        }
    }
    }
    
  • 2

    试试这个,

    ConnectivityManager connec = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
            try {
                android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
            android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    
            if (wifi.isConnected()||mobile.isConnected())  
                return true;
            else if (wifi.isConnected() && mobile.isConnected())  
                return true;
            else  
                return false;
    
        } catch (NullPointerException e) {
            Log.d("ConStatus", "No Active Connection");
            return false;
        }
    
  • 0

    此代码可能对您有所帮助 .

    ConnectivityManager cn= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    
    
        NetworkInfo networkInfo = cn.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
        testwifi=networkInfo.isConnected();
        if(!testwifi)
            tv1.setText("wifi is off");
        else
            tv1.setText("wifi is on");
    
  • 0

    试试这个:

    public static void isNetworkAvailable(Context context){
        HttpGet httpGet = new HttpGet("http://www.google.com");
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        try{
            Log.d(TAG, "Checking network connection...");
            httpClient.execute(httpGet);
            Log.d(TAG, "Connection OK");
            return;
        }
        catch(ClientProtocolException e){
            e.printStackTrace();
        }
        catch(IOException e){
            e.printStackTrace();
        }
    
        Log.d(TAG, "Connection unavailable");
    }
    

    资料来源:Check for Active internet connection Android

  • 0

    调用此类的isConnectingToInternet函数来检查您想要检查Internet连接的Internet连接 .

    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;
    }
    
    /**
     * Checking for all possible internet providers
     * **/
    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;
    }
    }
    
  • 0

    To ensure that actual internet is available or not need to ping any global url e.g www.google.com

    This will work 100%

    public static boolean isNetwokReachable() {
            final ConnectivityManager connMgr = (ConnectivityManager) mSmartAndroidActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
    
            if (netInfo != null && netInfo.isConnected()) {
                try {
                    URL url = new URL("http://www.google.com");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setRequestProperty("User-Agent", "Android Application");
                    urlc.setRequestProperty("Connection", "close");
                    urlc.setConnectTimeout(10 * 1000);
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) {
                        return true;
                    } else {
                        return false;
                    }
                } catch (Throwable e) {
                    return false;
                }
            } else {
                return false;
            }
        }
    

相关问题