技术求助:如何通过Python代码控制Android设备热点的开启与关闭?
Hey there! I get that you're familiar with building Android apps using Python, but haven't found a way to toggle the device's hotspot via Python code—let's break down how to make this work.
First off, Python can't directly interact with Android's system-level features like hotspot control on its own. You'll need to bridge Python to Android's native Java APIs, and the most reliable tool for this is PyJNIus (a library that lets Python call Java code, commonly used in Kivy or Python-for-Android projects).
Key Prerequisites
- You'll need to set up a Python-for-Android environment (like with Kivy Buildozer) to package your app.
- Add critical permissions to your
AndroidManifest.xml—these are required to access and modify WiFi/hotspot settings:
Note: The<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <!-- For Android 10+ --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />WRITE_SETTINGSpermission is a special system permission—your app will need to prompt users to enable it manually via the device's settings menu.
Implementation by Android Version
Android changed its hotspot API starting from Android 10 (API level 29), so you'll need different code for older vs newer devices.
1. Android 9 (API 28) and Below
These versions allow direct control via the WifiManager.setWifiApEnabled() method. Here's a working code snippet:
from jnius import autoclass, cast # Import required Android Java classes Context = autoclass('android.content.Context') WifiManager = autoclass('android.net.wifi.WifiManager') WifiConfiguration = autoclass('android.net.wifi.WifiConfiguration') Activity = autoclass('android.app.Activity') # Get the current app activity and WifiManager instance activity = Activity.mActivity wifi_manager = cast('android.net.wifi.WifiManager', activity.getSystemService(Context.WIFI_SERVICE)) def create_hotspot_config(ssid, password): """Create a hotspot configuration with SSID and password""" config = WifiConfiguration() config.SSID = f'"{ssid}"' # SSID needs to be wrapped in quotes config.preSharedKey = f'"{password}"' config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN) config.allowedProtocols.set(WifiConfiguration.Protocol.RSN) config.allowedProtocols.set(WifiConfiguration.Protocol.WPA) config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK) return config def toggle_hotspot(enable, ssid="MyPythonHotspot", password="12345678"): """Toggle hotspot on/off""" if enable: # Disable regular WiFi first (some devices require this) wifi_manager.setWifiEnabled(False) hotspot_config = create_hotspot_config(ssid, password) success = wifi_manager.setWifiApEnabled(hotspot_config, True) print(f"Hotspot enabled: {success}") else: success = wifi_manager.setWifiApEnabled(None, False) print(f"Hotspot disabled: {success}")
2. Android 10 (API 29) and Above
The setWifiApEnabled() method was deprecated in Android 10. Instead, you'll use WifiManager.startLocalOnlyHotspot() which creates a local hotspot (no internet sharing by default). Here's how to implement it:
from jnius import autoclass, cast, PythonJavaClass, java_method # Import required Android Java classes Context = autoclass('android.content.Context') WifiManager = autoclass('android.net.wifi.WifiManager') Activity = autoclass('android.app.Activity') # Get the current app activity and WifiManager instance activity = Activity.mActivity wifi_manager = cast('android.net.wifi.WifiManager', activity.getSystemService(Context.WIFI_SERVICE)) # Define a Python callback to handle hotspot events class HotspotCallback(PythonJavaClass): __javainterfaces__ = ['android.net.wifi.WifiManager$LocalOnlyHotspotCallback'] reservation = None @java_method('(Landroid/net/wifi/WifiManager$LocalOnlyHotspotReservation;)V') def onStarted(self, reservation): HotspotCallback.reservation = reservation print("Local hotspot started successfully!") # You can get the hotspot SSID/password from reservation.getWifiConfiguration() @java_method('(I)V') def onStopped(self, reason): print(f"Local hotspot stopped. Reason code: {reason}") HotspotCallback.reservation = None @java_method('(I)V') def onFailed(self, reason): print(f"Failed to start hotspot. Reason code: {reason}") def start_local_hotspot(): """Start a local-only hotspot""" callback = HotspotCallback() wifi_manager.startLocalOnlyHotspot(callback, None) def stop_local_hotspot(): """Stop the local-only hotspot""" if HotspotCallback.reservation is not None: HotspotCallback.reservation.close() print("Local hotspot stopped.")
Important Notes
- For internet-sharing hotspots on Android 10+, Google restricted direct access for third-party apps—you'll need to use system-level APIs or prompt users to enable it manually via settings.
- Always test your code on physical devices (emulators often don't support hotspot functionality).
内容的提问来源于stack exchange,提问作者Guneet Singh




