代码地址以下:<br>http://www.demodashi.com/demo/13907.htmlhtml
###1、准备工做 开发环境: jdk1.8 AS(3.0.1) 运行环境: 华为V10(Android8.0)、华为p20(Android8.1)、华为mate10(Android8.0)android
实现功能: Wifi热点的开启关闭。微信
Android 7.0及之前Wifi热点 Android 7.一、8.0Wifi热点app
看以前评论发现Android7.1以上的手机开启Wifi热点后不能正常使用,故研究了一下如何解决次问题。ide
在Android7.0及之前的版本开启Wifi热点的方式以下:gradle
WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); //反射 method.invoke(mWifiManager, null, false);
对于Android7.一、8.0的设备,经过WifiManager setWifiApEnabled,能够打开Wifi热点,可是会发现此热点,链接不上(因为DHCP没有开启),因此不会分配ip地址,也就致使不能正常使用。ui
在Android7.1系统应用Settings,发现其开启热点的方式是经过ConnectivityManager的startTethering方法来开启的。 查看ConnectivityManager的方法
startTethering 是隐藏的方法,而且第三个参数OnStartTetheringCallback是ConnectivityManager内部抽象类,也是隐藏的。lua
/** * Callback for use with {@link #startTethering} to find out whether tethering succeeded. * @hide */ @SystemApi public static abstract class OnStartTetheringCallback { /** * Called when tethering has been successfully started. */ public void onTetheringStarted() {}; /** * Called when starting tethering failed. */ public void onTetheringFailed() {}; }
经过反射的方式并无找到方式获取startTethering方法,以及建立OnStartTetheringCallback子对象。spa
后来经过另外一种方式实现了。.net
首先修改ConnectivityManager源码,将TETHERING_WIFI字段、startTethering方法及OnStartTetheringCallback类中隐藏相关的标志去掉,而后单独编译一个jar包。 将jar包拷贝到工程中,以下所示: 该jar包会和官方sdk中的android.jar会有冲突,因此须要配置jar包的优先级。 在app的build.gradle中配置
provided files('src/main/libs/WifiAp8.jar')
在工程下的build.gradle中添加以下配置:
allprojects { gradle.projectsEvaluated { tasks.withType(JavaCompile) { //设置jar相对包路径或绝对路径 options.compilerArgs.add('-Xbootclasspath/p:app/src/main/libs/WifiAp8.jar') } } }
<font color=#0099ff size=4>开启热点</font>
if(getWifiAPState() != WIFI_AP_STATE_ENABLED){ //Android7.1及以上版本 if (Build.VERSION.SDK_INT >= 25) { mConnectivityManager.startTethering(ConnectivityManager.TETHERING_WIFI, true, new ONStartTetheringCallback()); } }
在AS中上述代码会有红色显示,可是不影响编译使用。能够正常编译生成apk。使用该方法不须要提早关闭wifi。
ONStartTetheringCallback类继承了OnStartTetheringCallback抽象类。
class ONStartTetheringCallback extends ConnectivityManager.OnStartTetheringCallback { }
<font color=#0099ff size=4>关闭热点</font>
if(getWifiAPState() != WIFI_AP_STATE_DISABLED){ //Android7.1及以上版本 if (Build.VERSION.SDK_INT >= 25) { mConnectivityManager.stopTethering(ConnectivityManager.TETHERING_WIFI); } }
<font color=#0099ff size=4>权限</font> 使用上述功能须要这三个权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" />
还须要在代码中申请WRITE_SETTINGS权限,不然不能正常使用。
这样就能够了,不仅是系统应用能够使用,平成的应用也能够正常使用。亲测(华为P20、华为mate十、华为V10均可以正常使用)。
欢迎你们关注、评论、点赞。 大家的支持是我坚持的动力。
Android WiFi热点7.1以上版本适配
代码地址以下:<br>http://www.demodashi.com/demo/13907.html
注:本文著做权归做者,由demo大师代发,拒绝转载,转载须要做者受权