android 网络广播 类似QQ动态检查网络

android 网络广播 类似QQ动态检查网络
    private ConnectivityManager mConnectivityManager;  

    private NetworkInfo netInfo; 



在onCreate 注册广播



 IntentFilter mFilter = new IntentFilter();  mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(myNetReceiver, mFilter);



一定要在onDestroy()方法注销广播

    @Override

    public void onDestroy() { 

        super.onDestroy();

        if(myNetReceiver!=null){ 

               unregisterReceiver(myNetReceiver); 

        }

    }





rl_error_item是布局文件类似QQ列表显示的未连接网络状态XML布局



    private BroadcastReceiver myNetReceiver = new BroadcastReceiver() { 

           

         @Override 

         public void onReceive(Context context, Intent intent) { 

             

          String action = intent.getAction(); 

                if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { 

                      

                    mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 

                    netInfo = mConnectivityManager.getActiveNetworkInfo();   

                    if(netInfo != null && netInfo.isAvailable()) {  

                         //网络连接 

                        String name = netInfo.getTypeName();  

                        if(netInfo.getType()==ConnectivityManager.TYPE_WIFI || netInfo.getType()==ConnectivityManager.TYPE_ETHERNET || netInfo.getType()==ConnectivityManager.TYPE_MOBILE){ 

                            //3g网络 

                              rl_error_item.setVisibility(View.GONE);

                        } 

                      } else { 

                          //网络断开  

                          rl_error_item.setVisibility(View.VISIBLE);

                    } 

                } 

           

           }  

    };  
View Code

 

你可能感兴趣的:(android)