3 回答
TA贡献1883条经验 获得超3个赞
更新:
如果目标为Android 7.0(API级别24)及更高版本的应用在清单中声明了广播接收器,则不会接收CONNECTIVITY_ACTION广播。如果应用向Context.registerReceiver()注册其BroadcastReceiver,并且该上下文仍然有效,则它们仍将接收CONNECTIVITY_ACTION广播。
您需要通过registerReceiver()方法注册接收器:
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
mCtx.registerReceiver(new NetworkBroadcastReceiver(), intentFilter);
TA贡献1865条经验 获得超7个赞
api 28+中已弃用 ConnectivityAction 。相反registerDefaultNetworkCallback,只要支持api 24+,就可以使用。
在科特林:
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
//take action when network connection is gained
}
override fun onLost(network: Network?) {
//take action when network connection is lost
}
})
}
添加回答
举报