【Android】获取当前 Wifi 的 MAC 地址(BSSID),注意并非是手机的MAC地址

前言

项目有个很重要的需求,就是获取手机的当前所连Wifi的mac地址注意并非是手机设备的mac地址。方法也是网上找的。

组员大概都用手机测了一遍。测试发现,有一部分手机,除了要授予APP定位权限外,还需要用户手动开启定位服务,才能获取到当前手机所连Wifi的mac地址。可能是Android版本的问题吧,或者是手机厂商的问题?

所以,获取完整的获取逻辑需要:

1、判断手机是否已经连接上某个Wifi

2、判断用户是否已经授予APP定位权限(运行时权限)。如果没有,要向用户请求获取权限

3、判断定位服务(注意不是定位权限)是否已开启。如果没有,要跳转到打开定位服务的界面,让用户手动打开定位服务。

为了方便以后直接复制使用,我完善了一下整个获取的逻辑。

AndroidManifest.xml











MainActivity

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button getinfo;
    private TextView setinfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getinfo = findViewById(R.id.getWiFiinfo);
        setinfo = findViewById(R.id.setWiFiinfo);

        // 点击按钮尝试获取当前Wifi的mac地址
        getinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tryGetWifiMac();
            }
        });
    }

    /**
     * 成功获取到当前的Wifi的bssid(mac地址)之后
     * 做的操作,比如说请求存到服务端
     *
     * @param bssid
     */
    public void onGetMacSucceeded(String bssid) {
        setinfo.setText(TextUtils.isEmpty(bssid) ? "获取失败" : bssid);
    }

    /**
     * 尝试获取Wifi的Mac地址
     *
     * @return
     */
    public void tryGetWifiMac() {
        if (!isWifiEnabled()) {
            Toast.makeText(this, "请连接Wifi", Toast.LENGTH_SHORT).show();
            return;
        }

        int curSdk = Build.VERSION.SDK_INT;
        String bssid = null;
        if (curSdk >= 27) {
            // 判断是否授予APP定位权限
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                return;
            } else {
                if (!isLocationServiceEnable()) {
                    // 让用户手动开启定位服务
                    showLocationAlertDialog();
                    return;
                } else {
                    bssid = getWifiMac();
                }
            }
        } else {
            bssid = getWifiMac();
        }

        onGetMacSucceeded(bssid);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    tryGetWifiMac();
                } else {
                    Toast.makeText(this, "您拒绝了APP启用定位服务",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            default: {
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 1: {
                tryGetWifiMac();
                break;
            }
            default: {
            }
        }
    }

    // 弹出确认提示框,请求用户手动开启定位服务
    private void showLocationAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("APP需要您手动开启定位权限,是否继续?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 1);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        builder.show();
    }

    /**
     * 判断是否已连接Wifi
     *
     * @return
     */
    public boolean isWifiEnabled() {
        Context appContext = getApplicationContext();
        WifiManager wifiMgr = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            ConnectivityManager connManager = (ConnectivityManager) appContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            return wifiInfo.isConnected();
        } else {
            return false;
        }
    }

    /**
     * 获取当前Wifi的mac地址
     *
     * @return
     */
    public String getWifiMac() {
        WifiManager wifiManager = (WifiManager) getApplicationContext()
                .getSystemService(WIFI_SERVICE);
        String bssid = wifiManager.getConnectionInfo().getBSSID();
        return "02:00:00:00:00:00".equals(bssid) ? null : bssid;
    }

    /**
     * 判断当前的手机的定位服务是否已开启
     *
     * @return
     */
    public boolean isLocationServiceEnable() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
                || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    }


    /*
     * 获取 WIFI 的名称
     * */
    public String getWiFiName() {
        WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (wm != null) {
            WifiInfo winfo = wm.getConnectionInfo();
            if (winfo != null) {
                String s = winfo.getSSID();
                if (s.length() > 2 && s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
                    return s.substring(1, s.length() - 1);
                }
            }
        }
        return null;
    }


    /*
     * 获取 WiFi 的 IP 地址
     * */
    public String getWifiIp() {
        WifiManager wifiMgr = (WifiManager) getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);

        if (isWifiEnabled()) {
            int ipAsInt = wifiMgr.getConnectionInfo().getIpAddress();
            String ip = Formatter.formatIpAddress(ipAsInt);
            if (ipAsInt == 0) {
                return "未能获取到IP地址";
            } else {
                return ip;
            }
        } else {
            return "WiFi 未连接";
        }
    }


}

 

你可能感兴趣的:(Android)