在Android中持续检查互联网连接的最佳方法是什么?

3

我正在开发一个应用程序。其中一个屏幕会在onCreate()方法之后立即检查网络连接情况。如果网络连接良好,我将调用一个AsyncTask类来加载国家列表,并在spinnerView上显示它。如果没有网络连接,我会向用户显示Toast消息并调用check_Network(AsyncTask)。在这个类的protected Long doInBackground(URL... params)方法中,我会检查网络是否连接,如果连接了,则调用countries AsyncTask,否则我会再次调用check_Network(AsyncTask)。这个过程会一直重复,直到网络连接成功。我的问题是,这种重复检查网络的方式是否正确,请给我建议。很抱歉我的英语不好,请理解下面是我展示的代码

if (CheckNetwork.isOnline(this)) {
            try {
                new CountryProcess().execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {


            Toast.makeText(
                    getApplicationContext(),
                    getString(R.string.network_connection_fail)
                            + "!", Toast.LENGTH_LONG).show();
            new NetWork_connectivity().execute();
}

//.......................//

class NetWork_connectivity extends AsyncTask<URL, Integer,Long>
    {
        @Override
        protected Long doInBackground(URL... params)
        {
            if (CheckNetwork.isOnline(MainActivity.this)) {

                new CountryProcess().execute();

            }else
            {
                new NetWork_connectivity().execute();
            }

            return null;
        }
    }

为什么不让国家列表RPC继续运行,如果失败了再报告toast呢? - moofins
我在那个屏幕上停留了很长时间,那么我该如何再次调用CountryProcess Async类呢? - Rajesh kumar
2个回答

8
在清单文件中添加以下代码,以添加具有连接更改意图的接收器。
<receiver android:name=".NetworkStateReceiver">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

在接收方,获取与意图相关的额外信息并检查状态。因此,每当网络状态发生变化时,您将收到通知,然后相应地执行任务。

public class NetworkStateReceiver extends BroadcastReceiver {
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) {
        //connected
    }
 }
 if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
        //not connected
 }
}
}

对于您的情况,您需要在清单文件中添加权限,并在您的活动中注册接收器。

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(networkReceiver, filter);

在离开活动之前,确保注销它。使用以下代码:
unregisterReceiver(networkReceiver);

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) {
            //connected
        }
     }
     //not connected 
   }
}

根据您的要求,您只需要一次连接状态。首先检查连接状态,如果未连接,则仅注册接收器。

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

谢谢,Anupam,这是最好的方法。 - Rajesh kumar

1
要访问互联网,我们需要INTERNET权限
要检测网络状态,我们需要ACCESS_NETWORK_STATE权限
请在AndroidManifest.xml中添加以下代码行:
<!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />

<!-- Network State Permissions -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

在你的Java类中创建这个方法:
public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null) 
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null) 
                  for (int i = 0; i < info.length; i++) 
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }

每当您想在应用程序中检查互联网状态时,请调用 isConnectingToInternet() 函数,它将返回 true 或 false。

ConnectionDetector cd = new ConnectionDetector(getApplicationContext());

Boolean isInternetPresent = cd.isConnectingToInternet(); // true or false

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接