检查程序是否具有通过wifi的互联网

如何解决检查程序是否具有通过wifi的互联网

| 在阅读了一些答案并尝试使用它们后,无论是否通过wifi上网,我仍然无法使我的代码返回正确的状态。 我必须通过WIFI进行“ ping”操作,因为我们可能没有任何互联网连接就已连接到接入点。这是完整的代码。
ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NI = CM.getActiveNetworkInfo();
boolean IC = false;             
IC = CM.requestRouteToHost(ConnectivityManager.TYPE_WIFI,FlavaGr.lookupHost(pingyIp));
System.out.println(\"##### IC=\" + IC + \"  TYPE = \" + NI.getTypeName());
在这里lookupHost,由另一个用户建议:
public static int lookupHost(String hostname) {
InetAddress inetAddress;
try {
    inetAddress = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
    return -1;
}
byte[] addrBytes;
int addr;
addrBytes = inetAddress.getAddress();
addr = ((addrBytes[3] & 0xff) << 24)
        | ((addrBytes[2] & 0xff) << 16)
        | ((addrBytes[1] & 0xff) << 8)
        |  (addrBytes[0] & 0xff);
return addr;
}   
IC总是假的。 我觉得答案是一步之遥,但仍然不知道该怎么办。 PS对不起,我的英语。     

解决方法

        这是我使用的代码,没有任何问题:
    ConnectivityManager conn;
            conn=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            // Skip if no connection,or background data disabled
            NetworkInfo info = conn.getActiveNetworkInfo();
            if (info == null ||
            !conn.getBackgroundDataSetting()) {
                // No Network detected
                return;
            } else {
                int netType = info.getType();
                int netSubtype = info.getSubtype();
                if (netType == ConnectivityManager.TYPE_WIFI) {
                    //WIFI DETECTED
                              } else if (netType == ConnectivityManager.TYPE_MOBILE
                && netSubtype >2) {
                           //Mobile connected that is at least 3G   
                } else {
                    //Has connection but i\'m not sure what kind
                }
            }
和清单中的以下内容:
<uses-permission android:name=\"android.permission.INTERNET\" />
<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />
请注意,在仿真时,检测到的Internet连接可能会表现异常。     ,        我的答案是:
    ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NI = CM.getActiveNetworkInfo();
    if (NI!=null) {
        if (NI.isAvailable()) { 
            boolean IC = false;
            if (NI.getTypeName()==\"WIFI\") {
                int response = 0;
                try {
                    URL url = new URL(\"http://www.google.com/\");    
                    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                    response = in.read();
                    in.close();

                    IC = (response != -1) ? true : false;
                    System.out.println(\"##### IC=\" + IC + \"  TYPE = \" + NI.getTypeName() + \"  response = \" + response);
                    if (true){
                                                ;
                    };
                } catch (Exception e) {
                }}}}}
仅检查当前连接是否为WIFI,然后请求页面,检查第一个字符。     ,        我知道了:) 首先,这是不允许的,并且在主线程上执行httprequest也不好!因此,您必须在AsyncTask中完成! 其次,您无需检查是否存在连接...因为您可以连接到本地连接或连接速度太慢! 您需要做的就是http请求并检查是否在准确的时间内有响应。为此,您需要设置超时!但只有超时无法正常工作-您需要检查状态码...这里是:
class ConnectionTask extends AsyncTask<String,String,String> {

    /**
     * Before starting background thread set flag to false
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        flag = false;
    }

    boolean flag;

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        Log.v(\"url\",url);
        JSONObject json = jParser.makeHttpRequest(url,\"GET\",params); 
        /*is json equal to null ?*/
        if( json != null )
        {
            // Check your log cat for JSON response
            Log.d(\"json: \",json.toString());
            try {
                message = json.getString(\"message\");
                flag = true;//we succeded so we make the flag to true
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        else
        {//if json is null
            message = \"not connected to internet connection\";
            flag = false;
        }

        return null;
    }

    /**
     * After completing background task check if there is connection or no
     * **/
    protected void onPostExecute(String file_url) {
        // updating UI from Background Thread
        if(flag)
        {//flag is tro so there is connection
            Log.v(\"connection\",\"conectioOOOOOoooOooooOoooooOOOOoooOOOOOO\");
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into textview
                     * */
                    TextView tvTest = (TextView) findViewById(R.id.testTextView);
                    tvTest.setText(message);
                }
            });
        }
        else
        {////we catched that there is no connection!
            Log.v(\"connection\",\"nooooooo conectioOOOOOoooOooooOoooooOOOOoooOOOOOO\");
            runOnUiThread(new Runnable() {
                public void run() {
                            /*update ui thread*/
                    TextView tvTest = (TextView) findViewById(R.id.testTextView);
                    tvTest.setText(\"no connection\");
                    Toast.makeText(getApplicationContext(),\"No internet connection\",Toast.LENGTH_LONG).show();
                }
            });
        }
    }

}
所以现在是json解析器:)
public class JSONParser {

private InputStream is = null;
private JSONObject jObj = null;
private String json = \"\";
static int timeoutConnection = 10000;
static int timeoutSocket = 10000;

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url,String method,List<NameValuePair> params) {

    // check for request method
    if(method == \"POST\"){
        try{
           HttpPost request = new HttpPost(url);
           HttpParams httpParameters = new BasicHttpParams();
           // Set the timeout in milliseconds until a connection is established.
           // The default value is zero,that means the timeout is not used. 
           HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
           // Set the default socket timeout (SO_TIMEOUT) 
           // in milliseconds which is the timeout for waiting for data.
           HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);
           // create object of DefaultHttpClient    
           DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
           request.addHeader(\"Content-Type\",\"application/json\");
           HttpResponse response = httpClient.execute(request);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
               is = entity.getContent();

            }
           // convert entity response to string

       }
     catch (SocketException e)
      {
          e.printStackTrace();
         return null;
      }
     catch (Exception e)
      {
          e.printStackTrace();
         return null;
      }

    }else if(method == \"GET\"){
        try{
           HttpGet request = new HttpGet(url);
           HttpParams httpParameters = new BasicHttpParams();
           // Set the timeout in milliseconds until a connection is established.
           // The default value is zero,\"application/json\");
           HttpResponse response = httpClient.execute(request);
           StatusLine statusLine = response.getStatusLine();
           int statusCode = statusLine.getStatusCode();
           if (statusCode == 200) {
               HttpEntity entity = response.getEntity();
               is = entity.getContent();

           }
           // convert entity response to string

           }
         catch (SocketException e)
          {
             e.printStackTrace();
             return null;
          }
         catch (Exception e)
          {
             e.printStackTrace();
             return null;
          }
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is,\"iso-8859-1\"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + \"\\n\");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e(\"Buffer Error\",\"Error converting result \" + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e(\"JSON Parser\",\"Error parsing data \" + e.toString());
    }

    // return JSON String
    return jObj;

}
}
效果很好!     ,        尝试使用此方法来检查是否存在互联网连接:
public boolean connexionStatus(ConnectivityManager connec)
    {
        NetworkInfo[] allNetwork = connec.getAllNetworkInfo();
        if (allNetwork != null) 
        {
            for (int i = 0; i < allNetwork.length; i++) 
            {
                if (allNetwork[i].getState() == NetworkInfo.State.CONNECTED || 
                        allNetwork[i].getState() == NetworkInfo.State.CONNECTING )
                    return true;
            }
        }
        return false;
    }
注意:清单中应具有INTERNET的许可     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-