我正在尝试通过内部wifi网络将远程信息发送到App Center,但不是在此网络上发送,而是在任何外部网络上发送。调试发现设备连接到内部wifi时未调用Method onAvailable(),但连接到任何外部wifi时都会调用它。
以下代码来自App Center SDK:
appcenter \ utils \ NetworkStateHelper.javaNetworkStateHelper.java。
类NetworkStateHelper->方法reopen()-> public void onAvailable(网络)方法
示例代码:
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方法。
答案 0 :(得分:1)
您必须将网络类型限制为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" />
答案 1 :(得分:0)
如Android docs中所述:
针对Android 7.0(API级别24)及更高版本的应用不会收到 CONNECTIVITY_ACTION广播,如果它们声明了广播接收者 在他们的清单上。应用仍将获得CONNECTIVITY_ACTION 如果他们向其注册了BroadcastReceiver广播 Context.registerReceiver(),并且该上下文仍然有效。
这意味着,如果您的目标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....
}
};