gpt4 book ai didi

android - 我在注册 BroadcastReceiver 后立即收到 "android.net.wifi.WIFI_STATE_CHANGED"

转载 作者:行者123 更新时间:2023-11-29 23:27:29 30 4
gpt4 key购买 nike

我在运行时注册一个广播以接收“android.net.wifi.WIFI_STATE_CHANGED”

   IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
broadcastReceiverAction = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.net.wifi.WIFI_STATE_CHANGED")) {
/*I get this action as soon as calling registerReceiver(broadcastReceiverAction, intentFilter);*/
}
}
}
registerReceiver(broadcastReceiverAction, intentFilter);

问题:这会在注册接收器后立即获取广播操作。我在 Android API 26 & Higher 上得到了这个,我不能在 list 中声明“android.net.wifi.WIFI_STATE_CHANGED”。 (Android系统不再支持)

最佳答案

要检查网络连接状态更改,您可以通过编程方式进行。它支持 API 21+。

    public class ConnectionStateMonitor extends ConnectivityManager.NetworkCallback {
public final String TAG = ConnectionStateMonitor.class.getSimpleName();
private boolean isLost = false;


final NetworkRequest networkRequest;
Context context;
private ConnectionStateMonitor instance;
private boolean isLost = false;

private ConnectionStateMonitor() {
networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();
}

public synchronized ConnectionStateMonitor getInstance() {
if (instance == null) {
instance = new ConnectionStateMonitor();
}
return instance;
}

public void enable(Context context) {
try {
if (context == null) return;
this.context = context;
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.registerNetworkCallback(networkRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void onAvailable(Network network) {
Log.i(TAG, "onAvailable called " +
network.toString());
if (isLost) {
isLost = false;}
// when network available called it
}


@Override
public void onLost(Network network) {
super.onLost(network);
isLost = true;
// when network lost called it
Log.i(TAG, "onLost called ");
}
}

关于android - 我在注册 BroadcastReceiver 后立即收到 "android.net.wifi.WIFI_STATE_CHANGED",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53311657/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com