Android: Check network and real internet connectivity

前端 未结 3 1587
暖寄归人
暖寄归人 2020-12-12 00:51

Below is the piece of Android code which works fine to check if network is connected or not.

public static boolean isNetworkAvailable(Context context) 
{
            


        
3条回答
  •  孤城傲影
    2020-12-12 01:19

    Issue #1:
    Android device connected to a Wi-Fi, which turns out to be a private network.
    So isNetworkAvailable will return that network is connected, but could not be connected to any other service.

    Issue #2:
    Sometimes the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access google/yahoo.

    I'm not sure about Issue #1 but I'm sure that following approach will solve Issue #2.
    

    Ultimately, you will need to Monitor the change in Network connection,

    Step 1:

    Just register a BroadcastReceiver for following action

    Step 2:

    when you get callback on onReceive(Context context,Intent intent) method ,check for connectivity status.

    i.e: boolean isConnected = getIntent().getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);

    //apart from EXTRA_NO_CONNECTIVITY, there are other parameters also which will be useful to monitor

    Reference:

    Examples:

    Working Example of Step1,Step2: how-to-monitor-network-connectivity-in-android

    Android-getting-notified-of-connectivity-changes

    Github: Example for network-detect-notify

    Android Docs:

    Connectivity Monitoring

    Connectivity Manager

    I hope it will be helpful !!

提交回复
热议问题