我试图查看用户是否可以上网。 当用户没有互联网时,它会显示一个带有消息的对话框,但是如果他触摸对话框之外,则该对话框将不执行任何操作。
我尝试过:
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isConnected())
{
new AlertDialog.Builder(this)
.setTitle("No internet")
.setMessage("Message ")
.setPositiveButton("Close", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int w) {
finish();
}
})
.show();
}
}
private boolean isConnected()
{
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
答案 0 :(得分:2)
使用这个:
new AlertDialog.Builder(this)
.setTitle("No internet")
.setCancelable(false)
.setMessage("Message ")
.setPositiveButton("Close", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int w) {
finish();
}
})
.show();