public class NetworkStateReceiver extends BroadcastReceiver {
// internet bilan aloqa yo’qolganda
post qiluvchi hodisa
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) {
// there is Internet connection
} else if(intent
.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
//
no Internet connection, tarmoq holati o’zgarganini
yuborish
EventBus.getDefault().post(new NetworkStateChanged(false));
}
}
// hodisa
public class NetworkStateChanged {
private mIsInternetConnected;
public NetworkStateChanged(boolean isInternetConnected) {
this.mIsInternetConnected = isInternetConnected;
}
public boolean isInternetConnected() {
return this.mIsInternetConnected;
}
}
public class HomeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this); //
register EventBus
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this); // unregister EventBus
}
// method that will be called
when someone posts an event
NetworkStateChanged
public void onEventMainThread(NetworkStateChanged event) {
if (!event.isInternetConnected()) {
Toast.makeText(this, "Aloqa uzilgan!",
Toast.LENGTH_SHORT).show();
}
} }