分享到:
点击次数:333  更新时间:2016-10-11 16:24:04  【打印此页】  【关闭
澳门新濠天地娱乐场澳门新濠天地娱乐定制
当前位置:主页 > 新闻动态 > 技术交流 > Android开源库:EventBus

Android开源库:EventBus

责任编辑:admin 发布时间:2016-11-17 14:36 浏览次数:

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(); 
            } 
        } 
     
    }