簡體   English   中英

以編程方式打開Wifi熱點並出現WiFi錯誤

[英]Turning on a Wifi Hotspot programmatically and getting a WiFi Error

我正在使用關於此問題的StackOverflow上一篇文章中的以下代碼,

public static boolean configApState(Context context) {
    WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration wificonfiguration = null;
    try {
        // if WiFi is on, turn it off
        if(isApOn(context)) {
            if (wifimanager != null) {
                wifimanager.setWifiEnabled(false);
            }
        }
        Method method = wifimanager != null ? wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class) : null;



        if (method != null) {
            method.invoke(wifimanager, null, !isApOn(context));
        }else{
            return false;
        }
        return true;
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

看來工作正常。 就我用於靜態IP而言,我正在運行Android 7.0的Android TV Box X96 mini上使用此代碼。 但是當我嘗試自動連接時,Android TV的DHCP為連接設備提供了非常奇怪的IP。

我得到的是169.254.68.26另一方面,如果我嘗試ping通過靜態IP 192.168.43.50連接的設備,則會給我PING:傳輸失敗。 一般失敗。 錯誤信息。

另一方面,如果我嘗試從設置菜單手動啟用wifi熱點,則獲得的IP是正常的,並且ping也可以正常工作。 再次關閉熱點,然后嘗試通過App開啟熱點,然后顯示與上述相同的行為。

有什么我想念的嗎?

這是我正在使用上述功能的服務類

public class MyPersistingService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(getApplicationContext(),""+AppManager.isApOn(getApplicationContext()),Toast.LENGTH_LONG).show();
    if(!AppManager.isApOn(getApplicationContext())) {
        WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifi != null) {
            wifi.setWifiEnabled(false);
            AppManager.configApState(getApplicationContext());
        }else{
            Toast.makeText(getApplicationContext(), "No Wifi Found", Toast.LENGTH_SHORT).show();
        }

    }

    return  START_STICKY;
}}

編輯我在兩種情況下都嘗試了以下功能以獲得IP地址

 public  static  String getIPInfo2(Context context) throws SocketException {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

    String finalIP = "";
    while (interfaces.hasMoreElements())
    {
        NetworkInterface networkInterface = interfaces.nextElement();

        if (networkInterface.isLoopback())
            continue; // Don't want to broadcast to the loopback interface

        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses())
        {
            InetAddress broadcast = interfaceAddress.getBroadcast();

             InetAddress ip = interfaceAddress.getAddress();
            // interfaceAddress.getNetworkPrefixLength() is another way to express subnet mask

            // Android seems smart enough to set to null broadcast to
            //  the external mobile network. It makes sense since Android
            //  silently drop UDP broadcasts involving external mobile network.
            if (broadcast == null)
                continue;

            finalIP = ip.getHostAddress();


        }
    }

    return  finalIP;
}

我觀察到了奇怪的行為。 當我從設置手動進行熱點共享時。 此函數返回192.168.43.1,但是當我通過Code打開wifi時,上述函數返回“”空字符串。

192.168.43.1是設備以編程方式或手動打開熱點時應返回的正確IP地址。 由於Android設備的IP地址不變。

PS: 除非是其Android Pie或Google Pixel設備。

使用以下代碼打開熱點。 這是使用android的私有API的反映。 不建議這樣做,但是如果您沒有其他選擇,則可能要這樣做:

 public boolean setWifiEnabled(WifiConfiguration wifiConfig, boolean enabled) { 
    try {   
      if (enabled) { //disables wifi hotspot if it's already enabled    
        wifiManager.setWifiEnabled(false);  
      } 

       Method method = wifiManager.getClass()   
          .getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);   
      return (Boolean) method.invoke(wifiManager, wifiConfig, enabled); 
    } catch (Exception e) { 
      Log.e(this.getClass().toString(), "", e); 
      return false; 
    }   
  }

這是您可以用來獲取IP地址的代碼。 從API 15到Pie,在所有設備上均可正常運行。 在演示應用程序Spotserve上對其進行了測試。

  private String getIpAddress() {
    Log.v("DANG", "Inside getIpAdress()");
    String ip = "";
    try {
      Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
          .getNetworkInterfaces();
      while (enumNetworkInterfaces.hasMoreElements()) {
        NetworkInterface networkInterface = enumNetworkInterfaces
            .nextElement();
        Enumeration<InetAddress> enumInetAddress = networkInterface
            .getInetAddresses();
        while (enumInetAddress.hasMoreElements()) {
          InetAddress inetAddress = enumInetAddress.nextElement();

          if (inetAddress.isSiteLocalAddress()) {
            ip += inetAddress.getHostAddress() + "\n";
          }
        }
      }
      //To remove extra characters from IP for Android Pie
      if (ip.length() > 14) {
        for (int i = 15, j = 12; i < 18; i++, j++) {
          if ((ip.charAt(i) == '.')) {
            ip = ip.substring(0, j + 1);
            break;
          }
        }
      }
    } catch (SocketException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      ip += "Something Wrong! " + e.toString() + "\n";
    }

    Log.v("DANG", "Returning : " + "http://" + ip);
    return "http://" + ip;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM