在android登录中测试互联网连接

时间:2016-06-11 16:41:19

标签: android

我想查看互联网连接。我尝试使用此代码执行此操作,但它不起作用。我没有收到任何消息(Aucune connexion internet)

private boolean isConnectingToInternet(Context applicationContext){
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            Toast.makeText(getApplicationContext(), "no internet", Toast.LENGTH_LONG).show();
            return false;
        } else
            return true;

    }

protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                if(isConnectingToInternet(getApplicationContext()))   {
                showEmployee(s);
                }else{
                    // show alert
                    Toast.makeText(MainActivity.this, "Aucune connexion internet", Toast.LENGTH_SHORT).show();
                }
            }

2 个答案:

答案 0 :(得分:1)

您是从互联网上获取String s,这就是您使用AsyncTask的原因吗?在这种情况下,您应该在运行isConnectingToInternet之前检查AsyncTask ,而不是在其中。

无论如何,请在isConnectingToInternet

中试试
private boolean isConnectingToInternet(Context applicationContext){
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    return ni != null && ni.isConnectedOrConnecting();
}

答案 1 :(得分:0)

你在正确的轨道上,但缺少一小部分,检查isConnected以及!= null,如下所示:

 private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return ((activeNetworkInfo != null) && activeNetworkInfo.isConnected());
}

这个功能对我有用。它只是与你的另一个条件不同。