Android开源库:EventBus
EventBus是用于简化应用中各个部件之间通信的一个库。比如从一个Activity发送消息到一个正在运行的服务,亦或是片段之间简单的互动。而下面使用的示例,就是如果网络连接丢失,该如何通知一个活动: public class NetworkStateReceiver extends BroadcastReceiver { // post event if there is no Internet connection 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, send network state changed EventBus.getDefault().post(new NetworkStateChanged(false)); } } // event 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, "No Internet connection!", Toast.LENGTH_SHORT).show(); } } }