Display an alert when internet connection not available in android application

后端 未结 13 777
有刺的猬
有刺的猬 2020-12-08 11:48

In my application data comes from internet and I am trying to create a function that checks if a internet connection is available or not and if it isn\'t, it gives an alert

13条回答
  •  无人及你
    2020-12-08 12:22

    write this code in your create method

    if (internetConnection.hasConnection(BankAccount.this))
    {
       // call your methods
    }
    
    else
    {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        alertDialogBuilder
                .setMessage("No internet connection on your device. Would you like to enable it?")
                .setTitle("No Internet Connection")
                .setCancelable(false)
                .setPositiveButton(" Enable Internet ",
                        new DialogInterface.OnClickListener()
                        {
    
                            public void onClick(DialogInterface dialog, int id)
                            {
                                Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                                dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(dialogIntent);
                            }
                        });
    
        alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {
                dialog.cancel();
            }
        });
    
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
    

提交回复
热议问题