override fun setR2SettingData(cmd: String, status: String) {
val requestbuilder = NetworkRequest.Builder()
requestbuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
connectivityManager.requestNetwork(
requestbuilder.build(),
object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
val builder1 = OkHttpClient.Builder()
builder1.socketFactory(network.socketFactory)
val apiService =
RetrofitInstance.getApiServiceXMLForR2(
Constants.BASE_URL_CAMERA_R2,
builder1
)
trackDisposable(
apiService.requestCameraR2URLForSettingResponse(cmd, status)
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui())
.subscribe()
)
}
})
}
这段代码我正在使用网络调用,当我们调用API时,我收到以下错误:android.net.ConnectivityManager$TooManyRequestsException
Process: com.rovedashcam.android, PID: 25285
android.net.ConnectivityManager$TooManyRequestsException
at android.net.ConnectivityManager.convertServiceException(ConnectivityManager.java:3378)
at android.net.ConnectivityManager.sendRequestForNetwork(ConnectivityManager.java:3564)
at android.net.ConnectivityManager.requestNetwork(ConnectivityManager.java:3585)
at android.net.ConnectivityManager.requestNetwork(ConnectivityManager.java:3661)
at android.net.ConnectivityManager.requestNetwork(ConnectivityManager.java:3622)
at
connectivityManager.requestNetwork
谁能告诉我为什么我得到这个错误?
我已经尝试通过整合connectivityManager
与fragment
生命周期方法来解决这个问题
这是我的实现。
-
创建类属性
private var connectivityManager:ConnectivityManager? = null private val connectionCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) {//perform your stuff} override fun onLost(network: Network) {//perform your stuff} }
-
在
onCreateView()
中初始化并注册ConnectivityManager
connectivityManager = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager connectivityManager?.registerDefaultNetworkCallback(connectionCallback)
-
onPause()/onStop()/onDestroy()
中的unregisterNetworkCallback
基于您的要求connectivityManager?.unregisterNetworkCallback(connectionCallback)