1. 程式人生 > >Android 開啟WiFi 熱點的一些適配方案

Android 開啟WiFi 熱點的一些適配方案

前言

博主又來更新文章了,有點墨跡哈,很久才來一篇文章,不講究文章量的大小,只在乎內容的實用性,幫助每一個開發者,避過一些不必要的坑,廢話不多說了,文章的內容就是說各種版本手機通過程式碼如何開啟熱點,文章也比較簡潔,不會有太多的囉嗦話

不同版本開啟熱點的方式

首先呢,通過Android 對應Api的原始碼(哈哈哈上來就原始碼,不看原始碼怎麼知道開熱點啊)就可以找到如何開熱點的,在我們手機的設定頁面肯定會有開啟熱點的功能,然後呢 就去找對於版本號的Api, 程式碼我就貼出來了,簡潔的程式碼 有興趣的同學可以去原始碼官網檢視TetherSettings.java 原始碼

  • 6.0之前的開啟wifi 熱點的方式
 public void onClick(DialogInterface dialogInterface, int button) {
       if (button == DialogInterface.BUTTON_POSITIVE) {
           mWifiConfig = mDialog.getConfig();
           if (mWifiConfig != null) {
               /**
                * if soft AP is stopped, bring up
                * else
restart with new config * TODO: update config on a running access point when framework support is added */ if (mWifiManager.getWifiApState() == WifiManager.WIFI_AP_STATE_ENABLED) { mWifiManager.setWifiApEnabled(null, false); mWifiManager.setWifiApEnabled(mWifiConfig, true
); } else { mWifiManager.setWifiApConfiguration(mWifiConfig); } int index = WifiApDialog.getSecurityTypeIndex(mWifiConfig); mCreateNetwork.setSummary(String.format(getActivity().getString(CONFIG_SUBTEXT), mWifiConfig.SSID, mSecurityType[index])); } } } 複製程式碼

從原始碼上可以看到 開啟熱是通過wifimanager setWifiApEnabled的方式走的

  • 8.0之後開啟wifi熱點的方式
 public void onClick(DialogInterface dialogInterface, int button) {
       if (button == DialogInterface.BUTTON_POSITIVE) {
           mWifiConfig = mDialog.getConfig();
           if (mWifiConfig != null) {
               /**
                * if soft AP is stopped, bring up
                * else restart with new config
                * TODO: update config on a running access point when framework support is added
                */
               if (mWifiManager.getWifiApState() == WifiManager.WIFI_AP_STATE_ENABLED) {
                   Log.d("TetheringSettings",
                           "Wifi AP config changed while enabled, stop and restart");
                   mRestartWifiApAfterConfigChange = true;
                   mCm.stopTethering(TETHERING_WIFI);
               }
               mWifiManager.setWifiApConfiguration(mWifiConfig);
               int index = WifiApDialog.getSecurityTypeIndex(mWifiConfig);
               mCreateNetwork.setSummary(String.format(getActivity().getString(CONFIG_SUBTEXT),
                       mWifiConfig.SSID,
                       mSecurityType[index]));
           }
       }
   }

複製程式碼

從上面的程式碼可以看到變了,變得不認識了,不是通過wifiManager的方式走的了,而是通過更新config 檔案然後通過別的方式來開啟熱點的,下面的程式碼就是開啟熱點的方式。

 private void startTethering(int choice) {
       if (choice == TETHERING_BLUETOOTH) {
           // Turn on Bluetooth first.
           BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
           if (adapter.getState() == BluetoothAdapter.STATE_OFF) {
               mBluetoothEnableForTether = true;
               adapter.enable();
               mBluetoothTether.setSummary(R.string.bluetooth_turning_on);
               mBluetoothTether.setEnabled(false);
               return;
           }
       }

       mCm.startTethering(choice, true, mStartTetheringCallback, mHandler);
   }

複製程式碼

通過上面程式碼可以看到 開啟的方式是走ConnectivityManager方式來開啟熱點的。而不是通過wifimanager了。

  • 6.0-8.0(7.0,7.1)的開啟方式 檢視setting原始碼可以看到同樣也是通過8.0方式走的,通過ConnectivityManager 進行開啟wifi 熱點的。但是雖然是通過8.0方式走的,我們卻沒有許可權進行開啟。很奇怪下面我會相信講解為什麼。 7.0也是可以通過wifimanager開啟熱點的,但是到了7.1之後有些手機是可以的,有些手機是可以開啟熱點但是無法連線。然後看了7.1原始碼可以看到7.1之後開啟原始碼的方式也是通過ConnectivityManager方式來進行開啟的。不是通過wifimanager 進行開啟熱點。但是為什麼還可以用wifimanager呢,是因為在7.1這個wifimanager的setWifiApEnabled方式沒有廢棄還是可以用的。

不同版本我們如何通過程式碼進行開啟熱點。

在說如何開啟熱點的程式碼時候,還是會帶大家看一點點的原始碼。然後看看如何在自己專案中用程式碼進行開啟。

  • 上面也介紹了通過哪個類和哪個方法進行開啟wifi,但是知道了還是不行的。
  • 首選我們來看一下6.0 Wifimanager的方式通過setWifiApEnabled進行開啟熱點方式的原始碼

   /**
    * Start AccessPoint mode with the specified
    * configuration. If the radio is already running in
    * AP mode, update the new configuration
    * Note that starting in access point mode disables station
    * mode operation
    * @param wifiConfig SSID, security and channel details as
    *        part of WifiConfiguration
    * @return {@code true} if the operation succeeds, {@code false} otherwise
    *
    * @hide Dont open up yet
    */
   public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
       try {
           mService.setWifiApEnabled(wifiConfig, enabled);
           return true;
       } catch (RemoteException e) {
           return false;
       }
   }

複製程式碼

可以看到這個Api已經被隱藏了。大兄弟們,你們是沒法玩耍的。只能乾瞪眼

  • 然後我們在看一下7.0,7.1 Wifimanager的方式通過setWifiApEnabled開熱點的方式。發現和6.0沒有什麼區別
/**
    * Start AccessPoint mode with the specified
    * configuration. If the radio is already running in
    * AP mode, update the new configuration
    * Note that starting in access point mode disables station
    * mode operation
    * @param wifiConfig SSID, security and channel details as
    *        part of WifiConfiguration
    * @return {@code true} if the operation succeeds, {@code false} otherwise
    *
    * @hide
    */
   @SystemApi
   public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
       try {
           mService.setWifiApEnabled(wifiConfig, enabled);
           return true;
       } catch (RemoteException e) {
           throw e.rethrowFromSystemServer();
       }
   }


複製程式碼

看到沒有變成了系統級別的Api 不緊隱藏了,還變成了系統級別的Api,而且發現出現exec的時候直接返回exception而不是返回false 直接返回false 這個無關緊要

  • 然後我們在看一下8.1的Wifimanager setWifiApEnabled 原始碼,發現這個api已經被廢棄了。
    /**
    * This call is deprecated and removed.  It is no longer used to
    * start WiFi Tethering.  Please use {@link ConnectivityManager#startTethering(int, boolean,
    * ConnectivityManager#OnStartTetheringCallback)} if
    * the caller has proper permissions.  Callers can also use the LocalOnlyHotspot feature for a
    * hotspot capable of communicating with co-located devices {@link
    * WifiManager#startLocalOnlyHotspot(LocalOnlyHotspotCallback)}.
    *
    * @param wifiConfig SSID, security and channel details as
    *        part of WifiConfiguration
    * @return {@code false}
    *
    * @hide
    * @deprecated This API is nolonger supported.
    * @removed
    */
   @SystemApi
   @Deprecated
   @RequiresPermission(android.Manifest.permission.TETHER_PRIVILEGED)
   public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
       String packageName = mContext.getOpPackageName();

       Log.w(TAG, packageName + " attempted call to setWifiApEnabled: enabled = " + enabled);
       return false;
   }

複製程式碼

也就是說這個api啊 在8.1的時候已經被完全廢棄了。直接給你返回false。只能通過8.0的方式進行開啟wifi 熱點了

那麼接下來說的就是手動編寫的程式碼了

由於都是隱藏的api 所以開啟熱點的方式幾乎都是通過反射來進行的

  • 7.0之前的方式(程式碼直接copy)就不一一解釋了。網上程式碼很多
public boolean createAp(boolean isOpen) {
        StringBuffer sb = new StringBuffer();
        try {
            mWifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
            if (mWifiManager.isWifiEnabled()) {
                mWifiManager.setWifiEnabled(false);
            }
            sb.append(1);
            WifiConfiguration netConfig = new WifiConfiguration();
            netConfig.SSID = "xiaomeng";
            netConfig.preSharedKey = "11111111";
            Log.d("oye", "WifiPresenter:createAp----->netConfig.SSID:"
                    + netConfig.SSID + ",netConfig.preSharedKey:" + netConfig.preSharedKey + ",isOpen=" + isOpen);
            netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            sb.append(2);
            if (isOpen) {
                netConfig.allowedKeyManagement.set(4);
                sb.append(3);
            } else {
                netConfig.allowedKeyManagement.set(4);
                sb.append(4);
            }
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            sb.append(5);

            Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
            sb.append(9);
            return (boolean) method.invoke(mWifiManager, netConfig, true);
            

        } catch (NoSuchMethodException e) {
            sb.append(10 + (e.getMessage()));
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            sb.append(11 + (e.getMessage()));
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            sb.append(12 + (e.getMessage()));
            e.printStackTrace();
        } 
        log.setText(sb.toString());

        return false;
    }

複製程式碼
  • 8.0的方式有兩種方式開啟熱點

第一種直接呼叫系統提供的Api 但是不穩定 不靠譜(而且熱點的名稱和密碼都是隨機的)

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {

                @TargetApi(Build.VERSION_CODES.O)
                @Override
                public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
                    super.onStarted(reservation);
                    WifiConfiguration wifiConfiguration = reservation.getWifiConfiguration();
                    ssid = wifiConfiguration.SSID;
                    //可以通過config拿到開啟熱點的賬號和密碼
                    mHandler.obtainMessage(2018, wifiConfiguration).sendToTarget();
                }

                @Override
                public void onStopped() {
                    super.onStopped();
                }

                @Override
                public void onFailed(int reason) {
                    super.onFailed(reason);
                }

            }, mHandler);

複製程式碼

第二種開啟的方式 有些機型會報NoSuchMethodException的異常 是因為有些機型他會多出來一個引數

 private void startTethering() {
        mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (mWifiManager != null) {
            int wifiState = mWifiManager.getWifiState();
            boolean isWifiEnabled = ((wifiState == WifiManager.WIFI_STATE_ENABLED) || (wifiState == WifiManager.WIFI_STATE_ENABLING));
            if (isWifiEnabled)
                mWifiManager.setWifiEnabled(false);
        }
        if (mConnectivityManager != null) {
            try {
                Field internalConnectivityManagerField = ConnectivityManager.class.getDeclaredField("mService");
                internalConnectivityManagerField.setAccessible(true);
                WifiConfiguration apConfig = new WifiConfiguration();
                apConfig.SSID = "cuieney";
                apConfig.preSharedKey = "12121212";

                StringBuffer sb = new StringBuffer();
                Class internalConnectivityManagerClass = Class.forName("android.net.IConnectivityManager");
                ResultReceiver dummyResultReceiver = new ResultReceiver(null);
                try {
                    
                    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
                    Method mMethod = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
                    mMethod.invoke(wifiManager, apConfig);
                    Method startTetheringMethod = internalConnectivityManagerClass.getDeclaredMethod("startTethering",
                            int.class,
                            ResultReceiver.class,
                            boolean.class);

                    startTetheringMethod.invoke(internalConnectivityManagerClass,
                            0,
                            dummyResultReceiver,
                            true);
                } catch (NoSuchMethodException e) {
                    Method startTetheringMethod = internalConnectivityManagerClass.getDeclaredMethod("startTethering",
                            int.class,
                            ResultReceiver.class,
                            boolean.class,
                            String.class);

                    startTetheringMethod.invoke(internalConnectivityManagerClass,
                            0,
                            dummyResultReceiver,
                            false,
                            context.getPackageName());
                } catch (InvocationTargetException e) {
                    sb.append(11 + (e.getMessage()));
                    e.printStackTrace();
                } finally {
                    log.setText(sb.toString());
                }


            } catch (Exception e) {
                Log.e("WifiApManager.startTethering", Log.getStackTraceString(e));
            }
        }
    }

複製程式碼

通過ConnectivityManager的startTethering方式進行開啟wifi熱點。可以配置名稱和密碼。是以系統級別的熱點開啟方式。

  • 7.1方式開啟wifi熱點

    首先呢,7.1的方式比較奇葩 有的機型可以通過Wifimanager的方式進行開啟,也能正常連線,但是有的能開啟但是無法正常連線。

    下面有幾種方式可以成功的開啟7.1熱點同時也能連線上網

  1. 第一種方式,通過編譯修改原始碼的方式進行,把ConnectivityManager這個包下面的原始碼單獨編譯一個jar 然後匯入jar包到專案中使用。
  2. 第二種方式,通過8.0的方式走ConnectivityManager 的startTethering方式進行開啟熱點,但是要注意的是7.1的startTethering 引數和8.0的startTethering引數有所不同注意修改。但是即使這樣還是會報一個錯誤(need MANAGE_USERS or CREATE_USERS permission to: query user)沒有許可權呼叫這個Api同時還會出現一個Exec異常InvocationTargetException 就是說你這個app不是系統app需要許可權,那我們就把他變成系統app,如何才能變成呢,下載簽名工具 簽名包可以在這裡下載 然後通過命令java -jar signapk.jar platform.x509.pem platform.pk8 src.apk dst.apk進行簽名 adb push 到你的手機裡的/system/app/ 目錄下 。別忘了chmod更改 apk許可權 同時reboot 最後可以通過adb shell dumpsys package 包名 檢視你的app所有許可權。自此 7.1版本的熱點就可以啟動了。 具體操作可以給老鐵們一份連線
  3. 第三種方式,和大家說一下,之所以開啟了wifi熱點成功,但是卻沒有成功連線是因為。DHCP沒有給這個熱點分配IP地址,熱點開啟了,卻沒有啟用這個熱點是因為沒有分配IP,這個我在嘗試,有結果了立馬給老鐵們上程式碼。

ending

花了個把小時寫的東西,希望給老鐵們帶來的是知識的儲備而不是時間的浪費。不早了不早了下班了,