gpt4 book ai didi

android - 检测 3G 或 Wifi 网络恢复

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:37 26 4
gpt4 key购买 nike

是否可以实现 PhoneStateListener(或任何其他机制)来检测 3G 或 Wifi 网络连接何时恢复?

我在 API 的摘要中看到 LISTEN_DATA_CONNECTION_STATE 和 LISTEN_DATA_ACTIVITY 都说 (cellular)。这是否意味着只有 3G?

谢谢

最佳答案

更好的方法是使用 android.net.ConnectivityManager 类。注册接收器并监听广播。

private class ConnectionMonitor extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
return;
}
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
NetworkInfo aNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (!noConnectivity) {
if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
|| (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
// Handle connected case
}
} else {
if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
|| (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
// Handle disconnected case
}
}
}
}

private synchronized void startMonitoringConnection() {
IntentFilter aFilter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mConnectionReceiver, aFilter);
}
private synchronized void stopMonitoringConnection() {
unregisterReceiver(mConnectionReceiver);
}

在哪里

mConnectionReceiver = new ConnectionMonitor();

关于android - 检测 3G 或 Wifi 网络恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4503561/

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