Internet listener Android example

前端 未结 2 654
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 02:33

I am working on an Android app that will continuously remain connected to Internet. If Internet is dow, it should give an appropriate message to the User.

Is there a

2条回答
  •  情深已故
    2020-11-29 03:08

    Create one Broadcast Receiver for that and register it in manifest file.

    First create a new class NetworkStateReceiver and extend BroadcastReceiver.

    public class NetworkStateReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
         Log.d("app","Network connectivity change");
         if(intent.getExtras()!=null) {
            NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
            if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
                Log.i("app","Network "+ni.getTypeName()+" connected");
            }
         }
         if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
                Log.d("app","There's no network connectivity");
         }
       }
    }
    

    Put this code in your AndroidManifest.xml under the "application" element:

    
       
          
       
    
    

    And add this permission

    
    

    EDIT

    This code just detects connectivity change but cannot tell whether the network it is connected to has a internet access. Use this method to check that -

    public static boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500); 
                urlc.connect();
                return (urlc.getResponseCode() == 200);
            } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
            }
        } else {
        Log.d(LOG_TAG, "No network available!");
        }
        return false;
    }
    

提交回复
热议问题