Possible Duplicate:
How can I monitor the network connection status in Android?
I need to continuously check whether the internet is connected or not and update the text area accordingly with appropriate message . Now if i create an asynctask it will execute once and stop which is not what I want . I want to check at every moment continuously and obviously this should not be on the main thread .So Service wont be a good choice either . Can anyone help me What is the best and efficient approach to handle this . Thanks
The API enables you to determine whether the device is currently connected to a network that satisfies your app's requirements.
How does your app check that internet connectivity is available in the manifest? In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object.
do it with a receiver. you can be notified about network state change. for example,
private BroadcastReceiver networkReceiver = new BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
// we're connected
}
}
// we're not connected
}
}
register this in your onResume()
, and unregister on onPause()
.
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(networkReceiver);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkReceiver, filter);
}
additionally, to obtain the initial state before your receiver has been registered, call this in your onResume()
method,
public boolean isNetworkConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
make sure your app requests this permission,
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You don't need to constantly ask the OS if there is a network connection. Simply check whether a connection exists in onResume()
and then use a BroadcastReceiver to listen for the CONNECTIVITY_ACTION
Intent from the ConnectivityManager when the connection is changed and check EXTRA_NO_CONNECTIVITY
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With