您的位置:首页 > 理论基础 > 计算机网络

Android 判断网络连接状态--实现微信在线/离线状态切换

2016-05-10 20:49 906 查看
先看效果图,有图有效果了才有动力(右边是关闭wifi/3g之后的Title样子)





首先了解一下网络状态的判断方法,网络状态是一个SystemService,可以通过context.getSystemService(String name)获取,对应的服务名称为context.CONNECTIVITY_SERVICE; 获取网络状态管理对象

  ConnectivityManager connManger = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

  在ConnectivityManger对象中有一些相关的方法

  NetworkInfo[] infos = connManger.getAllNetworkInfo(); // 获取所有的连接对象信息

  NetworkInfo active_info = connManger.getActiveNetworkInfo(); // 获取可用的连接对象信息

  active_info.isAvailable(); // 可用

  active_info.isConnected(); // 已经连接

  active_info.isConnectedOrConnecting(); // 已经连接或正在连接

  // active_info.getState().CONNECTED;

  // active_info.getState().CONNECTING;

  



  也可以指定获取连接的网络如{3G,WiFi,蓝牙等如止图右边框} 判断完网络状态之后,如果网络没有打开当前没有可用的网络,肯定希望直接打开网络设置进行网络的配置,看下面的代码

  Intent mIntent = new Intent("/");

  ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");

  mIntent.setComponent(component);

  mIntent.setAction("android.intent.action.VIEW");

  startActivity(mIntent);

  至此对网络状态的判断有了了解,怎么实时的监听网络状态改变呢,在android中,当网络状态发生改变的时候会发出一个广播,我们只需要接收到此广播即可进行判断

  public static final String CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";

  再看我们的标题,也就是重点,需要在页面上显示当前是否在线,也就是需要在接收到网络状态改变的广播的时候,要能够与Activity进行交互,通知Activity当前的网络状态,让Activity进行提示通知当前是在线还是离线,这就需要写一个Service,并且绑定到Activity,把广播监听到的实时的网络状态返回给Activity

  public class ReceiveMsgService extends Service {// 实时监听网络状态改变

  private BroadcastReceiver mReceiver = new BroadcastReceiver() {

  @Override

  public void onReceive(Context context, Intent intent) {

  String action = intent.getAction();

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

  Timer timer = new Timer();

  timer.schedule(new QunXTask(getApplicationContext()), new Date());

  }

  }

  };public interface GetConnectState {

  public void GetState(boolean isConnected); // 网络状态改变之后,通过此接口的实例通知当前网络的状态,此接口在Activity中注入实例对象

  }

  private GetConnectState onGetConnectState;

  public void setOnGetConnectState(GetConnectState onGetConnectState) {

  this.onGetConnectState = onGetConnectState;

  }

  private Binder binder = new MyBinder();

  private boolean isContected = true;

  @Override

  public IBinder onBind(Intent intent) {

  return binder;

  }

  @Override

  public void onCreate() {// 注册广播

  IntentFilter mFilter = new IntentFilter();

  mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action

  registerReceiver(mReceiver, mFilter);

  }

  class QunXTask extends TimerTask {

  private Context context;

  public QunXTask(Context context) {

  this.context = context;

  }

  @Override

  public void run() {

  if (isConnectNet()) {

  isContected = true;

  } else {

  isContected = false;

  }

  if (onGetConnectState != null) {

  onGetConnectState.GetState(isContected); // 通知网络状态改变

  }

  }

  /**

  * 判断是否连通网络

  *

  * @return

  */

  private boolean isConnectNet() {

  ConnectivityManager connectivityManager = (ConnectivityManager) context

  .getSystemService(Context.CONNECTIVITY_SERVICE);

  NetworkInfo Mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

  NetworkInfo Wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

  if (Mobile.getState().equals(State.DISCONNECTED)

  && Wifi.getState().equals(State.DISCONNECTED)) {

  return false;

  }

  return true;

  }

  }

  public class MyBinder extends Binder {

  public ReceiveMsgService getService() {

  return ReceiveMsgService.this;

  }

  }

  @Override

  public void onDestroy() {

  super.onDestroy();

  unregisterReceiver(mReceiver); // 删除广播

  }

  }

  接下来在Activity中,绑定服务

  private boolean conncetState = true; // 记录当前连接状态,因为广播会接收所有的网络状态改变wifi/3g等等,所以需要一个标志记录当前状态

  private ServiceConnection serviceConnection = new ServiceConnection() {

  @Override

  public void onServiceDisconnected(ComponentName name) {

  }

  @Override

  public void onServiceConnected(ComponentName name, IBinder service) {

  receiveMsgService = ((MyBinder) service).getService();

  receiveMsgService.setOnGetConnectState(new GetConnectState() { // 添加接口实例获取连接状态

  @Override

  public void GetState(boolean isConnected) {

  if (conncetState != isConnected) { // 如果当前连接状态与广播服务返回的状态不同才进行通知显示

  conncetState = isConnected;

  if (conncetState) {// 已连接

  handler.sendEmptyMessage(1);

  } else {// 未连接

  handler.sendEmptyMessage(2);

  }

  }

  }

  });

  }

  };

  在handler中处理连接状态改变之后的通知

  public class QunXHandler extends Handler {

  @Override

  public void handleMessage(Message msg) {

  super.handleMessage(msg);

  switch (msg.what) {case 1:// 已连接

  ...

  break;

  case 2:// 未连接

  title_tv.setText("群信(离线)");

  break;default:

  break;

  }

  }

  }

  当然也可以直接在Activity中注册一个广播,在接收到广播之后进行判断,这种情况就稍简单些,Activity可以直接访问到广播中的一些变量; 最后,需要添加一些权限:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: