Android Network Availability Check and Alert Dialog

This code snippet demonstrates how to check for network availability in Android and display an alert dialog if the network is unavailable.

public void run() {
    if (!isNetworkAvailable()) {
        LogHelper.d(TAG, 'Network is not available.');
        
        return;
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle('Network Unavailable');
    builder.setMessage('Please check your internet connection.');
    builder.setPositiveButton('OK', new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // do nothing
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

Explanation:

  1. Network Availability Check: The isNetworkAvailable() method checks if the device has an active internet connection. If not, it logs a message and returns.
  2. AlertDialog Creation: An AlertDialog.Builder is used to construct the alert dialog.
  3. Dialog Title and Message: The setTitle() and setMessage() methods set the title and message of the dialog, respectively.
  4. Positive Button: The setPositiveButton() method adds a positive button labeled 'OK' to the dialog. The onClick() listener handles the button click, which in this case does nothing.
  5. Show AlertDialog: The create() method builds the alert dialog, and the show() method displays it to the user.

Usage:

This code can be used in any Android activity or fragment where you want to check network availability and display an alert if the network is unavailable. You can customize the dialog title, message, and button text to fit your specific needs.

Note:

  • The isNetworkAvailable() method is not shown in this code snippet. You will need to implement it based on your application's requirements.
  • The LogHelper class is assumed to be a custom logging utility. You can use any logging framework of your choice.
Android Network Availability Check and Alert Dialog

原文地址: https://www.cveoy.top/t/topic/oOcs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录