简体   繁体   中英

Failed to check internet connectivity (Android)?

I am fetching the data from server in my android app, while checking Internet connection the app crashes when there is no Internet connection. I am using the default http connection for connecting to the server.

The code to check Internet connection is:

public void onClick(View view) {
    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        //if it is connected to internet than start Another Activity.
        startActivity(new Intent(SearchActivity.this, SearchActivity.class));
    } else if (netInfo == null) {
        AlertDialog alertDialog = new AlertDialog.Builder(ListViewExample.this).create();
        alertDialog.setTitle("Connection Problem");
        alertDialog.setMessage("You are not connected to Internet");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        alertDialog.show();
    }

}

确保您已在清单文件中添加了此权限,

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Use This code to check internet connection, it check all the internet connection over device. And Make Sure you have added Internet Permission in menifest.

        boolean flag=false;
        ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().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)
                    {
                        flag=true;

                    }

        }
        if(flag==true)
        {
             startActivity(new Intent(SearchActivity.this, SearchActivity.class));
        }
        else
        {
             AlertDialog alertDialog = new AlertDialog.Builder(ListViewExample.this).create();
        alertDialog.setTitle("Connection Problem");
        alertDialog.setMessage("You are not connected to Internet");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        alertDialog.show();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM