检测 3G 或 Wifi 网络恢复 [英] Detect 3G or Wifi Network restoration

查看:27
本文介绍了检测 3G 或 Wifi 网络恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to implement a PhoneStateListener(or any other mechanism) to detect when either the 3G or Wifi network connection is restored ?

我在 API 的摘要中看到 LISTEN_DATA_CONNECTION_STATE 和 LISTEN_DATA_ACTIVITY 都说(蜂窝).是不是只有3G?

I see both LISTEN_DATA_CONNECTION_STATE and LISTEN_DATA_ACTIVITY say (cellular) in the API's summary. Does it mean 3G only ?

谢谢

推荐答案

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

Better approach would be to use android.net.ConnectivityManager class. Register the receiver and monitor broadcasts.

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();

这篇关于检测 3G 或 Wifi 网络恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆