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" />