我怎样才能检查android中的网络连接?

时间:2012-01-25 09:24:36

标签: android wifi gprs

我开发了一个应用程序,我必须检查网络是否已连接我使用以下代码,但它不起作用。任何人都可以解决我的问题。我的代码是

public class AbcActivity extends Activity {
    Button b;
    private static final String tag = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                netCheckin();
            }
        });
    }
        private void netCheckin() {

            try {

                ConnectivityManager nInfo = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                nInfo.getActiveNetworkInfo().isConnectedOrConnecting();

                Log.d(tag, "Net avail:"
                        + nInfo.getActiveNetworkInfo().isConnectedOrConnecting());

                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                   Toast.makeText(getApplicationContext(), "net on", Toast.LENGTH_LONG).show();
                    Log.d(tag, "Network available:true");

                } else {
                     Toast.makeText(getApplicationContext(), "net OFF", Toast.LENGTH_LONG).show();
                    Log.d(tag, "Network available:false");

                }

            } catch (Exception e) {
               Log.e("error",""+e);
            }
        }

    }

我已经给了android:name =“android.permission.ACCESS_NETWORK_STATE”/> 在我的清单文件中 在上面的代码我的问题是当net启用或禁用时它给出与“net on”(toast message)相同的输出。

4 个答案:

答案 0 :(得分:1)

我在我的申请中做了这个。要真正检查网络连接,请尝试ping或DNS解析 www.google.com

  • 如果ping成功,则表示您已建立Internet连接
  • 如果没有,则表示您没有Internet连接

@Waqas,该问题不涉及连接到路由器但没有Internet访问的情况,因为ConnectivityManager无法区分网络和Internet连接。

答案 1 :(得分:1)

只需尝试以下代码,以便检查是否有互联网连接。这段代码对我有用。你也可以检查互联网是否通过手机连接,然后是否在漫游。

    int typeOfConnection = 0;
    //Gets the system service of the connectivity.
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = connectivityManager.getAllNetworkInfo();

    //Checks whether the connectivity type is WIFI or MOBILE.
    for (NetworkInfo networkInfo : netInfo)
    {
        if (networkInfo.getTypeName().equalsIgnoreCase("WIFI"))
            if (networkInfo.isConnected()){
                                     typeOfConnection = 1;
                 Toast.makeText(getApplicationContext(), "net on", Toast.LENGTH_LONG).show();

            }
        if (networkInfo.getTypeName().equalsIgnoreCase("MOBILE"))
            if (networkInfo.isConnected()){
                                     typeOfConnection = 2;
                 Toast.makeText(getApplicationContext(), "net on", Toast.LENGTH_LONG).show();

            }
    }

    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if(typeOfConnection== 2 && telephonyManager.isNetworkRoaming()){
        typeOfConnection = 3;
    }

    if(typeOfConnection == 0){
                Toast.makeText(getApplicationContext(), "net OFF", Toast.LENGTH_LONG).show();

    }

一切顺利

答案 2 :(得分:1)

在onCreate方法的顶部,使用

if(!checkInternetConnection()){
            // network connnectivity error , show some dialog here and exit from the app 

        }

其中

private boolean checkInternetConnection() {

            ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            // ARE WE CONNECTED TO THE NET
            if (conMgr.getActiveNetworkInfo() != null
                    && conMgr.getActiveNetworkInfo().isAvailable()
                    && conMgr.getActiveNetworkInfo().isConnected()) {

                return true;

            } else {
                Log.v("", "Internet Connection Not Present");
                return false;
            }
        }

希望这会帮助你。

答案 3 :(得分:1)

// check internet connectivity
public static boolean isNetworkAvailable(Context context) {

    boolean networkStatus;
    try {

        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();

        networkStatus = (activeNetworkInfo != null && activeNetworkInfo.isConnected()) ? true : false;

    } catch (Exception e) {

        e.printStackTrace();
        DinotaLogger.log(e, Level.SEVERE);
        networkStatus = false;

    }

    return networkStatus;
}

请确保放入清单文件。如果您使用模拟器进行检查,请按F8以禁用网络访问。这适用于android 2.3.3模拟器。