Android 以编程方式打开/关闭 WiFi 热点 [英] Android turn On/Off WiFi HotSpot programmatically

查看:60
本文介绍了Android 以编程方式打开/关闭 WiFi 热点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 API 可以通过编程方式在 Android 上打开/关闭 WiFi 热点?

Is there an API to turn On/Off the WiFi HotSpot on Android programmatically?

我应该调用什么方法来打开/关闭它?

What methods should I call to turn it On/Off?

更新:有这个选项可以启用热点,只需打开/关闭 WiFi,但这对我来说不是一个好的解决方案.

UPDATE:There's this option to have the HotSpot enabled, and just turn On/Off the WiFi, but this is not a good solution for me.

推荐答案

警告 此方法在 5.0 后无法使用,这是一个相当过时的条目.

使用下面的类来更改/检查Wifi hotspot设置:

Use the class below to change/check the Wifi hotspot setting:

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

您需要将以下权限添加到您的 AndroidMainfest:

<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

希望这对某人有帮助

这篇关于Android 以编程方式打开/关闭 WiFi 热点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆