我正在开发一个 Android 应用程序,它可以识别设备是否连接到网络。如果没有,应用程序会显示AlertDialog并让用户有机会转到设备设置并打开 wifi。
我已经为这项工作创建了一个BroadcastReceiver,但我不知道如何创建一个AlertDialog并为用户提供启用 wifi 的选项。
这是 的代码BroadcastReceiver。
public class ExampleBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
if (noConnectivity) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("You must have internet connection");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.create();
builder1.show();
} else {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
}
温温酱
相关分类