知道网络连接何时返回

时间:2010-12-11 20:18:47

标签: android

我有一个试图成为一个好撒玛利亚人的应用程序,基本上当任何需要与网络交互的服务启动时。我正在检查设备是否有连接:

hasConnectivity方法

private boolean hasConnectivity() {
    NetworkInfo info = mConnectivity.getActiveNetworkInfo();
    boolean connected = false;
    int netType = -1; 
    int netSubtype = -1; 

    if (info == null) {
        Log.w(sTag, "network info is null");
        notifyUser(MyIntent.ACTION_VIEW_ALL, "There is no network connectivity.", false);
    } else if (!mConnectivity.getBackgroundDataSetting()) {
        Log.w(sTag, "background data setting is not enabled");
        notifyUser(MyIntent.ACTION_VIEW_ALL, "background data setting is disabled", false);
    } else {
        netType = info.getType();
        netSubtype = info.getSubtype();

        if (netType == ConnectivityManager.TYPE_WIFI) {
            connected = info.isConnected();
        } else if (netType == ConnectivityManager.TYPE_MOBILE
                   && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
                   && !mTelephonyManager.isNetworkRoaming()
                  ) { 
            connected = info.isConnected();
        } else if (info.isRoaming()) {
            notifyUser(MyIntent.ACTION_VIEW_ALL, "Currently Roaming skipping check.", false);
        } else if (info.isAvailable()) {
            connected = info.isConnected();
        } else {
            notifyUser(MyIntent.ACTION_VIEW_ALL, "..There is no network connectivity.", false);
        }   
    }   
    return connected;
} 

当此方法返回false时,我知道我没有连接,因为用户在手机上或3g且wifi无法使用

什么是最好的方式来了解何时连接可用而不定期用定时器拉出网络统计数据?

我是否可以通过广播接收器观察到的Intent动作,该接收器会通过连接宣布更改?

感谢您提供任何帮助,我将继续搜索文档以获取有关下一步操作的一些线索。

1 个答案:

答案 0 :(得分:3)

这是我检查互联网访问权限(实际上,更像是启用了Wifi并连接到网络)。

public class ConnectivityReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if(action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION))
    {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        MainMap.setWifiState(wm.getWifiState());
        Log.e("Debug", "Setting wifistate: " + wm.getWifiState());
    } else if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
    {
        NetworkInfo ni = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        MainMap.setConnected(ni.isConnected());
        Log.e("Debug", "Setting isConnected: " + ni.isConnected());
        if(ni.isConnected()) Toast.makeText(context, "Connected!", Toast.LENGTH_LONG).show();
    }
}

}

检查用户是使用3G还是使用Wifi应该不会太难。