8

我正在尝试通过内部 wifi 网络将远程数据发送到 App Center,但它不在此网络上发送,但它在任何外部网络上发送。调试时发现当设备连接到内部 wifi 时不会调用方法 onAvailable(),但在连接到任何外部 wifi 时会调用它。

以下代码来自 App Center SDK:
appcenter\utils\NetworkStateHelper.javaNetworkStateHelper.java。类 NetworkStateHelper -> 方法重新打开() -> public void onAvailable(Network network) 方法

示例代码:

private ConnectivityManager.NetworkCallback mNetworkCallback = new ConnectivityManager.NetworkCallback() 
{

    @Override
    public void onAvailable(Network network) {
        onNetworkAvailable(network);
    }

    @Override
    public void onLost(Network network) {
        onNetworkLost(network);
    }
};

当连接到内部 wifi 网络时,它应该调用 onAvailable 方法。

4

2 回答 2

8

您必须将网络类型限制为Wifi

1.构建NetworkRequest

val networkRequest = getNetworkRequest()

private fun getNetworkRequest(): NetworkRequest {
    return NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)    //here!!
        .build()
}

2. 构建NetworkCallback

val networkCallback = getNetworkCallBack()

private fun getNetworkCallBack(): ConnectivityManager.NetworkCallback {
    return object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {    //when Wifi is on
            super.onAvailable(network)

            Toast.makeText(requireContext(), "Wifi is on!", Toast.LENGTH_SHORT).show()
        }

        override fun onLost(network: Network) {    //when Wifi 【turns off】
            super.onLost(network)

            Toast.makeText(requireContext(), "Wifi turns off!", Toast.LENGTH_SHORT).show()
        }
    }
}

3.注册和注销:

fun getConnectivityManager() = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

override fun onResume() {    //start monitoring when in the foreground
    super.onResume()

    getConnectivityManager().registerNetworkCallback(networkRequest, networkCallback)
}

override fun onPause() {    //stop monitoring when not fully visible
    super.onPause()

    getConnectivityManager().unregisterNetworkCallback(networkCallback)
}

4.不要忘记许可:

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

演示:https ://youtu.be/RPRcGbuB6eI

于 2021-03-10T21:12:07.603 回答
2

正如 android文档中所写:

面向 Android 7.0(API 级别 24)及更高版本的应用如果在其清单中声明广播接收器,则不会接收 CONNECTIVITY_ACTION 广播。如果应用程序使用 Context.registerReceiver() 注册其 BroadcastReceiver 并且该上下文仍然有效,则应用程序仍将接收 CONNECTIVITY_ACTION 广播。

这意味着如果您的目标 api 高于 24,您需要在活动开始时注册广播接收器。

在你的活动中onCreate()

IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityReceiver, intentFilter);

声明广播:

private BroadcastReceiver connectivityReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      //check state here....
    }
  };
于 2019-02-05T07:21:26.883 回答