简体   繁体   English

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

[英]How to check that android phone is not connected to internet?

I'm developing an application in android which fetches data from the database.我正在 android 中开发一个从数据库中获取数据的应用程序。 I have developed the code to find whether the WIFI or Mobile data is ON or OFF like this:我开发了代码来查找 WIFI 或移动数据是打开还是关闭,如下所示:

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;

    }

Now suppose that my WIFI or Mobile Data network is ON but I'm not connected to internet at all(WIFI not connected to any access point).How can i show this in android?现在假设我的 WIFI 或移动数据网络已打开,但我根本没有连接到互联网(WIFI 没有连接到任何接入点)。我如何在 android 中显示它?

Thanks,谢谢,

you can simply use this:你可以简单地使用这个:

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;
}

This class is pretty complete :这门课非常完整:

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;
    }
}
}

Try this,试试这个,

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;
    }

This code might help you.此代码可能对您有所帮助。

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");

Try this:试试这个:

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");
}

Source: Check for Active internet connection Android来源: 检查活动的互联网连接 Android

call the isConnectingToInternet function of this class to check the internet connection where u want to check internet connectivity .调用这个类的 isConnectingToInternet 函数来检查你想要检查互联网连接的互联网连接。

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;
}
}

To ensure that actual internet is available or not need to ping any global url eg www.google.com确保实际互联网可用或不需要 ping 任何全球网址,例如www.google.com

This will work 100%这将工作 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;
        }
    }

i was searching this question's answer also then i do this in my code and it works .我也在搜索这个问题的答案,然后我在我的代码中这样做并且它有效。 don't know , it is good or not .不知道好不好if there is something wrong please tell me about that.如果有什么问题,请告诉我。

Step : 1 Make a BaseActivity class and extends AppCompatActivity class and write code in this for network check and show message to user if there is no network connection :步骤: 1 创建一个BaseActivity并扩展AppCompatActivity并在其中编写代码以进行网络检查并在没有网络连接时向用户显示消息:

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar

open class BaseActivity : AppCompatActivity() {

    private var cManager: ConnectivityManager? = null
    private var mCallback: ConnectivityManager.NetworkCallback? = null
    private var request : NetworkRequest? = null
    private var view: View? = null
    private var mSnackBar: Snackbar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        cManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        request = NetworkRequest.Builder().build()

        // get root view where we want to show message
        view = window.decorView.rootView

        mCallback = object : ConnectivityManager.NetworkCallback() {
            override fun onLost(network: Network) {
                super.onLost(network)

                mSnackBar = Snackbar.make(view!!, "No Network connection", Snackbar.LENGTH_LONG)
                mSnackBar!!.duration = Snackbar.LENGTH_INDEFINITE
                mSnackBar!!.show()
            }

            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                if (mSnackBar != null){
                    mSnackBar!!.dismiss()
                }
            }
        }
        cManager!!.registerNetworkCallback(request!!, mCallback!!)
    }
    override fun onStop() {
        super.onStop()
        cManager!!.unregisterNetworkCallback(mCallback!!)    
    }
}

Step 2:第2步:

Now in MainActivity class , extends this BaseActivity class.现在在MainActivity类中,扩展此BaseActivity类。

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }
}

step 3 : Don't forget to add this in AndroidManifest File第 3 步:不要忘记在AndroidManifest文件中添加它

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

now run and check your application.现在运行并检查您的应用程序。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Android中检查移动网络是否连接到互联网 - How to check if mobile network is connected to the internet or not in android 如何检查Wifi是否已连接,但Android中无法访问Internet - How to check Wifi is connected, but no Internet access in Android 如何检查android中连接的真实互联网? - how to check the real Internet connected in android? android如何检查wifi已连接但没有互联网连接 - android how to check wifi is connected but no internet connection 如何检查我的测试android设备是否已连接到互联网? - How to check My test android device is connected to internet or not? Android-如何检查其他用户是否已连接到互联网? - Android - How to check whether other user is connected to internet? 检查设备是否确实已连接到互联网android - check if device is really connected to the internet android 使用Python脚本检查android设备是否已连接到互联网 - Python script to check if android device is connected to internet 如何显示未在Android中连接的互联网 - How to show internet not connected in android 如何在Android程序中检查wifi路由器是否访问互联网? 手机已连接到wifi路由器,但路由器无法访问互联网? - How check wifi router accessing internet or not In Android Program? Mobile is connected to wifi router but router not accessing internet?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM