Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internet listener Android example

Tags:

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 any thing like Internet Listener? Or how to implement this event that whenever Internet connection is not available it should give alert.

like image 347
Zeeshan Chaudhry Avatar asked Aug 28 '12 10:08

Zeeshan Chaudhry


People also ask

How do Android apps connect to the internet?

Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Now just click on button, It will check internet connection as well as it will download image. Out would be as follows and it has fetch the logo from internet.

How do you check internet is on or off in android programmatically?

In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object. Following is the code snippet of using the ConnectivityManager class to know whether the internet connection is available or not.


2 Answers

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:

<receiver android:name=".NetworkStateReceiver">    <intent-filter>       <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />    </intent-filter> </receiver> 

And add this permission

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

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; } 
like image 165
Chirag Avatar answered Oct 01 '22 21:10

Chirag


The code from Chirag Raval above certainly works. The trouble is that the listener will get invoked even when the application is not running in foreground.

IMHO, the better approach is to register / unregister the receiver in the onResume() / onPause() methods of all your application activities. This code should do it:

private final NetworkStateReceiver stateReceiver = new NetworkStateReceiver();  @Override protected void onResume() {     super.onResume();     IntentFilter filter = new IntentFilter();     filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");     registerReceiver(stateReceiver, filter); }  @Override protected void onPause() {     super.onPause();     unregisterReceiver(stateReceiver); } 

Obviously, remove the registration from AndroidManifest.xml file.

Using this solution, the receiver will be called also when switching between activities of your application (assuming you are closing them). In such a case, use a static flag (being shared between all your activities) like in the example below (called online):

public class NetworkStateReceiver extends BroadcastReceiver {      private static boolean online = true;  // we expect the app being online when starting      public static final String TAG = NetworkStateReceiver.class.getSimpleName();      public void onReceive(Context context, Intent intent) {         Log.d(TAG,"Network connectivity change");         ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);         NetworkInfo ni = manager.getActiveNetworkInfo();         if (ni == null || ni.getState() != NetworkInfo.State.CONNECTED) {             Log.d(TAG,"There's no network connectivity");             if (online) // don't show the message if already offline                 Toast.makeText(context, R.string.noInternet, Toast.LENGTH_SHORT).show();             online = false;         } else {             Log.d(TAG,"Network "+ni.getTypeName()+" connected");             if (!online)  // don't show the message if already online                 Toast.makeText(context, R.string.backOnline, Toast.LENGTH_SHORT).show();             online = true;         }     } } 

If starting your app when being offline, the Toast message will appear; otherwise it appears only when losing / re-establishing the connection .

like image 29
pepan Avatar answered Oct 01 '22 23:10

pepan