How to check currently internet connection is available or not in android

前端 未结 18 1432
轮回少年
轮回少年 2020-12-04 15:40

I want to execute my application offline also, so I need to check if currently an internet connection is available or not. Can anybody tell me how to check if internet is av

18条回答
  •  不思量自难忘°
    2020-12-04 16:04

    This will show an dialog error box if there is not network connectivity

        ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    
        if (networkInfo != null && networkInfo.isConnected()) {
            // fetch data
        } else {
            new AlertDialog.Builder(this)
                .setTitle("Connection Failure")
                .setMessage("Please Connect to the Internet")
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
        }
    

提交回复
热议问题