Android的开启/关闭WiFi热点编程热点、Android、WiFi

由网友(狗蛋儿)分享简介:有一个API来开启/关闭WiFi热点在Android编程?Is there an API to turn On/Off the WiFi HotSpot on Android programmatically?我应该方法,我应该叫把它开/关?What should methods I should call to...

有一个API来开启/关闭WiFi热点在Android编程?

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

我应该方法,我应该叫把它开/关?

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

更新:有这个选项有热点激活,并且只要打开/关闭无线网络,但是这不是我一个很好的解决方案。

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.

推荐答案

使用下面的类来更改/检查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

您需要添加以下到您的Andr​​oidMainfest的权限:

<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

希望这会帮助别人

阅读全文

相关推荐

最新文章