精华内容
下载资源
问答
  • android打开关闭wifi
    2022-02-15 23:55:36

    将做工程过程中经常用的一些代码记录起来,下面代码内容是关于Android 开启和关闭wifi的的代码,应该能对小伙伴们有较大好处。

    android.permission.ACCESS_WIFI_STATE
    android.permission.CHANGE_WIFI_STATE
    android.permission.WAKE_LOCK

    2、获取WifiManager

    wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

    3、开启、关闭wifi

    if (wifiManager.isWifiEnabled()) {
    wifiManager.setWifiEnabled(false);
    } else {
    wifiManager.setWifiEnabled(true);
    }

    更多相关内容
  • Android WiFi 打开关闭流程

    千次阅读 2021-08-26 15:34:41
    本文简单介绍下WiFi打开关闭流程,参考源码Android P。 一、WiFi 开机自动打开流程 系统服务启动的时候会启动WifiService,在SystemService.PHASE_SYSTEM_SERVICES_READY的时候,会调用 WifiServiceImpl#...

    本文简单介绍下WiFi打开与关闭流程,参考源码Android P

    一、WiFi 开机自动打开流程

    系统服务启动的时候会启动WifiService,在SystemService.PHASE_SYSTEM_SERVICES_READY的时候,会调用 WifiServiceImpl#checkAndStartWifi(),获取Wi-Fi开关,持久化存储的值。

    然后判断是否需要打开WiFi。

        /**
         * Check if we are ready to start wifi.
         *
         * First check if we will be restarting system services to decrypt the device. If the device is
         * not encrypted, check if Wi-Fi needs to be enabled and start if needed
         *
         * This function is used only at boot time.
         */
        public void checkAndStartWifi() {
            // First check if we will end up restarting WifiService
            if (mFrameworkFacade.inStorageManagerCryptKeeperBounce()) {
                Log.d(TAG, "Device still encrypted. Need to restart SystemServer.  Do not start wifi.");
                return;
            }
    
            // Check if wi-fi needs to be enabled
            boolean wifiEnabled = mSettingsStore.isWifiToggleEnabled();
            ........
    
            // If we are already disabled (could be due to airplane mode), avoid changing persist
            // state here
            if (wifiEnabled) {
                try {
                    setWifiEnabled(mContext.getPackageName(), wifiEnabled);
                } catch (RemoteException e) {
                    /* ignore - local call */
                }
            }
        }

    二、系统设置主动开启WiFi

    1. WiFi开关切换,在WifiEnabler的SwitchToggled中会调用WifiManager.setWifiEnabled方法。

        @Override
        public boolean onSwitchToggled(boolean isChecked) {
            //Do nothing if called as a result of a state machine event
            if (mStateMachineEvent) {
                return true;
            }
            // Show toast message if Wi-Fi is not allowed in airplane mode
            if (isChecked && !WirelessUtils.isRadioAllowed(mContext, Settings.Global.RADIO_WIFI)) {
                Toast.makeText(mContext, R.string.wifi_in_airplane_mode, Toast.LENGTH_SHORT).show();
                // Reset switch to off. No infinite check/listener loop.
                mSwitchWidget.setChecked(false);
                return false;
            }
    
            if (isChecked) {
                mMetricsFeatureProvider.action(mContext, MetricsEvent.ACTION_WIFI_ON);
            } else {
                // Log if user was connected at the time of switching off.
                mMetricsFeatureProvider.action(mContext, MetricsEvent.ACTION_WIFI_OFF,
                        mConnected.get());
            }
            if (!mWifiManager.setWifiEnabled(isChecked)) {
                // Error
                mSwitchWidget.setEnabled(true);
                Toast.makeText(mContext, R.string.wifi_error, Toast.LENGTH_SHORT).show();
            }
            return true;
        }

    2. WifiManager中通过AIDL接口调用WifiService的方法。

        /**
         * Enable or disable Wi-Fi.
         * <p>
         * Applications must have the {@link android.Manifest.permission#CHANGE_WIFI_STATE}
         * permission to toggle wifi.
         *
         * @param enabled {@code true} to enable, {@code false} to disable.
         * @return {@code false} if the request cannot be satisfied; {@code true} indicates that wifi is
         *         either already in the requested state, or in progress toward the requested state.
         * @throws  {@link java.lang.SecurityException} if the caller is missing required permissions.
         */
        public boolean setWifiEnabled(boolean enabled) {
            try {
                return mService.setWifiEnabled(mContext.getOpPackageName(), enabled);
            } catch (RemoteException e) {
                throw e.rethrowFromSystemServer();
            }
        }

    3. WiFiManager.aidl中提供了setWifiEnabled()接口。

    boolean setWifiEnabled(String packageName, boolean enable);

    4. WifiServiceImpl中实现WifiManager的接口,在setWifiEnabled函数中会先调用WifiSettingsStore将WiFi开关值进行持久化存储。

    然后WifiController发消息CMD_WIFI_TOGGLED 去打开WiFi。

        /**
         * see {@link android.net.wifi.WifiManager#setWifiEnabled(boolean)}
         * @param enable {@code true} to enable, {@code false} to disable.
         * @return {@code true} if the enable/disable operation was
         *         started or is already in the queue.
         */
        @Override
        public synchronized boolean setWifiEnabled(String packageName, boolean enable)
                throws RemoteException {
            ........
    
            try {
                if (! mSettingsStore.handleWifiToggled(enable)) {
                    // Nothing to do if wifi cannot be toggled
                    return true;
                }
            } finally {
                Binder.restoreCallingIdentity(ident);
            }
            ........
    
            mWifiController.sendMessage(CMD_WIFI_TOGGLED);
            return true;
        }

    5. WifiController中对CMD_WIFI_TOGGLED消息进行处理,从初始状态StaDisabledState(如果没有开启wifi_scan_always_enabled功能)切换到DeviceActiveState状态。

        class StaDisabledState extends State {
            private int mDeferredEnableSerialNumber = 0;
            private boolean mHaveDeferredEnable = false;
            private long mDisabledTimestamp;
    
            @Override
            public void enter() {
                mWifiStateMachinePrime.disableWifi();
                // Supplicant can't restart right away, so note the time we switched off
                mDisabledTimestamp = SystemClock.elapsedRealtime();
                mDeferredEnableSerialNumber++;
                mHaveDeferredEnable = false;
                mWifiStateMachine.clearANQPCache();
            }
            @Override
            public boolean processMessage(Message msg) {
                switch (msg.what) {
                    case CMD_WIFI_TOGGLED:
                        if (mSettingsStore.isWifiToggleEnabled()) {
                            if (doDeferEnable(msg)) {
                                if (mHaveDeferredEnable) {
                                    //  have 2 toggles now, inc serial number and ignore both
                                    mDeferredEnableSerialNumber++;
                                }
                                mHaveDeferredEnable = !mHaveDeferredEnable;
                                break;
                            }
                            transitionTo(mDeviceActiveState);
                        } else if (checkScanOnlyModeAvailable()) {
                            // only go to scan mode if we aren't in airplane mode
                            if (mSettingsStore.isAirplaneModeOn()) {
                                transitionTo(mStaDisabledWithScanState);
                            }
                        }
                        break;
            ........
            }
        }
    
        /**
         * Parent: StaEnabledState
         *
         * TODO (b/79209870): merge DeviceActiveState and StaEnabledState into a single state
         */
        class DeviceActiveState extends State {
            @Override
            public void enter() {
                mWifiStateMachinePrime.enterClientMode();
                mWifiStateMachine.setHighPerfModeEnabled(false);
            }
    
            @Override
            public boolean processMessage(Message msg) {
                if (msg.what == CMD_USER_PRESENT) {
                    // TLS networks can't connect until user unlocks keystore. KeyStore
                    // unlocks when the user punches PIN after the reboot. So use this
                    // trigger to get those networks connected.
                    if (mFirstUserSignOnSeen == false) {
                        mWifiStateMachine.reloadTlsNetworksAndReconnect();
                    }
                    mFirstUserSignOnSeen = true;
                    return HANDLED;
                } else if (msg.what == CMD_RECOVERY_RESTART_WIFI) {
                    final String bugTitle;
                    final String bugDetail;
                    if (msg.arg1 < SelfRecovery.REASON_STRINGS.length && msg.arg1 >= 0) {
                        bugDetail = SelfRecovery.REASON_STRINGS[msg.arg1];
                        bugTitle = "Wi-Fi BugReport: " + bugDetail;
                    } else {
                        bugDetail = "";
                        bugTitle = "Wi-Fi BugReport";
                    }
                    if (msg.arg1 != SelfRecovery.REASON_LAST_RESORT_WATCHDOG) {
                        (new Handler(mWifiStateMachineLooper)).post(() -> {
                            mWifiStateMachine.takeBugReport(bugTitle, bugDetail);
                        });
                    }
                    return NOT_HANDLED;
                }
                return NOT_HANDLED;
            }
        }

    进入DeviceActiveState,执行enter()函数,执行enterClientMode,给ModeStateMachine状态机发送CMD_START_CLIENT_MODE消息。

        /**
         * Method to switch wifi into client mode where connections to configured networks will be
         * attempted.
         */
        public void enterClientMode() {
            changeMode(ModeStateMachine.CMD_START_CLIENT_MODE);
        }
    
    
        private class ModeStateMachine extends StateMachine {
            ........
            private boolean checkForAndHandleModeChange(Message message) {
                switch(message.what) {
                    case ModeStateMachine.CMD_START_CLIENT_MODE:
                        Log.d(TAG, "Switching from " + getCurrentMode() + " to ClientMode");
                        mModeStateMachine.transitionTo(mClientModeActiveState);
                        break;
                    case ModeStateMachine.CMD_START_SCAN_ONLY_MODE:
                        Log.d(TAG, "Switching from " + getCurrentMode() + " to ScanOnlyMode");
                        mModeStateMachine.transitionTo(mScanOnlyModeActiveState);
                        break;
                    case ModeStateMachine.CMD_DISABLE_WIFI:
                        Log.d(TAG, "Switching from " + getCurrentMode() + " to WifiDisabled");
                        mModeStateMachine.transitionTo(mWifiDisabledState);
                        break;
                    default:
                        return NOT_HANDLED;
                }
                return HANDLED;
            }
            ........
        }

    6. 进入ClientModeActiveState,执行enter()函数,WifiInjector创建一个 ClientModeManager,并start。

        class ClientModeActiveState extends ModeActiveState {
                @Override
                public void enter() {
                    Log.d(TAG, "Entering ClientModeActiveState");
    
                    mListener = new ClientListener();
                    mManager = mWifiInjector.makeClientModeManager(mListener);
                    mManager.start();
                    mActiveModeManagers.add(mManager);
    
                    updateBatteryStatsWifiState(true);
                }
        }
    
    
        /**
         * Create a ClientModeManager
         *
         * @param listener listener for ClientModeManager state changes
         * @return a new instance of ClientModeManager
         */
        public ClientModeManager makeClientModeManager(ClientModeManager.Listener listener) {
            return new ClientModeManager(mContext, mWifiStateMachineHandlerThread.getLooper(),
                    mWifiNative, listener, mWifiMetrics, mScanRequestProxy, mWifiStateMachine);
        }

    ClientModeManager 中去启动客户端模式,发送消息CMD_START,进去到IdleState继续处理,处理完毕进入StartedState。

        /**
         * Start client mode.
         */
        public void start() {
            mStateMachine.sendMessage(ClientModeStateMachine.CMD_START);
        }
            private class IdleState extends State {
    
                @Override
                public void enter() {
                    Log.d(TAG, "entering IdleState");
                    mClientInterfaceName = null;
                    mIfaceIsUp = false;
                }
    
                @Override
                public boolean processMessage(Message message) {
                    switch (message.what) {
                        case CMD_START:
                            updateWifiState(WifiManager.WIFI_STATE_ENABLING,
                                            WifiManager.WIFI_STATE_DISABLED);
    
                            mClientInterfaceName = mWifiNative.setupInterfaceForClientMode(
                                    false /* not low priority */, mWifiNativeInterfaceCallback);
                            if (TextUtils.isEmpty(mClientInterfaceName)) {
                                Log.e(TAG, "Failed to create ClientInterface. Sit in Idle");
                                updateWifiState(WifiManager.WIFI_STATE_UNKNOWN,
                                                WifiManager.WIFI_STATE_ENABLING);
                                updateWifiState(WifiManager.WIFI_STATE_DISABLED,
                                                WifiManager.WIFI_STATE_UNKNOWN);
                                break;
                            }
                            sendScanAvailableBroadcast(false);
                            mScanRequestProxy.enableScanningForHiddenNetworks(false);
                            mScanRequestProxy.clearScanResults();
                            transitionTo(mStartedState);
                            break;
                        default:
                            Log.d(TAG, "received an invalid message: " + message);
                            return NOT_HANDLED;
                    }
                    return HANDLED;
                }
            }

    7. 接下来看下WifiNative 中setupInterfaceForClientMode,在其中做了HAL部分的启动(包含check驱动是否已经准备ok,HAL部分是否成功启动),之后再进行wpa_supplicant进程的启动,状态检测进程的启动startMonitoring。

        /**
         * Setup an interface for Client mode operations.
         *
         * This method configures an interface in STA mode in all the native daemons
         * (wificond, wpa_supplicant & vendor HAL).
         *
         * @param lowPrioritySta The requested STA has a low request priority (lower probability of
         *                       getting created, higher probability of getting destroyed).
         * @param interfaceCallback Associated callback for notifying status changes for the iface.
         * @return Returns the name of the allocated interface, will be null on failure.
         */
        public String setupInterfaceForClientMode(boolean lowPrioritySta,
                @NonNull InterfaceCallback interfaceCallback) {
            synchronized (mLock) {
                if (!startHal()) {
                    Log.e(TAG, "Failed to start Hal");
                    mWifiMetrics.incrementNumSetupClientInterfaceFailureDueToHal();
                    return null;
                }
                if (!startSupplicant()) {
                    Log.e(TAG, "Failed to start supplicant");
                    mWifiMetrics.incrementNumSetupClientInterfaceFailureDueToSupplicant();
                    return null;
                }
                Iface iface = mIfaceMgr.allocateIface(Iface.IFACE_TYPE_STA);
                if (iface == null) {
                    Log.e(TAG, "Failed to allocate new STA iface");
                    return null;
                }
                iface.externalListener = interfaceCallback;
                iface.name = createStaIface(iface, lowPrioritySta);
                if (TextUtils.isEmpty(iface.name)) {
                    Log.e(TAG, "Failed to create STA iface in vendor HAL");
                    mIfaceMgr.removeIface(iface.id);
                    mWifiMetrics.incrementNumSetupClientInterfaceFailureDueToHal();
                    return null;
                }
                if (mWificondControl.setupInterfaceForClientMode(iface.name) == null) {
                    Log.e(TAG, "Failed to setup iface in wificond on " + iface);
                    teardownInterface(iface.name);
                    mWifiMetrics.incrementNumSetupClientInterfaceFailureDueToWificond();
                    return null;
                }
                if (!mSupplicantStaIfaceHal.setupIface(iface.name)) {
                    Log.e(TAG, "Failed to setup iface in supplicant on " + iface);
                    teardownInterface(iface.name);
                    mWifiMetrics.incrementNumSetupClientInterfaceFailureDueToSupplicant();
                    return null;
                }
                iface.networkObserver = new NetworkObserverInternal(iface.id);
                if (!registerNetworkObserver(iface.networkObserver)) {
                    Log.e(TAG, "Failed to register network observer on " + iface);
                    teardownInterface(iface.name);
                    return null;
                }
                mWifiMonitor.startMonitoring(iface.name);
                // Just to avoid any race conditions with interface state change callbacks,
                // update the interface state before we exit.
                onInterfaceStateChanged(iface, isInterfaceUp(iface.name));
                initializeNwParamsForClientInterface(iface.name);
                Log.i(TAG, "Successfully setup " + iface);
                return iface.name;
            }
        }

    8. 在ClientModeManager中进行状态的更新,广播WiFi状态改变消息。

        /**
         * Update Wifi state and send the broadcast.
         * @param newState new Wifi state
         * @param currentState current wifi state
         */
        private void updateWifiState(int newState, int currentState) {
            if (!mExpectedStop) {
                mListener.onStateChanged(newState);
            } else {
                Log.d(TAG, "expected stop, not triggering callbacks: newState = " + newState);
            }
    
            // Once we report the mode has stopped/failed any other stop signals are redundant
            // note: this can happen in failure modes where we get multiple callbacks as underlying
            // components/interface stops or the underlying interface is destroyed in cleanup
            if (newState == WifiManager.WIFI_STATE_UNKNOWN
                    || newState == WifiManager.WIFI_STATE_DISABLED) {
                mExpectedStop = true;
            }
    
            if (newState == WifiManager.WIFI_STATE_UNKNOWN) {
                // do not need to broadcast failure to system
                return;
            }
    
            mWifiStateMachine.setWifiStateForApiCalls(newState);
    
            final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
            intent.putExtra(WifiManager.EXTRA_WIFI_STATE, newState);
            intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, currentState);
            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
        }

    9. 系统设置在WifiEnabler中会监听WiFi的状态。

        private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
                    handleWifiStateChanged(mWifiManager.getWifiState());
                } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
                    if (!mConnected.get()) {
                        handleStateChanged(WifiInfo.getDetailedStateOf((SupplicantState)
                                intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE)));
                    }
                } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
                    NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
                            WifiManager.EXTRA_NETWORK_INFO);
                    mConnected.set(info.isConnected());
                    handleStateChanged(info.getDetailedState());
                }
            }
        };

    三、WiFi关闭流程

    与打开流程一样,只是在WifiController中收到CMD_WIFI_TOGGLED消息,会从StaEnabledState切换到mStaDisabledState(如果没有启用wifi_scan_always_enabled功能)。

        class StaDisabledState extends State {
            private int mDeferredEnableSerialNumber = 0;
            private boolean mHaveDeferredEnable = false;
            private long mDisabledTimestamp;
    
            @Override
            public void enter() {
                mWifiStateMachinePrime.disableWifi();
                // Supplicant can't restart right away, so note the time we switched off
                mDisabledTimestamp = SystemClock.elapsedRealtime();
                mDeferredEnableSerialNumber++;
                mHaveDeferredEnable = false;
                mWifiStateMachine.clearANQPCache();
            }

    会调用WifiStateMachinePrime.disableWifi() 发送消息CMD_DISABLE_WIFI 。

        /**
         * Method to disable wifi in sta/client mode scenarios.
         *
         * This mode will stop any client/scan modes and will not perform any network scans.
         */
        public void disableWifi() {
            changeMode(ModeStateMachine.CMD_DISABLE_WIFI);
        }

    WifiStateMachinePrime中则会由ClientModeActiveState切换到WifiDisabled,会执行ClientModeActiveState的exit()函数,其调用ModeActiveState的exit(),调用mManager.stop(),最终会将wifi最新状态设置到WifiStateMachine。

            class ModeActiveState extends State {
                ActiveModeManager mManager;
                @Override
                public boolean processMessage(Message message) {
                    // handle messages for changing modes here
                    return NOT_HANDLED;
                }
    
                @Override
                public void exit() {
                    // Active states must have a mode manager, so this should not be null, but it isn't
                    // obvious from the structure - add a null check here, just in case this is missed
                    // in the future
                    if (mManager != null) {
                        mManager.stop();
                        mActiveModeManagers.remove(mManager);
                    }
                    updateBatteryStatsWifiState(false);
                }
            }
            private boolean checkForAndHandleModeChange(Message message) {
                switch(message.what) {
                    case ModeStateMachine.CMD_START_CLIENT_MODE:
                        Log.d(TAG, "Switching from " + getCurrentMode() + " to ClientMode");
                        mModeStateMachine.transitionTo(mClientModeActiveState);
                        break;
                    case ModeStateMachine.CMD_START_SCAN_ONLY_MODE:
                        Log.d(TAG, "Switching from " + getCurrentMode() + " to ScanOnlyMode");
                        mModeStateMachine.transitionTo(mScanOnlyModeActiveState);
                        break;
                    case ModeStateMachine.CMD_DISABLE_WIFI:
                        Log.d(TAG, "Switching from " + getCurrentMode() + " to WifiDisabled");
                        mModeStateMachine.transitionTo(mWifiDisabledState);
                        break;
                    default:
                        return NOT_HANDLED;
                }
                return HANDLED;
            }

    ClientModeManager中也会从StartedState切换到IdleState,在启exit()函数中调用mWifiNative.teardownInterface

            private class StartedState extends State {
    
                private void onUpChanged(boolean isUp) {
                    if (isUp == mIfaceIsUp) {
                        return;  // no change
                    }
                    mIfaceIsUp = isUp;
                    if (isUp) {
                        Log.d(TAG, "Wifi is ready to use for client mode");
                        sendScanAvailableBroadcast(true);
                        mWifiStateMachine.setOperationalMode(WifiStateMachine.CONNECT_MODE,
                                                             mClientInterfaceName);
                        updateWifiState(WifiManager.WIFI_STATE_ENABLED,
                                        WifiManager.WIFI_STATE_ENABLING);
                    } else {
                        if (mWifiStateMachine.isConnectedMacRandomizationEnabled()) {
                            // Handle the error case where our underlying interface went down if we
                            // do not have mac randomization enabled (b/72459123).
                            return;
                        }
                        // if the interface goes down we should exit and go back to idle state.
                        Log.d(TAG, "interface down!");
                        updateWifiState(WifiManager.WIFI_STATE_UNKNOWN,
                                        WifiManager.WIFI_STATE_ENABLED);
                        mStateMachine.sendMessage(CMD_INTERFACE_DOWN);
                    }
                }
    
                /**
                 * Clean up state, unregister listeners and update wifi state.
                 */
                @Override
                public void exit() {
                    mWifiStateMachine.setOperationalMode(WifiStateMachine.DISABLED_MODE, null);
    
                    if (mClientInterfaceName != null) {
                        mWifiNative.teardownInterface(mClientInterfaceName);
                        mClientInterfaceName = null;
                        mIfaceIsUp = false;
                    }
    
                    updateWifiState(WifiManager.WIFI_STATE_DISABLED,
                                    WifiManager.WIFI_STATE_DISABLING);
    
                    // once we leave started, nothing else to do...  stop the state machine
                    mStateMachine.quitNow();
                }
            }

    WifiNactive中后续则会调用到mWifiMonitor.stopMonitoring(),stopSupplicantIfNecessary(),stopHalAndWificondIfNecessary(),去停止监测,停止wpa_supplicant,停止hal服务等。

        /** Helper method invoked to teardown client iface and perform necessary cleanup */
        private void onClientInterfaceDestroyed(@NonNull Iface iface) {
            synchronized (mLock) {
                mWifiMonitor.stopMonitoring(iface.name);
                if (!unregisterNetworkObserver(iface.networkObserver)) {
                    Log.e(TAG, "Failed to unregister network observer on " + iface);
                }
                if (!mSupplicantStaIfaceHal.teardownIface(iface.name)) {
                    Log.e(TAG, "Failed to teardown iface in supplicant on " + iface);
                }
                if (!mWificondControl.tearDownClientInterface(iface.name)) {
                    Log.e(TAG, "Failed to teardown iface in wificond on " + iface);
                }
                stopSupplicantIfNecessary();
                stopHalAndWificondIfNecessary();
            }
        }

    Android 的WiFi打开关闭流程大致如此,不足之处后续会继续完善。

    展开全文
  • 您可以使用以下代码以编程方式启用,禁用和查询wifi直接状态。package com.kusmezer.androidhelper.networking;import java.lang.reflect.Method;import com.google.common.base.Preconditions;import android....

    7a7d9a0fe5ca15dc4e062a2a79a59888.png

    梵蒂冈之花

    警告此方法在5.0以后将无法使用,这是一个过时的条目。您可以使用以下代码以编程方式启用,禁用和查询wifi直接状态。package com.kusmezer.androidhelper.networking;import java.lang.reflect.Method;import com.google.common.base.Preconditions;import android.content.Context;import android.net.wifi.WifiConfiguration;import android.net.wifi.WifiManager;import android.util.Log;public final class WifiApManager {      private static final int WIFI_AP_STATE_FAILED = 4;      private final WifiManager mWifiManager;      private final String TAG = "Wifi Access Manager";      private Method wifiControlMethod;      private Method wifiApConfigurationMethod;      private Method wifiApState;      public WifiApManager(Context context) throws SecurityException, NoSuchMethodException {       context = Preconditions.checkNotNull(context);       mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);       wifiControlMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class,boolean.class);       wifiApConfigurationMethod = mWifiManager.getClass().getMethod("getWifiApConfiguration",null);       wifiApState = mWifiManager.getClass().getMethod("getWifiApState");      }         public boolean setWifiApState(WifiConfiguration config, boolean enabled) {       config = Preconditions.checkNotNull(config);       try {        if (enabled) {            mWifiManager.setWifiEnabled(!enabled);        }        return (Boolean) wifiControlMethod.invoke(mWifiManager, config, enabled);       } catch (Exception e) {        Log.e(TAG, "", e);        return false;       }      }      public WifiConfiguration getWifiApConfiguration()      {          try{              return (WifiConfiguration)wifiApConfigurationMethod.invoke(mWifiManager, null);          }          catch(Exception e)          {              return null;          }      }      public int getWifiApState() {       try {            return (Integer)wifiApState.invoke(mWifiManager);       } catch (Exception e) {        Log.e(TAG, "", e);            return WIFI_AP_STATE_FAILED;       }      }}

    展开全文
  • 一段关于wifi的代码
  • android 关闭wifi打开移动数据网络
  • 主要介绍了Android 通过代码设置、打开wifi热点及热点连接的实现代码,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
  • 设置手机WiFi便携热点,并且监听热点打开关闭,详情请参见我的博客http://blog.csdn.net/u011520181/article/details/46496377
  • Android 11 WiFi热点打开关闭接口

    千次阅读 热门讨论 2022-02-25 11:02:51
    一.android11之前wifi Hotspot开启关闭方式 1.manfiest中添加权限 <!-- WiFi AP startTethering --> <uses-permission android:name="android.permission.TETHER_PRIVILEGED" /> 2. android8.0 Ap...

    一.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();
            }
    
        }

    展开全文
  • 因发现Android 9.0 会在打开wifi的时候去默认关闭热点,所以我们看下打开wifi的流程,和在哪里去关闭的热点 1 设置打开wifi会调用 frameworks\base\wifi\java\android\net\wifi\WifiManager.java /** * ...
  • Android热点、WiFi、蓝牙等功能开启和关闭 1、需要添加权限,选择自己需要的添加,热点的开启和关闭可能还需要权限; <!--设备(亮屏)权限--> <user-permission android:name="android.permission.DEVICE_...
  • <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission....
  • Android打开/关闭wifi命令

    万次阅读 2017-06-19 10:31:28
    1.提升权限 # adb root; adb remount 2.关闭wifi # adb shell svc wifi disable 3.打开wifi # adb shell svc wifi enable
  • Android编程打开WiFi

    2021-05-28 08:08:30
    工作以后做的是手机WiFi相关的工作,有时会用到很多操作WiFiAndroid软件,但是因为需求不同,现有的apk或多或少的不能满足工作使用需求,所以一直想自己动手写个apk,满足工作使用.但是鉴于以前几乎从没有接触过Android...
  • Android7.1.1版本实现wifi打开关闭以及热点的设置

    千次阅读 热门讨论 2018-01-31 21:21:05
    wifi打开关闭很简单,网上百度一大堆,问题主要集中在主要在于7.1.1热点的打开以及参数设置的问题。以前的各种方式已经不适用,主要代码调整 如下: public boolean createAp(boolean isOpen) { //如果wifi...
  • app中进行wifi打开关闭

    千次阅读 2017-07-15 15:45:59
    uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> 初始化管理器WifiManager wifiManager=(WifiManager) mCont
  • 本篇文章主要记录一下Android打开Wifi、获取Wifi接入点信息及连接指定接入点的方法,通过小编自己写的demo主要用于测试接口的基本功能,具体实例代码大家通过本文一起学习吧
  • android点击按钮打开wifi或者关闭wifi

    千次阅读 2019-06-03 13:55:20
    1:写一个按钮实现点击 <Button android:id="@+id/btn_openwifi" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/op...
  • 本文主要介绍了Androidwifi与数据流量的切换监听的方法步骤。具有一定的参考价值,下面跟着小编一起来看下吧
  • wifi 获取系统wifi服务: WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); 获取wifi开关状态: int status = ... 关闭:wifiManager.setWifiE
  • 开启WIFI: button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WifiManager wifi =(WifiManager) mContext.getSystemService(Context.WIFI_SERVICE
  • WIFI连接源码(WIFI扫描 WIFI打开 WIFI关闭 WIFI连接).rar
  • android打开关闭蓝牙和wifi

    千次阅读 2015-06-30 16:47:38
    蓝牙获取系统蓝牙服务: BluetoothAdapter mBluetoothAdapter = BluetoothAdapter .getDefaultAdapter(); 打开:mBluetoothAdapter.enable(); 关闭:mBluetoothAdapter....wifi获取系统wifi服务 WifiManager
  • Android 开发wifi热点操作(开启和关闭,设置名称和密码)
  • 摘要:JAVA源码,媒体网络,Android源码,Wifi Wifi连接网络,通过程序你将了解到定义WifiManager对象,定义WifiInfo对象,获取网络连接列表,定义一个WifiLock,打开Wifi网卡,关闭Wifi网卡,检查当前Wifi网卡状态,...
  • Android 监听wifi热点打开关闭广播

    千次阅读 2020-08-12 16:37:51
    wifi热点的打开关闭也是有广播的,监听android.net.wifi.WIFI_AP_STATE_CHANGED广播就可以了,记录下做个笔记 private BroadcastReceiver wifiApBroadcast = new BroadcastReceiver(){ @Override public void ...
  • 主要介绍了android编程实现设置、打开wifi热点共享供他人连接的方法,涉及Android创建WiFi及设置共享的相关实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下
  • 实际上,对WIFI并不需要过多的控制(当成功连接WIFI后,就可以直接通过IP在WIFI设备之间进行通信了),一般只需要控制打开关闭WIFI以及获得一些与WIFI相关的信息(例如,MAC地址、IP等)。 如果读者的Android手机...
  • WiFi打开函数调用流程图
  • Android - 打开飞行模式不会关闭wifi的问题问题解决方法 问题 在Android设备上打开飞行模式,发现不会关闭wifi;可能是自动化脚本运行adb命令来关闭wifi的时候,导致了这个问题。 adb -s udid shell am broadcast -a...
  • WifiManager 打开关闭wifi --- a/frameworks/base/wifi/java/android/net/wifi/WifiManager.java +++ b/frameworks/base/wifi/java/android/net/wifi/WifiManager.java @@ -19,7 +19,7 @@ package android.net.wifi;...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 20,138
精华内容 8,055
关键字:

android打开关闭wifi