当Android应用程序中的互联网连接不可用时显示警报

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10242351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:58:22  来源:igfitidea点击:

Display an alert when internet connection not available in android application

androidalert

提问by ZooZoo

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 messege that no internet connection available. i am using following code. but its not working.

在我的应用程序中,数据来自互联网,我正在尝试创建一个函数来检查互联网连接是否可用,如果不可用,它会发出警报消息,表明没有可用的互联网连接。我正在使用以下代码。但它不工作。

public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main1);
  if (isOnline())
  {
   // my code
  }
  else
  {
   Hotgames4meActivity1.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); 
    try {
       AlertDialog alertDialog = new AlertDialog.Builder(Hotgames4meActivity1.this).create();

       alertDialog.setTitle("Info");
       alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
       //alertDialog.setIcon(R.drawable.alerticon);
       alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          finish();

         }
       });

       alertDialog.show();
    }
    catch(Exception e)
    {
       //Log.d(Constants.TAG, "Show Dialog: "+e.getMessage());
    }
  }
}

采纳答案by Sandeep

public void onCreate(Bundle obj) {
    super.onCreate(obj)
    setContextView(layout);

    if (isOnline()) {
        //do whatever you want to do 
    } else {
        try {
            AlertDialog alertDialog = new AlertDialog.Builder(con).create();

            alertDialog.setTitle("Info");
            alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
            alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }
            });

            alertDialog.show();
        } catch (Exception e) {
            Log.d(Constants.TAG, "Show Dialog: " + e.getMessage());
        }
    }
}

回答by vtuhtan

public boolean isOnline() {
    ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = conMgr.getActiveNetworkInfo();

    if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
        Toast.makeText(context, "No Internet connection!", Toast.LENGTH_LONG).show();
        return false;
    }
return true; 
}

And you must add premission for accessing network state and Internet:

并且您必须添加访问网络状态和 Internet 的权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

回答by Ishan Fernando

You can use these methods anywhere

您可以在任何地方使用这些方法

public void checkNetworkConnection(){
    AlertDialog.Builder builder =new AlertDialog.Builder(this);
    builder.setTitle("No internet Connection");
    builder.setMessage("Please turn on internet connection to continue");
    builder.setNegativeButton("close", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

public boolean isNetworkConnectionAvailable(){
    ConnectivityManager cm =
            (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnected();
    if(isConnected) {
        Log.d("Network", "Connected");
        return true;
        }
    else{
        checkNetworkConnection();
        Log.d("Network","Not Connected");
        return false;
    }
}

when you need to check connection available call isNetworkConnectionAvailable() method.If the network not available it will pop up your dialog box. If you need to check network in multiple screen add these methods to the super class and inherit that class to other class and call this method when need

当您需要检查连接可用时调用 isNetworkConnectionAvailable() 方法。如果网络不可用,它将弹出您的对话框。如果您需要在多个屏幕中检查网络,请将这些方法添加到超类并将该类继承到其他类并在需要时调用此方法

回答by sampathpremarathna

try this

尝试这个

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        android.net.NetworkInfo wifi = cm
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        android.net.NetworkInfo datac = cm
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if ((wifi != null & datac != null)
                && (wifi.isConnected() | datac.isConnected())) {
                //connection is avlilable
                 }else{
                //no connection
                  Toast toast = Toast.makeText(context, "No Internet Connection",
                Toast.LENGTH_LONG);
        toast.show();  
                }

and don't forget to add following permssions

并且不要忘记添加以下权限

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

回答by Boe-Dev

Maybe try this

也许试试这个

handler.removeCallbacks(checkInternetConnection);
                handler.postDelayed(checkInternetConnection, UPDATE_INTERVAL); 



    public Runnable checkInternetConnection = new Runnable() {

            public void run() {

                handler.postDelayed(checkInternetConnection, UPDATE_INTERVAL);
                ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

                if(conMgr.getActiveNetworkInfo()!=null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()){
                    alertOff();

                }
                else{
                    alertOn();
                }

            }
        };

回答by Dan Jurgen

The above method just informs you whether your mobile has the possibility to connect to the internet, however, it does not tell exactly if connectivity exists.. for example, you might be able to connect to a wifi, but be in a coffee shop where you should enter credentials into a hot spot website... or , your home wifi might be working, and you are connected to it, but cannot access internet. Use the below code to check for internet connetivity. it is preferable to use this inside an asynctask.

上面的方法只是告诉你你的手机是否有可能连接到互联网,但是,它并不能确切地告诉你是否存在连接......例如,你可能能够连接到 wifi,但在咖啡店里您应该在热点网站中输入凭据...或者,您的家庭 wifi 可能正在工作,并且您已连接到它,但无法访问互联网。使用以下代码检查互联网连接。最好在异步任务中使用它。

public boolean hasActiveInternetConnection()
{
        try
        {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(4000);
            urlc.setReadTimeout(4000);
            urlc.connect();
            networkcode2 = urlc.getResponseCode();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e)
        {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }

} 

回答by user2914699

public boolean isOnline() 
{


ConnectivityManager connectionManager;

if(app_context!=null)

connectionManager = (ConnectivityManager) app_context.getSystemService(Context.CONNECTIVITY_SERVICE);

        else
            return false;

        try 
        {
            if (connectionManager.getActiveNetworkInfo().isConnected()) 
            {
                Log.e(THIS_FILE, "Communicator ....isConnected()");
                return true;
            } 
            else
            { 
                Log.e(THIS_FILE, "Communicator ....isNotConnected()");
                return false;
            }
        } 
        catch (NullPointerException e) 
        {
            Log.e(THIS_FILE, "No Active Connection");
            return false;
        }
    }

set permission in manifest

在清单中设置权限

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

回答by Sam

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

if(!isNetworkAvailable()){
        //Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
        new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Closing the App")
        .setMessage("No Internet Connection,check your settings")
        .setPositiveButton("Close", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();    
        }

    })
    .show();
    }

回答by Mahesh Gawhane

This is working in my code, try this:

这在我的代码中有效,试试这个:

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (hasConnection(MainActivity.this)){
         //call methods
         //getJsonData();
      }
    else{
        showNetDisabledAlertToUser(MAinActivity.this);
    }
}

 public boolean hasConnection(Context context){
   ConnectivityManager cm=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);             
    NetworkInfowifiNetwork=cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()){
        return true;
    }          
   NetworkInfo mobileNetwork=cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()){
        return true;
    }
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()){
        return true;
    }
    return false;
}

public static void showNetDisabledAlertToUser(final Context context){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_TRADITIONAL);
    alertDialogBuilder.setMessage("Would you like to enable it?")
            .setTitle("No Internet Connection")
            .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();
}

回答by Mahesh Gawhane

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();
}