Android:获取MAC < 安卓系统11 <= 获取UUID

1.核心代码

主要的UseMac.java

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

public class UseMac {

    public static final String main(Context context) {
        //R对应安卓11  -->30
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            //这里做你想做的事
            String uuid = "";
            try {
                uuid = readKey();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return uuid;
        }else {
            return TVMac(context);
       }
    }



    private static String TVMac(Context context){
        int networkType;
        final ConnectivityManager connectivityManager= (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") final NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
        networkType=networkInfo.getType();
        Log.d("获取当前数据", "network type:"+networkType);
        if(networkType == ConnectivityManager.TYPE_WIFI){
            return getMac_wlan0();
        }else if((networkType == ConnectivityManager.TYPE_ETHERNET)){
            return getMac_eth0();
        }else{
            return getMac_wlan0();
        }
    }


    //====11-----G
        public static String Android11Mac(Context context){
        // 使用WifiManager获取Mac地址
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = null;
        if (wifiManager != null) {
            wifiInfo = wifiManager.getConnectionInfo();
        }

        // 获取Mac地址
        String macAddress = null;
        if (wifiInfo != null) {
            macAddress = wifiInfo.getMacAddress();
            Log.e("macAddress","====>>"+macAddress);
        }


        return macAddress;
    }


    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }



    private static String uuidfileName = "myuuid.txt";
    public static void saveBitmap() throws IOException {
        // 创建目录
        //获取内部存储状态
        String state = Environment.getExternalStorageState();
        //如果状态不是mounted,无法读写
        if (!state.equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        String sdCardDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        File appDir = new File(sdCardDir, "CaChe");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = uuidfileName;//这里是创建一个TXT文件保存我们的UUID
        File file = new File(appDir, fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        //保存android唯一表示符
        try {
            FileWriter fw = new FileWriter(file);
            fw.write(getUUID());
            fw.flush();
            fw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }





    public static String readKey() throws IOException {
        // 创建目录
        //获取内部存储状态
        String state = Environment.getExternalStorageState();
        //如果状态不是mounted,无法读写
        if (!state.equals(Environment.MEDIA_MOUNTED)) {
            return null;
        }
        String sdCardDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        File appDir = new File(sdCardDir, "CaChe");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = uuidfileName;//这里是进行读取我们保存文件的名称
        File file = new File(appDir, fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        BufferedReader reader = null;
        StringBuilder content=null;
        try {
            FileReader fr = new FileReader(file);
            content= new StringBuilder();
            reader = new BufferedReader(fr);
            String line;
            while ((line= reader.readLine())!=null){
                content.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (reader!=null){
                try {
                    reader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }






    public static final String getNetName(Context context) {
        int networkType;
        final ConnectivityManager connectivityManager= (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") final NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
        networkType=networkInfo.getType();
        Log.d("获取当前数据", "network type:"+networkType);
        if(networkType == ConnectivityManager.TYPE_WIFI){
            return "WIFI";
        }else if((networkType == ConnectivityManager.TYPE_ETHERNET)){
            return "有线";
        }else{
            return "WIFI";
        }
    }

    //获取无线mac地址
    public static final String getMac_wlan0() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!"wlan0".equalsIgnoreCase(nif.getName())) {
                    continue;
                }
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null || macBytes.length == 0) {
                    continue;
                }
                StringBuilder result = new StringBuilder();
                for (byte b : macBytes) {
                    result.append(String.format("%02X", b));
                }

                String s1 = result.toString().toUpperCase().replaceAll ("(.{2})", "$1:");//加入:

                return s1.substring(0,s1.length()-1);
            }
        } catch (Exception x) {
            x.printStackTrace();
        }
        return "";
    }

    //获取有线mac地址
    public static String getMac_eth0() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!"eth0".equalsIgnoreCase(nif.getName())) {
                    continue;
                }
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null || macBytes.length == 0) {
                    continue;
                }
                StringBuilder result = new StringBuilder();
                for (byte b : macBytes) {
                    result.append(String.format("%02X", b));
                }
                String s1 = result.toString().toUpperCase().replaceAll ("(.{2})", "$1:");//加入:
                return s1.substring(0,s1.length()-1);
            }
        } catch (Exception x) {
            x.printStackTrace();
        }
        return "";
    }


}

下面说一下使用

2.获取mac

2.1.修改

主要是在 下面这个方法注释掉的是获取mac的,适合安卓11以下

    public static final String main(Context context) {
        return TVMac(context);
    }

2.2.使用

把main方法的uuid部分注释掉

复制代码
UseMac.main(activity)

3.获取uuid

这边有一个类,会主动给你申请权限

import android.app.Activity;
import android.content.pm.PackageManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

public class FileOper {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
    private Activity activity;
    public FileOper(Activity activity) {
        this.activity =activity;
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限,去申请写的权限,会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //flie:要删除的文件夹的所在位置
    public void deleteFile(File file) {
        Log.e("TestFile","清除一下视频缓存");
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            // file.delete();//如要保留文件夹,只删除文件,请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }


    public void writeData(String url, String name, String content) {
        String filePath = url;
        String fileName = name + ".txt";
        writeTxtToFile(content, filePath, fileName);
    }

    // 将字符串写入到文本文件中
    private void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后,再生成文件,不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        // 每次写入时,都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    //生成文件
    private File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }


    //判断文件是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    //生成文件夹
    public void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            //不存在就新建
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

    //删除指定路径的文件
    public boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.e("--Method--", "删除文件" + filePath$Name + "成功!");
                return true;
            } else {
                Log.e("--Method--", "删除文件" + filePath$Name + "失败!");
                return false;
            }
        } else {
            Log.e("--Method--", "文件" + filePath$Name + "不存在!");
            return true;
        }
    }

    /**
     * 读取本地文件
     */
    public String readRate(String path) {

        StringBuilder stringBuilder = new StringBuilder();
        File file = new File(path);
        if (!file.exists()) {
            return "";
        }
        if (file.isDirectory()) {
            Log.e("TestFile", "The File doesn't not exist.");
            return "";
        } else {
            try {
                InputStream instream = new FileInputStream(file);
                if (instream != null) {
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    while ((line = buffreader.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                    instream.close();
                }
            } catch (java.io.FileNotFoundException e) {
                Log.e("TestFile", "The File doesn't not exist.");
                return "";
            } catch (IOException e) {
                Log.e("TestFile", e.getMessage());
                return "";
            }
        }
        return stringBuilder.toString();//对读到的设备ID解密
    }
}

        //读取uuid
        fileOper = new FileOper(this);
        try {
            if(fileOper.fileIsExists(Environment.getExternalStorageDirectory().getAbsolutePath()+uuidfileName)){
                UseMac.saveBitmap();
            }
        }catch(Exception e){
            System.out.println("base64Code:::"+e.toString());//出现异常的处理
        }

3.1.修改

    public static final String main(Context context) {

       //return TVMac(context);
        String uuid = "";
        try {
            uuid = readKey();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uuid;
    }

3.2.使用

就比较简单了

在activity里面调用

        //读取uuid
        fileOper = new FileOper(this);
        try {
            if(fileOper.fileIsExists(Environment.getExternalStorageDirectory().getAbsolutePath()+uuidfileName)){
                UseMac.saveBitmap();
            }
        }catch(Exception e){
            System.out.println("base64Code:::"+e.toString());//出现异常的处理
        }
相关推荐
大耳猫4 小时前
主动测量View的宽高
android·ui
帅次6 小时前
Android CoordinatorLayout:打造高效交互界面的利器
android·gradle·android studio·rxjava·android jetpack·androidx·appcompat
枯骨成佛7 小时前
Android中Crash Debug技巧
android
kim565912 小时前
android studio 更改gradle版本方法(备忘)
android·ide·gradle·android studio
咸芝麻鱼12 小时前
Android Studio | 最新版本配置要求高,JDK运行环境不适配,导致无法启动App
android·ide·android studio
无所谓จุ๊บ12 小时前
Android Studio使用c++编写
android·c++
csucoderlee13 小时前
Android Studio的新界面New UI,怎么切换回老界面
android·ui·android studio
kim565913 小时前
各版本android studio下载地址
android·ide·android studio
饮啦冰美式13 小时前
Android Studio 将项目打包成apk文件
android·ide·android studio
夜色。13 小时前
Unity6 + Android Studio 开发环境搭建【备忘】
android·unity·android studio