Android8.1打开关闭热点简单记录

2020-07-27  本文已影响0人  梧叶已秋声

首先确认ConnectivityService中的startTethering和stopTethering这两个函数中的的参数。例如我目前手上的设备使用的源码如下。

    @Override
    public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
            String callerPkg) {
        ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
        if (!isTetheringSupported()) {
            receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
            return;
        }
        mTethering.startTethering(type, receiver, showProvisioningUi);
    }

    @Override
    public void stopTethering(int type, String callerPkg) {
        ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
        mTethering.stopTethering(type);
    }

由于源码中是startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi, String callerPkg),所以调用getMethod("startTethering", int.class, ResultReceiver.class, boolean.class,String.class);;

    public static void setWifiApEnabledForAndroidO(Context context, boolean isEnable){
        ConnectivityManager connManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

        Field iConnMgrField = null;
        try {
            iConnMgrField = connManager.getClass().getDeclaredField("mService");
            iConnMgrField.setAccessible(true);
            Object iConnMgr = iConnMgrField.get(connManager);
            Class<?> iConnMgrClass = Class.forName(iConnMgr.getClass().getName());

            if(isEnable){
                Method startTethering = iConnMgrClass.getMethod("startTethering", int.class, ResultReceiver.class, boolean.class,String.class);
                startTethering.invoke(iConnMgr, 0, null, true,context.getPackageName());
            }else{
                Method startTethering = iConnMgrClass.getMethod("stopTethering", int.class,String.class);
                startTethering.invoke(iConnMgr, 0,context.getPackageName());
            }

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

然后,加系统权限。最后配置签名文件后编译即可。可参考我之前的记录:使用keytool生成keystore签名文件并在android studio中配置系统签名简单记录

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.test.myapplication"
          android:sharedUserId="android.uid.system"
    >

参考链接:
三、Android开启wifi热点
Android 开启WiFi 热点的一些适配方案

上一篇下一篇

猜你喜欢

热点阅读