是否有API以编程方式打开/关闭Android上的WiFi HotSpot?
我应该用什么方法打开/关闭它?
更新:有这个选项可以启用HotSpot,只需打开/关闭WiFi,但这对我来说不是一个好的解决方案。
使用下面的类来更改/检查Wifi hotspot
设置:
import android.content.*;
import android.net.wifi.*;
import java.lang.reflect.*;
public class ApManager {
//check whether wifi hotspot on or off
public static boolean isApOn(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
try {
Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled");
method.setAccessible(true);
return (Boolean) method.invoke(wifimanager);
}
catch (Throwable ignored) {}
return false;
}
// toggle wifi hotspot on or off
public static boolean configApState(Context context) {
WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
WifiConfiguration wificonfiguration = null;
try {
// if WiFi is on, turn it off
if(isApOn(context)) {
wifimanager.setWifiEnabled(false);
}
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
method.invoke(wifimanager, wificonfiguration, !isApOn(context));
return true;
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
} // end of class
您需要将以下权限添加到AndroidManifest:
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
从任何地方使用此独立的ApManager类,如下所示:
ApManager.isApOn(YourActivity.this); // check Ap state :boolean
ApManager.configApState(YourActivity.this); // change Ap state :boolean
希望这会对某人有所帮助
我们可以通过编程方式打开和关闭
btnHotspot.setOnClickListenr(view -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Step 1: Enable the location settings use Google Location Service
// Step 2: https://stackoverflow.com/questions/29801368/how-to-show-enable-location-dialog-like-google-maps/50796199#50796199
// Step 3: If OK then check the location permission and enable hotspot
// Step 4: https://stackoverflow.com/questions/46843271/how-to-turn-off-wifi-hotspot-programmatically-in-android-8-0-oreo-setwifiapen
enableLocationSettings();
return;
}
}
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
implementation 'com.google.android.gms:play-services-location:15.0.1'
使用回调类,以编程方式打开饼图(9.0)中的热点,您需要以编程方式关闭并打开。
您可以使用该选项的控制台和服务。
我认为你可以解决这个问题。我直接在控制台中进行了测试并启用了热点
我在这篇文章setWifiApDisable.invoke(connectivityManager, TETHERING_WIFI);//Have to disable to enable
setwifiApEnabled.invoke(connectivityManager, TETHERING_WIFI, false, mSystemCallback,null);
中找到了这个
在阅读界面后,我们可以使用相同的24但需要更多参数
服务呼叫连接24 i32 0 i32 1 i32 0 s16随机
Is it possible to USB tether an android device using adb through the terminal?
状态可能是WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);
或true
添加权限清单:false
Android SDK中没有与WiFi热点功能相关的方法 - 抱歉!
您可以使用以下代码以编程方式启用,禁用和查询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;
}
}
}
对于Android 8.0,有一个新的API来处理热点。据我所知,使用反射的旧方法不再适用。请参阅:
void startLocalOnlyHotspot (WifiManager.LocalOnlyHotspotCallback callback,
Handler handler)
请求本地唯一的热点,应用程序可以使用该热点在连接到创建的WiFi热点的共址设备之间进行通信。通过此方法创建的网络将无法访问Internet。
堆栈溢出 How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo)
如果打开热点,将调用onStarted(WifiManager.LocalOnlyHotspotReservation reservation)方法。使用WifiManager.LocalOnlyHotspotReservation引用,调用close()方法关闭热点。
您最好的选择是查看WifiManager课程。特别是setWifiEnabled(bool)
功能。
请参阅以下文档:http://developer.android.com/reference/android/net/wifi/WifiManager.html#setWifiEnabled(boolean)
有关如何使用它的教程(包括您需要的权限)可以在这里找到:http://www.tutorialforandroid.com/2009/10/turn-off-turn-on-wifi-in-android-using.html
仅适用于Oreo + ......
我创建了一个代码为here on GitHub的应用程序,它使用反射和DexMaker来“获取”奥利奥的网络共享功能,现在在ConnectionManager
,而不是WifiManager
。
WifiManager
中的东西仅适用于封闭的wifi网络(它解释了类名中的Closed位!)。
这适合我:
WifiConfiguration apConfig = null;
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
method.invoke(wifimanager, apConfig, true);
我已经发布了非正式的api's,它包含的不仅仅是热点转on/off
。 link
对于API DOC - qazxsw poi。
**对于奥利奥和PIE **我在下面发现了link
through this
使用率
private WifiManager.LocalOnlyHotspotReservation mReservation;
private boolean isHotspotEnabled = false;
private final int REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS = 101;
private boolean isLocationPermissionEnable() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
return false;
}
return true;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOnHotspot() {
if (!isLocationPermissionEnable()) {
return;
}
WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (manager != null) {
// Don't start when it started (existed)
manager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
@Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
//Log.d(TAG, "Wifi Hotspot is on now");
mReservation = reservation;
isHotspotEnabled = true;
}
@Override
public void onStopped() {
super.onStopped();
//Log.d(TAG, "onStopped: ");
isHotspotEnabled = false;
}
@Override
public void onFailed(int reason) {
super.onFailed(reason);
//Log.d(TAG, "onFailed: ");
isHotspotEnabled = false;
}
}, new Handler());
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void turnOffHotspot() {
if (!isLocationPermissionEnable()) {
return;
}
if (mReservation != null) {
mReservation.close();
isHotspotEnabled = false;
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void toggleHotspot() {
if (!isHotspotEnabled) {
turnOnHotspot();
} else {
turnOffHotspot();
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void enableLocationSettings() {
LocationRequest mLocationRequest = new LocationRequest();
/*mLocationRequest.setInterval(10);
mLocationRequest.setSmallestDisplacement(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);*/
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest)
.setAlwaysShow(false); // Show dialog
Task<LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
task.addOnCompleteListener(task1 -> {
try {
LocationSettingsResponse response = task1.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
toggleHotspot();
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(HotspotActivity.this, REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case REQUEST_ENABLE_LOCATION_SYSTEM_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
toggleHotspot();
Toast.makeText(HotspotActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(HotspotActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}