Android App: Display Network Unavailable Warning with AlertDialog
This code demonstrates how to check for network availability and display a warning message using an AlertDialog in an Android app.
public void run() {
if (!isNetworkAvailable()) {
LogHelper.d(TAG, 'Network is not available.');
return;
}
// Display the warning message
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle('Network Warning')
.setMessage('Network is not available.')
.setPositiveButton('Ok', new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
AlertDialog alert = builder.create();
alert.show();
}
Explanation:
- Network Check: The
isNetworkAvailable()method (not shown here) checks if a network connection is available. - Alert Creation: An
AlertDialog.Builderis used to construct the warning message. - Title and Message: The dialog's title is set to 'Network Warning', and the message displays 'Network is not available.'
- Positive Button: A 'Ok' button is added to dismiss the dialog.
- Display Alert: The
alert.show()method displays the AlertDialog to the user.
原文地址: https://www.cveoy.top/t/topic/oOci 著作权归作者所有。请勿转载和采集!