gpt4 book ai didi

java - 网络不可用时无法显示 Toast 通知

转载 作者:行者123 更新时间:2023-12-02 00:49:53 25 4
gpt4 key购买 nike

我正在尝试通过回调测试网络可用性。

我想在连接不可用时显示 toast 通知。当我可以访问互联网时, onAvailable() 工作正常。

onAvailable() 似乎不起作用。带有消息“无互联网连接”的 Toast 不会显示。

我已经阅读了文档中有关 unAvailable() 的一些信息。提到了超时值。我假设 onUnavailable() 在此超时后被调用。但是,如果它与问题有关,我不知道。

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
Toast.makeText(MainActivity.this, "Request successful", Toast.LENGTH_LONG).show();
}

@Override
public void onUnavailable() {
super.onUnavailable();
Toast.makeText(MainActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
};
final ConnectivityManager connectivityManager
= (ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);


connectivityManager.registerNetworkCallback(new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build(), networkCallback);

最佳答案

Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver in their manifest. Apps will still receive CONNECTIVITY_ACTION broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

这是link寻求解决方案

关于java - 网络不可用时无法显示 Toast 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57868633/

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