简体   繁体   English

启用wifi时检查Internet是否已在设备上连接

[英]Check Internet is Connected on Device or not when wifi is enable

I have facing a problem regarding device is available on internet or not.Let me explain my query in brief with a example: I have test my application with a use case ie I have on my router wifi but I unplug the Ethernet cable from my router and connect my device on wifi and by using following code: 我遇到有关设备是否可以在Internet上使用的问题。让我用一个示例简要说明我的查询:我已经用一个用例测试了我的应用程序,即我在路由器wifi上进行了测试,但是从路由器上拔了以太网电缆并使用以下代码在wifi上连接我的设备:

private boolean checkConnection() {
    boolean connected = false;
    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm != null) {
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();

        for (NetworkInfo ni : netInfo) {
            if ((ni.getTypeName().equalsIgnoreCase("WIFI")
                || ni.getTypeName().equalsIgnoreCase("MOBILE"))
                & ni.isConnected() & ni.isAvailable()) {
                connected = true;
            }

        }
    }

    return connected;
}

I will get a Boolean flag for connectivity .This code return the device status of switch means my device is connected with WiFi or not but I will not getting any response from the server or host,So I need to check the internet feasibility on my device or not .Please some one help me for the same.I have tried many goggling approaches or methodology but failed in success. 我将获得一个用于连接的布尔值标志。此代码返回交换机的设备状态,这意味着我的设备是否已连接WiFi,但我不会从服务器或主机获得任何响应,因此我需要检查设备上的互联网可行性是否可以。请有人帮我同样。我尝试了许多护目镜的方法或方法,但未能成功。

Thanks in advance. 提前致谢。

如果您需要检查连接是否确实可以提供Internet连接,则可以尝试ping通一些远程主机-Google,例如: 如何从Java Android Ping外部IP

      On button click 
        if(isInternetON(MainActivity.this)){
        mMyDownloadTask = new MyDownloadTask();
        delayCancel = new DelayCancel(mMyDownloadTask);
        handler.postDelayed(delayCancel,3*1000);
        mMyDownloadTask.execute();



        }



  public static class MyDownloadTask extends AsyncTask<Boolean,Void,Boolean> {

        public MyDownloadTask() {

        }

        protected Boolean doInBackground(Boolean... params) {
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//              connection.setRequestMethod("Head");
//              connection.setConnectTimeout(2000);
                connection.connect();

                int code = connection.getResponseCode();
                Log.e(TAG, "code : " + code);
                if (code == 200) {
                    ThreadActivity.isAviliable = true;
                    MainActivity.value = "true";
                    return true;

                } else {
                    ThreadActivity.isAviliable = false;
                    MainActivity.value = "false";
                    return false;

                }

            } catch (Exception e) {
                ThreadActivity.isAviliable = false;
                MainActivity.value = "false";
                e.printStackTrace();
                return false;
            }

        }

        protected void onPostExecute(Boolean result) {
            // dismiss progress dialog and update ui
            Log.e(TAG,"result "+result);
            if(result){
                ThreadActivity.isAviliable = true;
                MainActivity.value = "true";
            }else{
                ThreadActivity.isAviliable = false;
                MainActivity.value = "false";
            }

        }
    }
    public static class DelayCancel implements Runnable{
        private AsyncTask task;

        public DelayCancel(AsyncTask task) {
            this.task = task;

        }

        @Override
        public void run() {
            Log.e(TAG, "Running.....");
            if (task.getStatus() == AsyncTask.Status.RUNNING) {
                task.cancel(true);
                Log.e(TAG, "Cancel 1.....");
                ThreadActivity.isAviliable = false;
                MainActivity.value = "false";
            }
            if (task.getStatus() == AsyncTask.Status.PENDING){
                task.cancel(true);
                ThreadActivity.isAviliable = false;
                MainActivity.value = "false";
                Log.e(TAG, "Cancel 2.....");
            }
        }
    }

    public static boolean isInternetON(Context ctx){

        ConnectivityManager cm =(ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

       /* Log.e("Common Class","activeNetwork.getState()"+activeNetwork.getState());
        Log.e("Common Class","activeNetwork.isAvailable()"+activeNetwork.isAvailable());
        Log.e("Common Class","activeNetwork.getReason()"+activeNetwork.getReason());
        Log.e("Common Class","activeNetwork.getExtraInfo()"+activeNetwork.getExtraInfo());
        Log.e("Common Class","activeNetwork.describeContents()"+activeNetwork.describeContents());
        Log.e("Common Class","activeNetwork.isConnectedOrConnecting()"+activeNetwork.isConnectedOrConnecting());
        Log.e("Common Class","activeNetwork.isFailover()"+activeNetwork.isFailover());*/

        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting() && activeNetwork.isAvailable();

        return isConnected;
    }

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

相关问题 如何检查设备连接的wifi上网速度? - how to check device connected wifi internet connection speed? 检查设备上次何时连接到互联网 - Check when a device last time connected to the internet 当我的设备实际连接到WIFI时,为什么我的设备似乎没有连接到互联网? - Why doesn't my device appear to be connected to the internet when it is actually connected to WIFI? 如何检查Wifi是否已连接,但Android中无法访问Internet - How to check Wifi is connected, but no Internet access in Android android如何检查wifi已连接但没有互联网连接 - android how to check wifi is connected but no internet connection 是否有API检查WiFi是否连接到Internet? - Is there any API to check wether the WiFi is connected to the Internet or not? 以编程方式将Android设备连接到Hotspot(没有互联网)切换回带有互联网的wifi - Programatically connected android device to Hotspot (no internet) switches back to wifi with internet 如何检查互联网是否可用wifi(虽然连接了Wifi) - How to check internet is available in wifi(Though Wifi is connected ) 连接互联网/ WiFi时运行代码 - Run code when internet / WiFi is connected 如何检测WIFI何时连接到互联网? - How to detect when WIFI is connected to internet?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM