如何编码检查棒棒糖的互联网连接?

时间:2015-09-06 08:37:35

标签: android http

这是我正在部署的用于检查互联网连接的代码。这适用于除Lollipop之外的每个版本。我只是从几个链接中了解到棒棒糖版本的URL类与我们用于低级版本的版本不同。可以请任何人帮助我解决这个问题,提供适用于所有版本手机的代码。

代码是:

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


   ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                urlc.setConnectTimeout(4000);
                urlc.connect();
                if (urlc.getResponseCode() == 200) {
                    return true;
                }
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return false;

    }

3 个答案:

答案 0 :(得分:0)

要检查每个版本的Android中的互联网连接,请尝试:

1-创建一个名为ConnectionDetector的类并复制此代码

 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;

public class ConnectionDetector {
private Context _context;

public ConnectionDetector(Context context) {
    this._context = context;
}

public boolean isConnectingToInternet() {
    ConnectivityManager connectivity = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

    }
    return false;
}
}

2 - 在您的活动(上面的onCreate方法)中,您想要检查互联网连接是否复制此代码

    Boolean _isInternetPresent = false;
    ConnectionDetector _cd;

并且在OnCreate方法中,只要您想检查互联网连接,请使用以下条件:

     _cd = new ConnectionDetector(getApplicationContext());
     _isInternetPresent = _cd.isConnectingToInternet();

     if (_isInternetPresent) {
         // your code that u want run if internet is connected

     } else {
         Toast.makeText(DisplayActivity.this, "Not communicate",Toast.LENGTH_SHORT).show();
            }

简单实用......

答案 1 :(得分:0)

我点了这个链接http://www.androidhive.info/2012/07/android-detect-internet-connection-status/

公共类ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}

public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null) 
              for (int i = 0; i < info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}

}

创建该类的对象 ConnectionDetector cd = new ConnectionDetector(context); boolean isInternetPresent = cd.isConnectingToInternet();

答案 2 :(得分:0)

用于检查互联网连接。

 public static void isNetworkAvailable(final Handler handler, final int timeout) {
        // ask fo message '0' (not connected) or '1' (connected) on 'handler'
        // the answer must be send before before within the 'timeout' (in milliseconds)

        new Thread() {
            private boolean responded = false;
            @Override
            public void run() {
                // set 'responded' to TRUE if is able to connect with google mobile (responds fast)
                new Thread() {
                    URL aURL;
                    String link = "some link";

                    @Override
                    public void run() {
                      //  HttpGet requestForTest = new HttpGet("https://lit-hamlet-6856.herokuapp.com/eventsList/TECHNICAL");
                        HttpURLConnection connection;
                        try {
                            aURL = new URL(link);

                            connection = (HttpURLConnection) aURL.openConnection();
                            connection.setRequestMethod("GET");
                            connection.connect();

                           // new DefaultHttpClient().execute(requestForTest); // can last...

                            if(connection.getResponseCode()==200)
                            responded = true;
                            Log.i(getClass().getName(),"RESULT");
                        }
                        catch (Exception e) {
                        }
                    }
                }.start();

                try {
                    int waited = 0;
                    while(!responded && (waited < timeout)) {
                        sleep(100);
                        if(!responded ) {
                            waited += 100;
                        }
                    }
                }
                catch(InterruptedException e) {} // do nothing
                finally {
                    if (!responded) { handler.sendEmptyMessage(0); }
                    else { handler.sendEmptyMessage(1); }
                }
            }
        }.start();
    }

然后调用处理程序来执行你的互联网可用/不可用的工作

Handler h = new Handler(new Handler.Callback()  {
    @Override
    public boolean handleMessage(Message msg) {

        if (msg.what != 1) { // code if not connected

            new NoInternetclass().execute();
        } else { // code if connected
            new Internetclass().execute();//if net is present

        }
        return  true;

    }
});

然后从您的onCreate方法

中调用isNetworkAvailable(h, 3000);

请放心,这个课程正常,因为我在我的nexus 4 runing 5.1.1

上使用了这段代码