如何可靠地检查 Android 的网络连接?

问题描述 投票:0回答:1

我试图弄清楚如何让我的应用程序定期检查设备是否连接到网络。我有以下用于网络检查的代码:

public class NetworkHelper {

    private static final String TAG = "NetworkHelper";
    
    public static boolean isDeviceConnectedToNetwork(Context context) {
        boolean isConnected = false;
    
        try {
            ConnectivityManager cm = (ConnectivityManager)
                 context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
            Log.d(TAG, "Checking network: " + isConnected);
            return isConnected;
        } catch (NullPointerException e) {
            return false;
        }
    }

以下代码用于定期调用NetworkHelper:

public class MQTTConnectionFragment extends Fragment {

    ...

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
        networkCheckerThread = new HandlerThread("NetworkCheckerThread");
        networkCheckerThread.start();
    
        networkCheckerHandler = new Handler(networkCheckerThread.getLooper());
        networkCheckerRunnable = () -> {
            Log.d(TAG, "Running network check");
            boolean isConnected = NetworkHelper.isDeviceConnectedToNetwork(getContext());
            getActivity().runOnUiThread(() -> {
                 if (isConnected) {
                     connectionBox.setVisibility(View.VISIBLE);
                     disconnectButton.setVisibility(View.GONE);
                     loadingWheel.setVisibility(View.GONE);
                     noNetworkTextView.setVisibility(View.GONE);
                 } else {
                     connectionBox.setVisibility(View.GONE);
                     disconnectButton.setVisibility(View.GONE);
                     loadingWheel.setVisibility(View.GONE);
                     noNetworkTextView.setVisibility(View.VISIBLE);
                 }
                  networkCheckerHandler.postDelayed(networkCheckerRunnable,
                                                isConnected ? 5000 : 3000);
             });
        };
        
        networkCheckerHandler.postDelayed(networkCheckerRunnable, 200);
        
        return view;
    
    }
    ...
}

日志不断报告我始终保持连接,即使我关闭 Wi-Fi 也是如此。难道是因为我使用的是 AVD?或者是我的代码中我没有看到的东西?我有一段时间无法使用物理设备,认为在 AVD 上进行测试就可以了。

java android network-programming
1个回答
-1
投票

尝试使用 BroadcastReceiver 监听网络连接变化。供参考android-listening-to-connectivity-changes-the- Correct-way

© www.soinside.com 2019 - 2024. All rights reserved.