This question already has answers here:
Check INTENT internet connection
                                
                                    (12个答案)
                                
                        
                                2年前关闭。
            
                    
在我们的应用程序中,我们希望能够不断检查连接状态,如果连接状态出现故障,则抛出Toast或某种类型的UI,以向用户指示连接状态已下降。每当进行API调用时,我都尝试在Retrofit Api-Builder类中执行此操作,但它似乎并不喜欢Toasts(导致崩溃)。

iOS具有监视功能,但似乎在Android上,我们必须手动进行检查。考虑到存在多个活动等,是否有一种简单/干净的方法可以在我们的应用程序中执行此操作?

最佳答案

这就是我监视互联网连接状态的方法。创建一个Java类,并将其命名为NetworkStateChangeReceiver

NetworkStateChangeReceiver

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import static android.content.Context.CONNECTIVITY_SERVICE;

public class NetworkStateChangeReceiver extends BroadcastReceiver {
public static final String NETWORK_AVAILABLE_ACTION = "yourapp.packagename.NetworkAvailable";
public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";

@Override
public void onReceive(Context context, Intent intent) {
    Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
    networkStateIntent.putExtra(IS_NETWORK_AVAILABLE,  isConnectedToInternet(context));

LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
}

private boolean isConnectedToInternet(Context context) {
    try {
        if (context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
        }
        return false;
    } catch (Exception e) {
        Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
        return false;
    }
}
}


在您的MainActivity中,添加以下行。

IntentFilter intentFilter = new
IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
    LocalBroadcastManager.getInstance(this).registerReceiver(new
BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
            String networkStatus = isNetworkAvailable ? "Connected!" : "Disconnected!";

            final SweetAlertDialog CC = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE);
            CC.setTitleText("Network Status");
            CC.setContentText(networkStatus);
            CC.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
            CC.setCancelable(false);
            CC.show();


您可以使用简单的Alertdialog或Toast来显示消息。我使用SweetAlertDialog Library来获得更清晰的用户界面。

08-03 18:32