Android Network Availability Check and Alert Dialog
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:
- Network Availability Check: The
isNetworkAvailable()method checks if the device has an active internet connection. If not, it logs a message and returns. - AlertDialog Creation: An
AlertDialog.Builderis used to construct the alert dialog. - Dialog Title and Message: The
setTitle()andsetMessage()methods set the title and message of the dialog, respectively. - Positive Button: The
setPositiveButton()method adds a positive button labeled 'OK' to the dialog. TheonClick()listener handles the button click, which in this case does nothing. - Show AlertDialog: The
create()method builds the alert dialog, and theshow()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
LogHelperclass is assumed to be a custom logging utility. You can use any logging framework of your choice.
原文地址: https://www.cveoy.top/t/topic/oOcs 著作权归作者所有。请勿转载和采集!