检查网络连接问题

发布于 2024-09-26 01:36:27 字数 687 浏览 8 评论 0原文

我有一个 IntentService 可以进行一些 Web 服务调用。在拨打这些电话之前,我会检查以确保设备具有网络连接。我这样做是这样的:

 private boolean isOnline() {
  ConnectivityManager connec =  (ConnectivityManager)getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
  return connec.getNetworkInfo(0).isConnectedOrConnecting();
 }

不幸的是,当我在 Android 设备上进行调试时,当我同时拥有网络和无线连接时,这会返回 false。

关于 connec.getNetworkInfo(0) 的一些有趣的花絮:

mIsAvailable = true
mNetworkType = 0
mTypeName = "mobile"
mState.name = "DISCONNECTED"

显然这段代码是不够的(也许只有当我通过网络发送一些位并打开无线电时它才会返回 true?)。此外,由于我不太熟悉 ConnectivityManager,我假设我应该扫描所有网络(即:getNetworkInfo(0 到 N))。

我怎样才能在这里正确地完成我想要的事情?

I have an IntentService which makes some web service calls. Before making these calls I check to make sure the device has network connectivity. I am doing so like this:

 private boolean isOnline() {
  ConnectivityManager connec =  (ConnectivityManager)getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
  return connec.getNetworkInfo(0).isConnectedOrConnecting();
 }

Unfortunately, when I'm debugging on my Android device, this returns false when I have both a network and a wireless connection.

Some interesting tidbits about connec.getNetworkInfo(0):

mIsAvailable = true
mNetworkType = 0
mTypeName = "mobile"
mState.name = "DISCONNECTED"

Clearly this code is not sufficient (perhaps it would only return true if I sent some bit over the network and turned the radio on?). Moreover, since I'm not well versed in the ConnectivityManager, I'm assuming I should probably be scanning all networks (ie: getNetworkInfo(0 through N)).

How can I properly accomplish what I'm wanting here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

软糖 2024-10-03 01:36:27

试试这个:

public static boolean isNetworkConnected(Context context){
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo network = cm.getActiveNetworkInfo();

    if(network != null){
        return network.isAvailable();
    }

    return false;
}

Try this:

public static boolean isNetworkConnected(Context context){
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo network = cm.getActiveNetworkInfo();

    if(network != null){
        return network.isAvailable();
    }

    return false;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文