| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
10年前发布

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

项目主页:http://www.open-open.com/lib/view/home/1403076978887

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1403076978887.html
EventBus Android开发 移动开发