Android-应用程序打开后立即检查互联网连接

Android-应用程序打开后立即检查互联网连接,android,Android,我试图在用户打开应用程序后立即检查他是否有网络连接,但我遇到了一些困难。i、 例如,应用程序打开后,当它转到此尝试块时: try { new DefaultHttpClient().execute(requestForTest); responded = true; } catch (Exception e) { resp

我试图在用户打开应用程序后立即检查他是否有网络连接,但我遇到了一些困难。i、 例如,应用程序打开后,当它转到此尝试块时:

try {
                      new DefaultHttpClient().execute(requestForTest);
                      responded = true;
                    } catch (Exception e) {
                        responded = false;
                    }
Responsed始终返回false,但是当用户单击按钮返回到main/activity Responsed时返回true

简单地说,只有当用户在按下按钮后返回主屏幕/活动时,Responsed才会返回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"}
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
布尔检查=chkNetworkStatus(getBaseContext());
如果(检查==true)
{
Toast.makeText(getApplicationContext(),“您有一个工作的internet连接”,Toast.LENGTH\u SHORT.show();
//做点什么
}
公共静态布尔值chkNetworkStatus(上下文){
布尔结果=假;
新线程(){
@凌驾
公开募捐{

对于(int i=0;i使用此方法检查网络连接:

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;

    }

要检查internet连接状态,首先必须在清单中填写:

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

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

谢谢,但如果连接到路由器,此方法将返回true,但如果路由器未连接到internet怎么办!谢谢,但如果连接到路由器,此方法将返回true,但如果路由器未连接到internet怎么办!@user3458008其返回false simplyIt仍然返回true,而不是false,因为移动设备为con已连接到路由器!@yuvaツ 我已经发布了我的日志!
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;
}
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);