精华内容
下载资源
问答
  • 2022-04-21 14:49:07
    //飞行模式打开与关闭
    int isAirplaneMode = Settings.System.getInt(context.getContentResolver(),Settings.System.AIRPLANE_MODE_ON,0);
    //0关闭,1开启
    Log.e("motejia", "onCreate: ++++FLY+++++"+isAirplaneMode );
    //WIFI模式的打开与关闭
    ConfigTest.flyStatus  = isAirplaneMode;
    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    int wifiState = wifiManager.getWifiState();
    ConfigTest.wifiStatus = wifiState;
    //0关闭中,1关闭,2打开中,3打开
    Log.e("motejia", "onCreate: ++++WIFI+++++"+wifiState );

    权限

    <!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位 -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位 -->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
    <!-- 修改内容权限 -->
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />

    修改系统权限动态申请

    //是否允许修改系统权限
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        boolean isDoing = true;
        while (isDoing) {
            if (!Settings.System.canWrite(context)) {
                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            } else {
                isDoing = false;
    
            }
        }
    }
    更多相关内容
  • WIFI连接源码(WIFI扫描 WIFI打开 WIFI关闭 WIFI连接).rar
  • 本文简单介绍下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打开关闭流程大致如此,不足之处后续会继续完善。

    展开全文
  • android 关闭wifi打开移动数据网络
  • 打开关闭Wi-Fi 仅适用于macOS和Windows,但欢迎拉取请求以获取Linux支持。 安装 $ npm install manage-wifi 用法 import wifi from 'manage-wifi' ; await wifi . off ( ) ; console . log ( 'Wi-Fi is off' ) ;...
  • Win8关闭无线无法打开WIFI怎么办?.docx
  • 如何解决Win8系统关闭无线网无法打开WiFi.docx
  • 设置手机WiFi便携热点,并且监听热点打开关闭,详情请参见我的博客http://blog.csdn.net/u011520181/article/details/46496377
  • Android 监听wifi热点打开关闭广播

    千次阅读 2020-08-12 16:37:51
    wifi热点的打开关闭也是有广播的,监听android.net.wifi.WIFI_AP_STATE_CHANGED广播就可以了,记录下做个笔记 private BroadcastReceiver wifiApBroadcast = new BroadcastReceiver(){ @Override public void ...

    wifi热点的打开和关闭也是有广播的,监听android.net.wifi.WIFI_AP_STATE_CHANGED广播就可以了,记录下做个笔记

      private BroadcastReceiver wifiApBroadcast = new  BroadcastReceiver(){
    
          @Override
          public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(action)){
                //便携式热点的状态为:10---正在关闭;11---已关闭;12---正在开启;13---已开启
                int state = intent.getIntExtra("wifi_state",  0);
                Log.e("MainActivity","热点开关状态:state= "+String.valueOf(state));
                if(state == 13){
                    Log.e("MainActivity","热点已开启");
                }else if(state == 11){
                    Log.e("MainActivity","热点已关闭");
                }else if(state == 10){
                    Log.e("MainActivity","热点正在关闭");
                }else if(state == 12){
                    Log.e("MainActivity","热点正在开启");
                }
             }
          }
       };
    

    注册广播

    IntentFilter intentFilter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");
    mContext.registerReceiver(wifiApBroadcast,intentFilter);
    
    展开全文
  • 一段关于wifi的代码
  • wifi打开关闭操作

    2013-09-29 20:33:19
    WIFI_STATE_DISABLED = 1, 已经关闭 WIFI_STATE_DISABLING = 0, 正在关闭 WIFI_STATE_ENABLED = 3, 已经打开 WIFI_STATE_ENABLING = 2, 正在打开 WIFI_STATE_UNKNOWN = 4 未知状态 对wifi的操作
  • wifi打开关闭1.0

    2014-04-20 01:47:02
    wifi打开关闭1.0
  • 因发现Android 9.0 会在打开wifi的时候去默认关闭热点,所以我们看下打开wifi的流程,和在哪里去关闭的热点 1 设置打开wifi会调用 frameworks\base\wifi\java\android\net\wifi\WifiManager.java /** * ...

      因发现Android 9.0 会在打开wifi的时候去默认关闭热点,所以我们看下打开wifi的流程,和在哪里去关闭的热点

    1 设置打开wifi会调用

    frameworks\base\wifi\java\android\net\wifi\WifiManager.java

    
        /**
         * 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();
            }
        }

    2调用frameworks\opt\net\wifi\service\java\com\android\server\wifi\WifiServiceImpl.java 在这里有个判断热点状态的,我以为这里判断会有作用,后面发现没作用

    /**
         * 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 {
            if (enforceChangePermission(packageName) != MODE_ALLOWED) {
                return false;
            }
    
            Slog.d(TAG, "setWifiEnabled: " + enable + " pid=" + Binder.getCallingPid()
                        + ", uid=" + Binder.getCallingUid() + ", package=" + packageName);
            mLog.info("setWifiEnabled package=% uid=% enable=%").c(packageName)
                    .c(Binder.getCallingUid()).c(enable).flush();
    
            boolean isFromSettings = checkNetworkSettingsPermission(
                    Binder.getCallingPid(), Binder.getCallingUid());
    
            // If Airplane mode is enabled, only Settings is allowed to toggle Wifi
            if (mSettingsStore.isAirplaneModeOn() && !isFromSettings) {
                mLog.info("setWifiEnabled in Airplane mode: only Settings can enable wifi").flush();
                return false;
            }
    	
            // If SoftAp is enabled, only Settings is allowed to toggle wifi
            boolean apEnabled = mWifiApState == WifiManager.WIFI_AP_STATE_ENABLED;
    
            if (apEnabled && !isFromSettings) {
                mLog.info("setWifiEnabled SoftAp not disabled: only Settings can enable wifi").flush();
                return false;
            }
    		
            /*
            * Caller might not have WRITE_SECURE_SETTINGS,
            * only CHANGE_WIFI_STATE is enforced
            */
            long ident = Binder.clearCallingIdentity();
            try {
                if (! mSettingsStore.handleWifiToggled(enable)) {
                    // Nothing to do if wifi cannot be toggled
                    return true;
                }
            } finally {
                Binder.restoreCallingIdentity(ident);
            }
    	
    
            if (mPermissionReviewRequired) {
                final int wiFiEnabledState = getWifiEnabledState();
                if (enable) {
                    if (wiFiEnabledState == WifiManager.WIFI_STATE_DISABLING
                            || wiFiEnabledState == WifiManager.WIFI_STATE_DISABLED) {
                        if (startConsentUi(packageName, Binder.getCallingUid(),
                                WifiManager.ACTION_REQUEST_ENABLE)) {
                            return true;
                        }
                    }
                } else if (wiFiEnabledState == WifiManager.WIFI_STATE_ENABLING
                        || wiFiEnabledState == WifiManager.WIFI_STATE_ENABLED) {
                    if (startConsentUi(packageName, Binder.getCallingUid(),
                            WifiManager.ACTION_REQUEST_DISABLE)) {
                        return true;
                    }
                }
            }
    	
            mWifiController.sendMessage(CMD_WIFI_TOGGLED);
            return true;
        }
    

    3,上面代码没有开关热点操作,接着流程经历了一些状态传递,这里就不贴代码了,可以自己去看看下面几个类或者找一篇分析wifi开启流程的文章,frameworks\opt\net\wifi\service\java\com\android\server\wifi\WifiController.java

    接着来到frameworks\opt\net\wifi\service\java\com\android\server\wifi\ScanOnlyModeManager.java

    private class IdleState extends State {
    
                @Override
                public void enter() {
                    Log.d(TAG, "entering IdleState");
                    mClientInterfaceName = null;
                }
    
                @Override
                public boolean processMessage(Message message) {
                    switch (message.what) {
                        case CMD_START:
                            mClientInterfaceName = mWifiNative.setupInterfaceForClientMode(true,
                                    mWifiNativeInterfaceCallback);
                            if (TextUtils.isEmpty(mClientInterfaceName)) {
                                Log.e(TAG, "Failed to create ClientInterface. Sit in Idle");
                                updateWifiState(WifiManager.WIFI_STATE_UNKNOWN);
                                break;
                            }
                            // we have a new scanning interface, make sure scanner knows we aren't
                            // ready yet and clear out the ScanRequestProxy
                            sendScanAvailableBroadcast(false);
                            // explicitly disable scanning for hidden networks in case we were
                            // previously in client mode
                            mScanRequestProxy.enableScanningForHiddenNetworks(false);
                            mScanRequestProxy.clearScanResults();
    
                            transitionTo(mStartedState);
                            break;
                        default:
                            Log.d(TAG, "received an invalid message: " + message);
                            return NOT_HANDLED;
                    }
                    return HANDLED;
                }
            }

    这里我们查看setupInterfaceForClientMode方法

    frameworks\base\wifi\java\android\net\wifi\WifiManager.java

     /**
         * 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;
            }
        }

    可以看到这是过去需要开启wifi的设备节点的地方,然后查看createStaIface方法

     /**
         * Helper function to handle creation of STA iface.
         * For devices which do not the support the HAL, this will bypass HalDeviceManager &
         * teardown any existing iface.
         */
        private String createStaIface(@NonNull Iface iface, boolean lowPrioritySta) {
            synchronized (mLock) {
                if (mWifiVendorHal.isVendorHalSupported()) {
                    return mWifiVendorHal.createStaIface(lowPrioritySta,
                            new InterfaceDestoyedListenerInternal(iface.id));
                } else {
                    Log.i(TAG, "Vendor Hal not supported, ignoring createStaIface.");
    			   //通过打印LOG发现最终我这套代码是走到了这里
    				return handleIfaceCreationWhenVendorHalNotSupported(iface);
    				
                }
            }
        }

    接着查看handleIfaceCreationWhenVendorHalNotSupported

    
        // For devices that don't support the vendor HAL, we will not support any concurrency.
        // So simulate the HalDeviceManager behavior by triggering the destroy listener for
        // any active interface.
        private String handleIfaceCreationWhenVendorHalNotSupported(@NonNull Iface newIface) {
            synchronized (mLock) {
                Iface existingIface = mIfaceMgr.removeExistingIface(newIface.id);
                if (existingIface != null) {
                    onInterfaceDestroyed(existingIface);
                    Log.i(TAG, "Successfully torn down " + existingIface);
                }
                // Return the interface name directly from the system property.
                return mPropertyService.getString("wifi.interface", "wlan0");
            }
        }
    
      /** Helper method invoked to teardown iface and perform necessary cleanup */
        private void onInterfaceDestroyed(@NonNull Iface iface) {
            synchronized (mLock) {
                if (iface.type == Iface.IFACE_TYPE_STA) {
                    onClientInterfaceDestroyed(iface);
                } else if (iface.type == Iface.IFACE_TYPE_AP) {
                    onSoftApInterfaceDestroyed(iface);//这里最终执行了关闭热点
                }
                // Invoke the external callback.
                iface.externalListener.onDestroyed(iface.name);
            }
        }

    通过上述可以发现,我们只需要修改onInterfaceDestroyed handleIfaceCreationWhenVendorHalNotSupported createStaIface三个方法中的任何一个就可以让开wifi时不要不关闭热点,当然个人建议修改createStaIface方法

    展开全文
  • 我的三星N8000刷机Android 11wifi连上提示网络连接受限,无法上网,通过该adb命令工具,ADB_Fastboot.zip,执行了以下两条命令,并将飞行模式启用和关闭一下,然后就可以上网了。 亲测可用! adb命令如下: ...
  • 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...
  • 由于Mac具有稳定流畅的系统,因而...同时也耗费时间,而今天为用户带来了Mac电脑WiFi无法打开的解决教程,您仅需三两步即可自己解决WiFi无法正常开启的问题,赶紧学习一下吧!方法/步骤1,首先,我们先在桌面上打开F...
  • 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...
  • wifi打开关闭

    2011-05-19 15:02:19
    在wince下进行wifi打开关闭,基于VC++
  • 打印机开关 通过TP-Link智能WiFi插头打开关闭打印机的小服务
  • WiFi打开流程(详细)

    2020-11-18 16:15:06
    首先,与Wifi相关的类WifiEnabler管理着WiFi打开/关闭/扫描等事项。那么WiFi打开流程必然是从WifiEnable这个类开始的。(由于列出全部方法体会使篇幅较长,故只列出重要部分,但读者可参照路径与方法名找到具体方法...
  • Android编程打开WiFi

    2021-05-28 08:08:30
    工作以后做的是手机WiFi相关的工作,有时会用到很多操作WiFi的Android软件,但是因为需求不同,现有的apk或多或少的不能满足工作使用需求,所以一直想自己动手写个apk,满足工作使用.但是鉴于以前几乎从没有接触过Android...
  • Android 9.0 Wifi开关状态值的保存和开机打开Wifi的流程 我们在Android系统关开机之后会发现Wifi仍然保持着上一次关机时的状态,而且是进入home界面之后...我们每次打开关闭wifi都需要调用WifiManger.setWifi...
  • win10系统wlan打开关闭的解决方法

    千次阅读 2020-12-23 16:55:38
    很多小伙伴都遇到过win10系统wlan打开关闭的困惑吧,一些朋友看过网上零散的win10系统wlan打开关闭的处理方法,并没有完完全全明白win10系统wlan打开关闭是如何解决的,今天小编准备了简单的解决办法,只需要...
  • 网络切换器 背景扫描仪,根据与给定 Estimote Beacon 的接近程度,打开关闭 WiFi
  • wifi连接与关闭打开

    2015-07-31 14:57:47
    wifi的连接扫瞄 打开 关闭
  • Alfred WiFi工作流程 非常简单的工作流程,可从Alfred打开/关闭WiFi 安装 检查以获取最新打包的工作流程 用法 开启wifi on会开启wifi wifi off会关闭wifi
  • wifi自动连接,断开连接,打开关闭,亲测有效 step1: 导入依赖 D:\workspace\WifiTwo\app\build.gradle implementation 'androidx.appcompat:appcompat:1.1.0' implementation '...
  • 最近看到网上有网友在咨询这样的问题,很多用户为了防止路由器wifi被蹭网,将路由器SSID广播关闭(或隐藏)了,然后就不知道如何连接上网了,下面就来以安卓“路由器SSID广播关闭后怎么才能连接上网?”最近看到网上...
  • 步骤1:打开命令提示符1。打开“开始”菜单2。在搜索栏中输入命令提示符3。 右键单击命令提示符它应列在“程序”...查找您的wifi适配器的索引号第3步:键入命令以关闭wifi1。 键入wmic路径win32_networkadapter,其...
  • win10移动热点按钮打开后立刻自动关闭 问题如图: 解决措施 Windows+R,输入services.msc(或者打开任务管理器,点开“详细信息”,找到顶部的“服务”按钮,然后打开底部的“打开服务”) 打开本地服务,找到...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 39,797
精华内容 15,918
关键字:

wifi打开后自己关闭