wifi状态返回false即使它已连接

时间:2014-11-24 16:54:23

标签: android android-wifi wifimanager

我在应用程序的onStart上检查手机wifi状态,但即使它连接它返回false,我已经尝试了很多东西但是没有工作

这就是我正在做的事情

@Override protected void onStart() {
    super.onStart();
    onStartStates();
 }

onStartStates()方法

 private void onStartStates(){

   ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo net = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    Log.d(TAG, "Wifi State 1"+net.isConnected());
    Log.d(TAG, "Wifi State 2"+getCurrentSsid(esActivity.this));
}

getCurrentSsid()方法

 public static String getCurrentSsid(Context context) {
    WifiInfo wifiInfo = getCurrentWifiInfo(context);
    if (wifiInfo != null) {
        return wifiInfo.getSSID();
    }
    return null;
}

public static WifiInfo getCurrentWifiInfo(Context context) {
    final ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo != null && networkInfo.isConnected()) {
        final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wifiManager.getConnectionInfo();
    }

    return null;
}

两种方法都返回false,即使我切换wifi也只是启动我的应用程序...任何想法

1 个答案:

答案 0 :(得分:0)

尝试以下方法来检测设备是否具有网络连接。 获得当前活跃的网络可能对您有所帮助。

/**
 * Check for <code>TYPE_WIFI</code> and <code>TYPE_MOBILE</code> connection
 * using <code>isConnected()</code> Checks for generic Exceptions and writes
 * them to LogCat as <code>CheckConnectivity Exception</code>. Make sure
 * AndroidManifest.xml has appropriate permissions.
 * 
 * @param con
 *            Application context
 * @return Boolean
 */
public static boolean hasConnectivity(Context con)
{
    ConnectivityManager connectivityManager;
    NetworkInfo         wifiInfo;
    NetworkInfo mobileInfo;
    try
    {
        connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
        boolean serviceAvailable = (netInfo!=null && netInfo.isConnected())? true:false;

        wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (wifiInfo.isConnected() || mobileInfo.isConnected() || serviceAvailable) 
        { 
            Logger.info(TAG + " : " + true);
            return true; 
        }
    }
    catch (Exception e)
    {
        Logger.info(TAG + ": hasConnectivity: Exception: " + e.getMessage());
    }
    Logger.error(TAG + " : " + false);
    return false;
}