Android - 打开应用程序后立即检查Internet连接

时间:2014-05-07 13:10:16

标签: android

我正在尝试检查用户打开应用程序后是否有网络连接,但我遇到的困难很少。即,一旦打开申请并进入此尝试阻止:

try {
                      new DefaultHttpClient().execute(requestForTest);
                      responded = true;
                    } catch (Exception e) {
                        responded = false;
                    }

响应总是返回false,但是当用户点击按钮返回main / activity时,返回true。

简单来说,只有当用户在按下按钮后返回主屏幕/活动时,响应才会返回true,否则返回false。我哪里错了?感谢谢谢你的帮助!

 protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    boolean check=chkNetworkStatus(getBaseContext());
    if (check==true)
            {
                Toast.makeText(getApplicationContext(), "you have a working internet connection", Toast.LENGTH_SHORT).show();
                //do something

            }

    public static boolean chkNetworkStatus(Context context) {
            boolean result = false;

            new Thread() {
                @Override
                public void run() {


                   for(int i=0;i<1;i++){
                   HttpGet requestForTest = new HttpGet("http://m.google.com");
                   try {
                          new DefaultHttpClient().execute(requestForTest);
                          responded = true;
                        } catch (Exception e) {
                            responded = false;
                        }
                   }
                }
            }.start();
            boolean isOnline = isOnline(context);
            if(responded && isOnline){
                result = true;
            } else {
                result = false;
            }

            Log.e("","responded : "+responded);
            return result;
        }

    public static boolean isOnline(Context context) {
                ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                    return true;
                }
                return false;
            }

Log : 




[As Soon as application starts]
    05-07 13:41:00.121: E/(10640): responded : false
    05-07 13:41:00.313: D/libEGL(10640): loaded /system/lib/egl/libEGL_emulation.so
    05-07 13:41:00.321: D/(10640): HostConnection::get() New Host Connection established 0xb97d4600, tid 10640
    05-07 13:41:00.409: D/libEGL(10640): loaded /system/lib/egl/libGLESv1_CM_emulation.so
    05-07 13:41:00.409: D/libEGL(10640): loaded /system/lib/egl/libGLESv2_emulation.so
    [after clicking a button to get back to the first activity]
    05-07 13:41:23.553: E/(10640): responded : true
    05-07 13:41:23.689: D/dalvikvm(10640): GC_CONCURRENT freed 239K, 9% free 19341K/21156K, paused 3ms+1ms, total 35ms
    05-07 13:41:23.689: D/dalvikvm(10640): WAIT_FOR_CONCURRENT_GC blocked 8ms
    05-07 13:41:23.689: D/dalvikvm(10640): WAIT_FOR_CONCURRENT_GC blocked 9ms
    05-07 13:41:23.689: D/dalvikvm(10640): WAIT_FOR_CONCURRENT_GC blocked 9ms
    05-07 13:41:23.765: W/EGL_emulation(10640): eglSurfaceAttrib not implemented
    05-07 13:41:24.033: I/System.out(10640): {"result" : "true"}

3 个答案:

答案 0 :(得分:0)

使用此方法检查网络连接:

public static boolean isNetworkAvailable(Context context)
    {
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED
                || connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTING)
        {
            return true;
        }
        else
            if (connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED
                    || connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTING)
            {

                return true;
            }
            else
                return false;

    }

答案 1 :(得分:0)

要检查互联网连接状态,首先要在清单中写下:

 <!-- Internet Permissions -->
 <uses-permission android:name="android.permission.INTERNET" />

 <!-- Network State Permissions -->
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

然后我使用此方法检查连接状态:

public boolean isConnectingToInternet(Context context){
    ConnectivityManager connectivity = 
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity == null) {
        return false;
    }

    NetworkInfo[] info = connectivity.getAllNetworkInfo();
    if (info == null) {
        return false;
    }

    for (NetworkInfo anInfo : info) {
        if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
            return true;
        }
    }

    return false;
}

答案 2 :(得分:0)

if it is connected to a router but what if the router is not connected to the internet
Set time out

    HttpGet httpGet = new HttpGet(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. 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function setParams().

httpClient.setParams(httpParameters);