Detect if android device is connected to the internet

此生再无相见时 提交于 2019-12-05 16:13:07

Create a class :

public class Utility {
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

Then you call methode from activity, it will return true or false:

Utility.isNetworkAvailable(AnyActivity.this);

And don't forget to add permission to android manifest

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

This isn't the correct approach to checking for internet connectivity. You should be using Android's built in ConnectivityManager class for this.

It's quite simple to use, you can simply do the following to check for network connectivity:

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

This will also allow you to determine things like the type of connection, if it's monitored, etc. so that you can make informed decisions about the network tasks you are executing.

There is more info in this lesson on the Android Developers site.

You must do it in an asynctask. I use http://clients3.google.com/generate_204 to detect connection.

    import java.net.HttpURLConnection;
    import java.net.URL;


    ...

    private int inter = 0;   


    ...


     new checkconne().execute();

    ...



    class checkconne extends AsyncTask<String, String, String> {

                            @Override
                            protected void onPreExecute() {
                                super.onPreExecute();



                            }
                            @Override
                            protected String doInBackground(String... args) {

                                int kk=0;
                                try {
                                    HttpURLConnection urlc = (HttpURLConnection)
                                            (new URL("http://clients3.google.com/generate_204")
                                                    .openConnection());
                                    urlc.setRequestProperty("User-Agent", "Android");
                                    urlc.setRequestProperty("Connection", "close");
                                    urlc.setConnectTimeout(1500);
                                    urlc.connect();
                                    kk= urlc.getResponseCode();
                                } catch (IOException e) {


        Log.e("qweqwe", "Error checking internet connection", e);
                            }

                            inter=kk;



                            return null;
                        }
                        @Override
                        protected void onPostExecute(String file_url) {


                            if (inter == 204){       
             Toast.makeText(MainActivity3.this, "is connected", Toast.LENGTH_LONG).show();             

                            }else{    


                                Toast.makeText(MainActivity3.this, "No connection", Toast.LENGTH_LONG).show();

                            }


                        }
                    }

call this function :

     public static boolean isNetworkAvailable()
     {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        HttpGet httpGet = new HttpGet("http://www.google.com");
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 1500;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        try
        {
           httpClient.execute(httpGet);
           return true;
        }
        catch(ClientProtocolException e)
        {
           e.printStackTrace();
        }
        catch(IOException e)
        {
           e.printStackTrace();
        }
    return false;
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!