简体   繁体   English

实施ConnectivityManager和NetworkInfo时,应用程序停止

[英]App stops when implementing ConnectivityManager and NetworkInfo

For my app, I was trying to detect when the user is connected to the internet. 对于我的应用程序,我试图检测用户何时连接到互联网。 This is one of the methods I've been using, although I've used some other that where basically the same, but using other methods of the objects used: 这是我一直在使用的方法之一,尽管我使用了其他基本相同的方法,但是使用了所使用对象的其他方法:

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

Even if this does not lead to any compilation error, when launching the app it stops abruptly and does not respond. 即使这不会导致任何编译错误,在启动应用程序时,它也会突然停止并且不响应。 I'd like to know why this happens and how to solve it or, if has no aparent solution, if there's another way of doing what I wanted. 我想知道为什么会发生这种情况,以及如何解决,或者如果没有解决方案,是否还有另一种方法可以做我想要的事情。

I have tried deleting part of the code strategically and I have noticed that the part that gives problems is netInfo with both of ways it is being used, but I don`t know why. 我尝试过策略性地删除部分代码,并且我注意到导致问题的部分是使用两种方式使用的netInfo ,但是我不知道为什么。

AndroidManifest文件中添加访问网络权限

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

First add users-permission in AndroidManifest.xml file like this 首先像这样在AndroidManifest.xml文件中添加users-permission

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

Second, this pics of code can give you a boolean . 其次,这段代码可以给你一个boolean Network connection is available or not. 网络连接是否可用。 so put it in a method and get return of those code like this.. 所以把它放在一个方法中,然后像这样返回这些代码。

public boolean getCheckedNetStatus(Context context) {
   try{
      ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
      if (networkInfo != null && networkInfo.isConnected()) {
         return true;
      } else {
         return false;
      }
   }catch(Exception e){
     Log.e("Net Check Err", e.toString());
     return false;
   }
}

Have try catch will protect your from unexpected crash your app... 试用try可以保护您的应用程序免于意外崩溃。

Now Call it to conditionally execute your certain action like this 现在调用它有条件地执行您的某些操作,例如

if(getCheckedNetStatus(yourActivity.this)){
    //Net is available 
    //So do your action
}else{
   //Net not available 
   //you can notify user that net not available 
   //So you (User) can't do this
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM