获取Mac地址getMacAddress

系统获取Mac地址的方法:

        WifiManager wifiManager = (WifiManager) MainActivity.this.getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String mac =   wifiInfo.getMacAddress();

在Android 6后,应用无法用此方法获取Mac地址,系统会核查app的UID
获取WifiInfo

WifiManager.java
    public WifiInfo getConnectionInfo() {
        try {
            return mService.getConnectionInfo(mContext.getOpPackageName());
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }
WifiServiceImpl.java 
@Override
    public WifiInfo getConnectionInfo(String callingPackage) {
		//检查权限
        enforceAccessPermission();
        mLog.info("getConnectionInfo uid=%").c(Binder.getCallingUid()).flush();
        /*
         * Make sure we have the latest information, by sending
         * a status request to the supplicant.
         */
        return mWifiStateMachine.syncRequestConnectionInfo(callingPackage);
    }

WifiStateMachine.java
   /**
     * Get status information for the current connection, if any.
     *
     * @return a {@link WifiInfo} object containing information about the current connection
     */
    public WifiInfo syncRequestConnectionInfo(String callingPackage) {
        int uid = Binder.getCallingUid();
        WifiInfo result = new WifiInfo(mWifiInfo);\
       //检查UID 
        //if (uid == Process.myUid()) return result;
        boolean hideBssidAndSsid = true;
        result.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS);

        IPackageManager packageManager = AppGlobals.getPackageManager();

        try {
        //检查权限 否者WIFIInfo中不写入Mac地址
           // if (packageManager.checkUidPermission(Manifest.permission.LOCAL_MAC_ADDRESS,
           //         uid) == PackageManager.PERMISSION_GRANTED) {
                result.setMacAddress(mWifiInfo.getMacAddress());
           // }
            final WifiConfiguration currentWifiConfiguration = getCurrentWifiConfiguration();
            if (mWifiPermissionsUtil.canAccessFullConnectionInfo(
                    currentWifiConfiguration,
                    callingPackage,
                    uid,
                    Build.VERSION_CODES.O)) {
                hideBssidAndSsid = false;
            }
        } catch (RemoteException e) {
            Log.e(TAG, "Error checking receiver permission", e);
        } catch (SecurityException e) {
            Log.e(TAG, "Security exception checking receiver permission", e);
        }
        if (hideBssidAndSsid) {
            result.setBSSID(WifiInfo.DEFAULT_MAC_ADDRESS);
            result.setSSID(WifiSsid.createFromHex(null));
        }
        return result;
    }

修改后如下方法就能获取Mac地址了

WifiInfo.java
    public String getMacAddress() {
        return mMacAddress;
    }

待验证

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页