有效的方法,不断检查是否网络连接在机器人可 [英] Efficient approach to continuously check whether internet connection is available in Android

查看:89
本文介绍了有效的方法,不断检查是否网络连接在机器人可的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/3307237/how-can-i-monitor-the-network-connection-status-in-android">How我可以监视在Android上的网络连接状态?

我要不断上网查是否连接与否,并与相应的消息更新相应的文本区域。现在,如果我创建一个的AsyncTask 将执行一次并停止这不是我想要的。我要连续检查在每一个时刻,显然这不应该是主线程。所以在服务不会是一个很好的选择,要么。谁能帮我什么是处理这个最好的和有效的方法。谢谢

I need to continuously check whether the internet is connected or not and update the text area accordingly with appropriate message . Now if i create an asynctask it will execute once and stop which is not what I want . I want to check at every moment continuously and obviously this should not be on the main thread .So Service wont be a good choice either . Can anyone help me What is the best and efficient approach to handle this . Thanks

推荐答案

与接收做到这一点。你可以通知有关网络状态的变化。例如,

do it with a receiver. you can be notified about network state change. for example,

private BroadcastReceiver networkReceiver = new BroadcastReceiver {
    @Override
    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) {
            // we're connected
        }
     }
     // we're not connected 
   }
}

在此登记你的 onResume(),并注销在的onPause()

register this in your onResume(), and unregister on onPause().

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(networkReceiver);
}

@Override
protected void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(networkReceiver, filter);
}

此外,以获得您的接收器已被注册前的初始状态,称这种在 onResume()方法

additionally, to obtain the initial state before your receiver has been registered, call this in your onResume() method,

public boolean isNetworkConnected() {
        ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

请确保您的应用程序请求该权限,

make sure your app requests this permission,

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

这篇关于有效的方法,不断检查是否网络连接在机器人可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆