15

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

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

15 回答 15

15
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; 
}

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

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
于 2012-04-20T08:16:09.853 回答
7
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());
        }
    }
}
于 2012-04-20T08:49:47.920 回答
7

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

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

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

于 2016-09-23T06:36:11.713 回答
2

尝试这个

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

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

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2012-04-20T08:04:34.237 回答
1

也许试试这个

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

            }
        };
于 2012-04-20T09:01:23.937 回答
1

试试这个我用于我的专业应用程序

import androidx.appcompat.app.AlertDialog;

import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class MainActivity extends AppCompatActivity {    

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

        if (isOnline()) {
             // Do you Stuff
        } else {
            try {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Error")
                        .setMessage("Internet not available, Cross check your internet connectivity and try again later...")
                        .setCancelable(false)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();

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

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

        if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
            return false;
        }
        return true;
    }
}
于 2020-10-02T09:15:50.137 回答
0
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();
    }
于 2014-09-24T15:27:23.787 回答
0

在 manifest.xml 中添加权限

 <uses-permission android:name="android.permission.INTERNET" />
于 2012-04-20T08:01:47.817 回答
0
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;
        }
    }

在清单中设置权限

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2014-02-19T05:49:58.893 回答
0

上面的方法只是告诉你你的手机是否有可能连接到互联网,但是,它并不能准确地告诉你是否存在连接。例如,你可能能够连接到 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;
        }

} 
于 2013-02-15T11:25:13.607 回答
0

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

@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();
}
于 2016-03-19T05:06:32.393 回答
0

2021 年 22 月 - 沃金代码 - 没有最佳实践的互联网

创建一个类并使用 Application 扩展

     public class App extends Application {
    
        private static App instance;
    
        public static App getInstance() {
            return instance;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            instance = this;
        }
    
        public static boolean isOnline() {
            ConnectivityManager connectivityManager = (ConnectivityManager) instance.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null;
        }
}

在你的 AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:name=".App"... // "name" add your app class inside application 
      Tag.

现在调用你的活动

if (App.isOnline()){
        //todo task
    }else{
        if (pBar != null && pBar.getVisibility() == View.VISIBLE) pBar.setVisibility(View.GONE);
        Toast.makeText(App.getInstance(), "No Internet", Toast.LENGTH_SHORT).show();
    }
于 2021-12-05T08:26:56.897 回答
0

此代码工作正常如果 Intenet 可用,则顺利启动应用程序如果没有,则弹出一个对话框,要求打开或退出应用程序

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.setPositiveButton("Turn On", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MainActivity.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            }).show();

    builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finishAffinity();
        }
    }).show();

    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;
    }
}
于 2020-03-02T10:37:36.590 回答
0

如果您想在连接丢失时显示警报。您可以使用以下方法。

此方法用于检查一次连接。首先,您必须在您的班级中创建这个。

private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if(!(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected())){
            showNetworkDialog();
            return false;
        }
        return true;
    }

在您的类中创建此方法作为连接侦听器。

private void ConnectionCheck(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkRequest networkRequest = new NetworkRequest.Builder().build();
            connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    super.onAvailable(network);
                    Log.i("Tag", "active connection");
                }

                @Override
                public void onLost(Network network) {
                    super.onLost(network);
                    Log.i("Tag", "losing active connection");
                    isNetworkConnected();
                }
            });
        }
    }

为了显示对话框,您可以创建 showDialog() 方法。您可以添加 2 个按钮。重试并退出

private void showNetworkDialog(){
    new AlertDialog.Builder(MainActivity.this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Connection lost?")
            .setMessage("Please check your internet connection!")
            .setCancelable(false)
            .setPositiveButton("Exit", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            })
            .setNegativeButton("Retry", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    isNetworkConnected();
                }
            })
            .show();
}

最后,您可以在 onCreate() 方法中调用此方法。

if(isNetworkConnected()){
            ConnectionCheck();
        }

在清单文件中,您必须提及权限。

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2021-03-07T13:54:53.697 回答
0

在您的 create 方法中编写此代码

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();
}
于 2016-04-04T11:37:00.917 回答