Android 11 WiFi热点打开与关闭接口

一.android11之前wifi Hotspot开启关闭方式

1.manfiest中添加权限

<!-- WiFi AP startTethering -->
<uses-permission android:name="android.permission.TETHER_PRIVILEGED" />

2. android8.0 Ap开启关闭方法

 public static void setWiFiApEnable(Context mContext, boolean value) {
        ConnectivityManager mConnectivityManager= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (value) {
            mConnectivityManager.startTethering(ConnectivityManager.TETHERING_WIFI, false, new ConnectivityManager.OnStartTetheringCallback() {
                @Override
                public void onTetheringStarted() {
                    Log.d(TAG, "onTetheringStarted");
                    // Don't fire a callback here, instead wait for the next update from wifi.
                }

                @Override
                public void onTetheringFailed() {
                  Log.d(TAG, "onTetheringFailed");
                  // TODO: Show error.
                }
            });
        } else {
            mConnectivityManager.stopTethering(ConnectivityManager.TETHERING_WIFI);
        }
    }

3.WiFiApReceiver广播接收

private static int isWiFiApState = WifiManager.WIFI_AP_STATE_FAILED;

    public static boolean isWiFiApOpened_O() {
        return (isWiFiApState == WifiManager.WIFI_AP_STATE_ENABLING || isWiFiApState == WifiManager.WIFI_AP_STATE_ENABLED);
    }

    private final class WiFiApReceiver extends BroadcastReceiver {
        private boolean mRegistered;

        public void setListening(boolean listening) {
            if (listening && !mRegistered) {
                Log.d(TAG, "Registering receiver");
                final IntentFilter filter = new IntentFilter();
                filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
                mContext.registerReceiver(this, filter);
                mRegistered = true;
            } else if (!listening && mRegistered) {
                Log.d(TAG, "Unregistering receiver");
                mContext.unregisterReceiver(this);
                mRegistered = false;
            }
        }

        public void onReceive(Context context, Intent intent) {
            isWiFiApState = intent.getIntExtra(
                    WifiManager.EXTRA_WIFI_AP_STATE, WifiManager.WIFI_AP_STATE_FAILED);
            String result = null;

            switch (isWiFiApState) {
                case WifiManager.WIFI_AP_STATE_DISABLED:
                    result = "DISABLED";
                    break;
                case WifiManager.WIFI_AP_STATE_DISABLING:
                    result =  "DISABLING";
                    break;
                case WifiManager.WIFI_AP_STATE_ENABLED:
                    result =  "ENABLED";
                    break;
                case WifiManager.WIFI_AP_STATE_ENABLING:
                    result =  "ENABLING";
                    break;
                case WifiManager.WIFI_AP_STATE_FAILED:
                    result =  "FAILED";
                    break;
            }

            Log.d(TAG, "WiFi state : " + result);
        }
    }

二.android11的wifi Hotspot开启关闭方式,以proxy实现

1.定义回调接口

public abstract class TestOnStartTetheringCallback {
        /**
         * Called when tethering has been successfully started.
         */
        public abstract void onTetheringStarted();

        /**
         * Called when starting tethering failed.
         */
        public abstract void onTetheringFailed();

}

2.proxy类

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.android.dx.stock.ProxyBuilder;

import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;


@RequiresApi(api = Build.VERSION_CODES.O)
public class TestOreoWifiManager {
    private static final String TAG = TestOreoWifiManager.class.getSimpleName();

    private Context mContext;
    private WifiManager mWifiManager;
    private ConnectivityManager mConnectivityManager;

    public TestOreoWifiManager(Context c) {
        mContext = c;
        mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        mConnectivityManager = (ConnectivityManager) mContext.getSystemService(ConnectivityManager.class);
    }

    /**
     * This sets the Wifi SSID and password
     * Call this before {@code startTethering} if app is a system/privileged app
     * Requires: android.permission.TETHER_PRIVILEGED which is only granted to system apps
     */
    public void configureHotspot(String name, String password) {
        WifiConfiguration apConfig = new WifiConfiguration();
        apConfig.SSID = name;
        apConfig.preSharedKey = password;
        apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        try {
            Method setConfigMethod = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
            boolean status = (boolean) setConfigMethod.invoke(mWifiManager, apConfig);
            Log.d(TAG, "setWifiApConfiguration - success? " + status);
        } catch (Exception e) {
            Log.e(TAG, "Error in configureHotspot");
            e.printStackTrace();
        }
    }

    /**
     * Checks where tethering is on.
     * This is determined by the getTetheredIfaces() method,
     * that will return an empty array if not devices are tethered
     *
     * @return true if a tethered device is found, false if not found
     */
    /*public boolean isTetherActive() {
        try {
            Method method = mConnectivityManager.getClass().getDeclaredMethod("getTetheredIfaces");
            if (method == null) {
                Log.e(TAG, "getTetheredIfaces is null");
            } else {
                String res[] = (String[]) method.invoke(mConnectivityManager, null);
                Log.d(TAG, "getTetheredIfaces invoked");
                Log.d(TAG, Arrays.toString(res));
                if (res.length > 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error in getTetheredIfaces");
            e.printStackTrace();
        }
        return false;
    }
*/
    /**
     * This enables tethering using the ssid/password defined in Settings App>Hotspot & tethering
     * Does not require app to have system/privileged access
     * Credit: Vishal Sharma - https://stackoverflow.com/a/52219887
     */
    public boolean startTethering(final TestOnStartTetheringCallback callback) {

        // On Pie if we try to start tethering while it is already on, it will
        // be disabled. This is needed when startTethering() is called programmatically.
        /*if (isTetherActive()) {
            Log.d(TAG, "Tether already active, returning");
            return false;
        }*/

        File outputDir = mContext.getCodeCacheDir();
        Object proxy;
        try {
            proxy = ProxyBuilder.forClass(OnStartTetheringCallbackClass())
                    .dexCache(outputDir).handler(new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            switch (method.getName()) {
                                case "onTetheringStarted":
                                    callback.onTetheringStarted();
                                    break;
                                case "onTetheringFailed":
                                    callback.onTetheringFailed();
                                    break;
                                default:
                                    ProxyBuilder.callSuper(proxy, method, args);
                            }
                            return null;
                        }

                    }).build();
        } catch (Exception e) {
            Log.e(TAG, "Error in enableTethering ProxyBuilder");
            e.printStackTrace();
            return false;
        }

        Method method = null;
        try {
            method = mConnectivityManager.getClass().getDeclaredMethod("startTethering", int.class, boolean.class, OnStartTetheringCallbackClass(), Handler.class);
            if (method == null) {
                Log.e(TAG, "startTetheringMethod is null");
            } else {
                method.invoke(mConnectivityManager, ConnectivityManager.TYPE_MOBILE, false, proxy, null);
                Log.d(TAG, "startTethering invoked");
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Error in enableTethering");
            e.printStackTrace();
        }
        return false;
    }

    public void stopTethering() {
        try {
            Method method = mConnectivityManager.getClass().getDeclaredMethod("stopTethering", int.class);
            if (method == null) {
                Log.e(TAG, "stopTetheringMethod is null");
            } else {
                method.invoke(mConnectivityManager, ConnectivityManager.TYPE_MOBILE);
                Log.d(TAG, "stopTethering invoked");
            }
        } catch (Exception e) {
            Log.e(TAG, "stopTethering error: " + e.toString());
            e.printStackTrace();
        }
    }

    private Class OnStartTetheringCallbackClass() {
        try {
            return Class.forName("android.net.ConnectivityManager$OnStartTetheringCallback");
        } catch (ClassNotFoundException e) {
            Log.e(TAG, "OnStartTetheringCallbackClass error: " + e.toString());
            e.printStackTrace();
        }
        return null;
    }
}

3.调用方法

@RequiresApi(api = Build.VERSION_CODES.O)
    public static void setHotspotOnPhone(Context mContext, boolean isEnable) {

        if (mTestOreoWifiManager ==null){
            mTestOreoWifiManager = new TestOreoWifiManager(mContext);
        }


        if (isEnable){
            TestOnStartTetheringCallback callback = new TestOnStartTetheringCallback() {
                @Override
                public void onTetheringStarted() {
                }

                @Override
                public void onTetheringFailed() {

                }
            };

            mTestOreoWifiManager.startTethering(callback);
        }else{
            mTestOreoWifiManager.stopTethering();
        }

    }

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
### 回答1: Android 11WiFi打开函数调用流程图如下: 1. 点击设备的“设置”按钮,进入系统设置界面。 2. 在设置界面中找到“网络和互联网”的选项,点击进入。 3. 在网络和互联网界面中,找到并点击“WiFi”选项。 4. 进入WiFi设置界面后,点击“开启WiFi”按钮。 5. 设备调用系统的WiFi管理模块,开始执行WiFi打开的流程。 6. WiFi管理模块首先检查设备的WiFi芯片状态,如果芯片已经关闭,则需要先打开WiFi芯片。 7. 如果WiFi芯片已经打开,则WiFi管理模块开始搜索可用的WiFi网络。 8. 当找到可用的WiFi网络时,WiFi管理模块会尝试连接到该网络。 9. 连接到WiFi网络后,设备会获取该网络的IP地址和其他网络相关信息。 10. 设备将WiFi连接状态设置为已连接,并通知系统和应用程序。 11. 如果WiFi连接失败或者没有可用的WiFi网络,WiFi管理模块将会关闭WiFi芯片并返回WiFi打开失败的信息。 以上就是Android 11WiFi打开函数调用流程图。在实际执行中,可能还会有一些其他细节和错误处理逻辑,但总体而言,这个流程可以帮助用户打开设备的WiFi功能并连接到可用的WiFi网络。 ### 回答2: Android 11中的WiFi打开函数调用流程图如下: 1. 首先,应用程序通过调用WiFiManager类的getSystemService()方法获取系统的WiFi服务实例。 2. 接下来,应用程序通过调用WiFiManager类的setWifiEnabled()方法来打开WiFi功能。 3. WiFiManager类会将该请求传递给系统服务,即WifiService类。 4. WifiService类会通过调用WifiController类的方法来处理WiFi打开请求。 5. WifiController类会检查当前设备的权限和状态,以确定是否允许打开WiFi。 6. 如果设备具有足够的权限并且当前设备处于正确状态,则WifiController类会继续处理打开WiFi请求。 7. WifiController类会与驱动程序进行通信,以控制硬件设备的操作,从而打开WiFi。 8. 一旦WiFi硬件设备成功打开WifiController类会通知WifiService类。 9. WifiService类随后会通知应用程序,指示WiFi已成功打开。 10. 最后,应用程序可以进一步使用WiFi功能,如连接到可用的WiFi网络。 请注意,Android 11中的WiFi打开函数调用流程可能会因设备和系统定制而有所不同。上述流程图仅为概述,具体实现可能会有所差异。 ### 回答3: Android 11中的Wi-Fi打开函数调用流程图如下: 1. 应用程序调用Wi-Fi Manager类的`setWifiEnabled(true)`方法,用于打开Wi-Fi功能。 2. Wi-Fi Manager类将此请求发送给系统服务。 3. 系统服务接收到请求后,检查当前设备是否具有足够的权限来打开Wi-Fi。如果权限不足,服务将拒绝请求,并向应用程序返回相应的错误代码。 4. 如果应用程序具有足够的权限,系统服务将检查与Wi-Fi硬件驱动程序的通信是否正常。如果存在通信问题,服务将返回相应的错误代码。 5. 如果无任何问题,系统服务将向Wi-Fi硬件驱动程序发送打开Wi-Fi的指令。 6. Wi-Fi硬件驱动程序接收到指令后,控制Wi-Fi芯片打开相应的电路和无线射频器。 7. 一旦Wi-Fi硬件处于打开状态,驱动程序将返回成功的消息给系统服务。 8. 系统服务收到成功消息后,将其传递给Wi-Fi Manager类。 9. Wi-Fi Manager类会更新其内部状态,表示Wi-Fi已成功打开。 10. Wi-Fi Manager类将成功的消息返回给应用程序,通知其Wi-Fi已成功打开11. 应用程序可以通过检查Wi-Fi Manager类的状态来确认Wi-Fi是否已打开。 总的来说,Android 11中的Wi-Fi打开函数调用流程主要涉及应用程序调用Wi-Fi Manager类的方法,将请求传递给系统服务,然后由系统服务与Wi-Fi硬件驱动程序进行通信以打开Wi-Fi。最后,成功的消息将传递回应用程序,并更新Wi-Fi Manager类的内部状态。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值