简体   繁体   English

检查互联网连接类型时应用崩溃

[英]App crashing during checking internet connectivity type

I have written code to check the network connectivity type as follows: 我已经编写了如下代码来检查网络连接类型:

ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

//mobile
NetworkInfo.State mobile = conMan.getNetworkInfo(0).getState();

//wifi
NetworkInfo.State wifi = conMan.getNetworkInfo(1).getState();

I have also added the following permission to the AndroidManifest.xml file 我还向AndroidManifest.xml文件添加了以下权限

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

But when I run the application it crashes. 但是,当我运行该应用程序时,它崩溃了。 Does anyone know what is causing this? 有谁知道是什么原因造成的?

Have you added these two permissions in your manifest file, if not add these: 您是否在清单文件中添加了这两个权限(如果未添加):

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

Can't tell the actual problem or solution as you haven't posted any error log. 由于您尚未发布任何错误日志,因此无法说出实际的问题或解决方案。 Though you can try this code. 虽然您可以尝试此代码。

 private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

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

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