How to display dialog when internet connection not

2019-06-07 16:16发布

I am creating an android app. I need to display a dialog when internet connection is not available.I don't need to write network connection check in every activity . how to implement this using services in android?

1条回答
女痞
2楼-- · 2019-06-07 17:18

Create a class nameed CheckConnection as bellow

Than you call this class where you want to check is INTERNET connection available or not

Code

public class ConnectionCheck {

    public boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }

    public AlertDialog.Builder showconnectiondialog(Context context) {

        final AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("Error!")
                .setCancelable(false)
                .setMessage("No Internet Connection.")
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });

        return builder;
    }
}

Call above class where you want to check Internet connection: as above line

ConnectionCheck connectionCheck = new ConnectionCheck();
        if (connectionCheck.isNetworkConnected(this)){// or your context pass here
            //operation you want if connection available
        }else {
            connectionCheck.showconnectiondialog(this);  //context pass here
        }

And you must add Permission for accessing network state and Internet in to ManifestActivity.xml:

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
查看更多
登录 后发表回答