有效的方法,不断检查是否网络连接在机器人可机器人、有效、方法、网络

2023-09-05 23:27:04 作者:你最珍贵,请别皱眉

可能重复:   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" />