Android以编程方式打开/关闭WiFi热点
是否有API可以通过编程方式打开/关闭Android上的WiFi热点 我应该调用什么方法来打开/关闭它Android以编程方式打开/关闭WiFi热点,android,wifi,android-wifi,Android,Wifi,Android Wifi,是否有API可以通过编程方式打开/关闭Android上的WiFi热点 我应该调用什么方法来打开/关闭它 更新:有此选项可以启用热点,只需打开/关闭WiFi,但这对我来说不是一个好的解决方案。您最好的选择是查看WifiManager类。特别是setWifiEnabled(bool)功能 请参阅以下网址的文档: 有关如何使用它(包括您需要的权限)的教程可在此处找到: 其中状态可能为true或false 添加权限清单:警告此方法在5.0之后无法工作,它是一个非常过时的条目 您可以使用以下代码以编程
更新:有此选项可以启用热点,只需打开/关闭WiFi,但这对我来说不是一个好的解决方案。您最好的选择是查看WifiManager类。特别是
setWifiEnabled(bool)
功能
请参阅以下网址的文档:
有关如何使用它(包括您需要的权限)的教程可在此处找到:
其中状态可能为true
或false
添加权限清单:
警告此方法在5.0之后无法工作,它是一个非常过时的条目
您可以使用以下代码以编程方式启用、禁用和查询wifi direct状态
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;
}
}
}
这对我来说很有效:
WifiConfiguration apConfig = null;
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
method.invoke(wifimanager, apConfig, true);
警告此方法在5.0之后无法使用,它是一个非常过时的条目。 使用下面的类更改/检查
Wifi热点设置:
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
<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.isApOn(YourActivity.this); // check Ap state :boolean
ApManager.configApState(YourActivity.this); // change Ap state :boolean
您需要将以下权限添加到您的AndroidMainfest:
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
<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.isApOn(YourActivity.this); // check Ap state :boolean
ApManager.configApState(YourActivity.this); // change Ap state :boolean
希望这将帮助某人我已经发布了非官方的api,它包含的不仅仅是热点打开/关闭
对于Android 8.0的API文档-。,有一个新的API来处理热点。据我所知,使用反射的旧方法已经不起作用了。 请参阅: 安卓开发者 请求一个本地专用热点,应用程序可以使用该热点在连接到创建的WiFi热点的同一位置设备之间进行通信。通过此方法创建的网络将无法访问Internet 堆栈溢出
如果热点处于打开状态,则将调用onStarted(WifiManager.localonlyhotspotpreservation)方法。。使用WifiManager.localonlyhotspotpreservation引用调用close()方法关闭热点
仅适用于Oreo+。 我制作了一个应用程序,其代码使用反射和“获取”Oreo的栓系功能,该功能现在位于
ConnectionManager
,而不是WifiManager
WifiManager
中的内容仅适用于封闭的wifi网络(这解释了类名中的封闭位!)
更多的解释 **奥利奥和馅饼**我在下面找到了方法
private WifiManager.localonlyhotspotpreservation mReservation;
私有布尔值isHotspotEnabled=false;
私有最终整数请求\启用\位置\系统\设置=101;
私有布尔值isLocationPermissionEnable(){
if(ActivityCompat.checkSelfPermission(此,Manifest.permission.ACCESS\u位置)!=PackageManager.permission\u已授予){
ActivityCompat.requestPermissions(这是一个新字符串[]{Manifest.permission.ACCESS\u\u LOCATION},2);
返回false;
}
返回true;
}
@RequiresApi(api=Build.VERSION\u CODES.O)
私有void turnonhospot(){
如果(!isLocationPermissionEnable()){
返回;
}
WifiManager=(WifiManager)getApplicationContext().getSystemService(Context.WIFI_服务);
if(manager!=null){
//启动时不启动(已存在)
manager.startOcalOnlyHotSpot(新的WifiManager.LocalOnlyHotspotCallback(){
@凌驾
已启动公共void(WifiManager.localonlyhotspottreservation){
超级启动(预订);
//Log.d(标记“Wifi热点已打开”);
M保留=保留;
isHotspotEnabled=true;
}
@凌驾
公共空间{
super.onStopped();
//Log.d(标签“onStopped:”);
isHotspotEnabled=false;
}
@凌驾
public void onFailed(内部原因){
super.onFailed(原因);
//Log.d(标记“onFailed:”);
isHotspotEnabled=false;
}
},新处理程序());
}
}
@RequiresApi(api=Build.VERSION\u CODES.O)
专用无效关闭热点(){
如果(!isLocationPermissionEnable()){
返回;
}
if(mReservation!=null){
mReservation.close();
isHotspotEnabled=false;
}
}
@RequiresApi(api=Build.VERSION\u CODES.O)
私有void toggleHotspot(){
如果(!isHotspotEnabled){
打开热点();
}否则{
关闭热点();
}
}
@RequiresApi(api=Build.VERSION\u CODES.O)
私有void enableLocationSettings(){
LocationRequest MLLocationRequest=新的LocationRequest();
/*mLocationRequest.setInterval(10);
M定位请求。设置最小位移(10);
mlLocationRequest.SetFastTestInterval(10);
mLocationRequest.setPriority(位置请求.优先级高精度)*/
LocationSettingsRequest.Builder=新建LocationSettingsRequest.Builder();
builder.addLocationRequest(mlLocationRequest)
.setAlwaysShow(false);//显示对话框
Task Task=LocationServices.getSettingsClient(this.checkLocationSettings(builder.build());
task.addOnCompleteListener(task1->{
试一试{
LocationSettingsResponse-response=task1.getResult(ApiException.class);
//满足所有位置设置。客户端可以初始化位置
//请求在这里。
切换热点();
}捕获(ApiException异常){
开关(异常。getStatusCode()){
案例位置设置StatusCodes.RESOLUTION_要求:
//不满足位置设置。但可以通过显示
//用户创建一个对话框。
试一试{
//强制转换为可解决的异常。
ResolvableApiException resolvable=(ResolvableApiException)异常;
//通过调用startResolu显示对话框
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'
setWifiApDisable.invoke(connectivityManager, TETHERING_WIFI);//Have to disable to enable
setwifiApEnabled.invoke(connectivityManager, TETHERING_WIFI, false, mSystemCallback,null);
<uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
private boolean showWritePermissionSettings() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
if (!Settings.System.canWrite(this)) {
Log.v("DANG", " " + !Settings.System.canWrite(this));
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + this.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
return false;
}
}
return true; //Permission already given
}
public boolean setWifiEnabled(WifiConfiguration wifiConfig, boolean enabled) {
WifiManager wifiManager;
try {
if (enabled) { //disables wifi hotspot if it's already enabled
wifiManager.setWifiEnabled(false);
}
Method method = wifiManager.getClass()
.getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(wifiManager, wifiConfig, enabled);
} catch (Exception e) {
Log.e(this.getClass().toString(), "", e);
return false;
}
}
private WifiManager wifiManager;
WifiConfiguration currentConfig;
WifiManager.LocalOnlyHotspotReservation hotspotReservation;
@RequiresApi(api = Build.VERSION_CODES.O)
public void turnOnHotspot() {
wifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {
@Override
public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
super.onStarted(reservation);
hotspotReservation = reservation;
currentConfig = hotspotReservation.getWifiConfiguration();
Log.v("DANG", "THE PASSWORD IS: "
+ currentConfig.preSharedKey
+ " \n SSID is : "
+ currentConfig.SSID);
hotspotDetailsDialog();
}
@Override
public void onStopped() {
super.onStopped();
Log.v("DANG", "Local Hotspot Stopped");
}
@Override
public void onFailed(int reason) {
super.onFailed(reason);
Log.v("DANG", "Local Hotspot failed to start");
}
}, new Handler());
}
`
private void hotspotDetaisDialog()
{
Log.v(TAG, context.getString(R.string.hotspot_details_message) + "\n" + context.getString(
R.string.hotspot_ssid_label) + " " + currentConfig.SSID + "\n" + context.getString(
R.string.hotspot_pass_label) + " " + currentConfig.preSharedKey);
}
allprojects {
repositories {
...
jcenter()
}
}
dependencies {
implementation 'com.vkpapps.wifimanager:APManager:1.0.0'
}