1. Core code
MainUseMac.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 corresponds to Android 11 -->30 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { //Do what you want here 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("Get current data", "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){ // Use WifiManager to get the Mac address WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = null; if (wifiManager != null) { wifiInfo = wifiManager.getConnectionInfo(); } // Get Mac address 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 { // Create a directory //Get internal storage status String state = Environment.getExternalStorageState(); //If the status is not mounted, it cannot be read or written. 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;//Here is creating a TXT file to save our UUID File file = new File(appDir, fileName); if (!file.exists()) { file.createNewFile(); } //Save the android unique identifier 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 { // Create a directory //Get internal storage status String state = Environment.getExternalStorageState(); //If the status is not mounted, it cannot be read or written. 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;//This is the name of the file we save when reading it 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("Get current data", "network type:" + networkType); if(networkType == ConnectivityManager.TYPE_WIFI){ return "WIFI"; }else if((networkType == ConnectivityManager.TYPE_ETHERNET)){ return "wired"; }else{ return "WIFI"; } } //Get wireless mac address 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(" X", b)); } String s1 = result.toString().toUpperCase().replaceAll ("(.{2})", "$1:");//Add: return s1.substring(0,s1.length()-1); } } catch (Exception x) { x.printStackTrace(); } return ""; } //Get the wired mac address 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(" X", b)); } String s1 = result.toString().toUpperCase().replaceAll ("(.{2})", "$1:");//Add: return s1.substring(0,s1.length()-1); } } catch (Exception x) { x.printStackTrace(); } return ""; } }
Let’s talk about using
2. Get mac
2.1.Modification
Mainly, the method commented out below is to obtain mac, suitable for Android 11 and below.
public static final String main(Context context) { return TVMac(context); }
2.2.Use
Comment out the uuid part of the main method
UseMac.main(activity)
3. Get uuid
There is a class here that will actively apply for permissions for you.
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 { //Check whether there is write permission int permission = ActivityCompat.checkSelfPermission(activity, "android.permission.WRITE_EXTERNAL_STORAGE"); if (permission != PackageManager.PERMISSION_GRANTED) { // If you don’t have write permission, apply for write permission, and a dialog box will pop up. ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); } } catch (Exception e) { e.printStackTrace(); } } //flie: The location of the folder to be deleted public void deleteFile(File file) { Log.e("TestFile","Clear the video cache"); if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i + + ) { File f = files[i]; deleteFile(f); } // file.delete();//If you want to keep the folder and only delete the files, please comment this line } 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); } //Write string to text file private void writeTxtToFile(String strcontent, String filePath, String fileName) { //After generating the folder, generate the file, otherwise an error will occur makeFilePath(filePath, fileName); String strFilePath = filePath + fileName; //Every time you write, write in a new line String strContent = strcontent + "\r\\ "; 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); } } //generate file 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; } //Determine whether the file exists public boolean fileIsExists(String strFile) { try { File f = new File(strFile); if (!f.exists()) { return false; } } catch (Exception e) { return false; } return true; } //generate folder public void makeRootDirectory(String filePath) { File file = null; try { file = new File(filePath); //If it does not exist, create a new one if (!file.exists()) { file.mkdir(); } } catch (Exception e) { Log.i("error:", e + ""); } } //Delete the file at the specified path public boolean deleteSingleFile(String filePath$Name) { File file = new File(filePath$Name); // If the file corresponding to the file path exists and is a file, delete it directly if (file.exists() & amp; & amp; file.isFile()) { if (file.delete()) { Log.e("--Method--", "Delete file" + filePath$Name + "Success!"); return true; } else { Log.e("--Method--", "Delete file" + filePath$Name + "Failed!"); return false; } } else { Log.e("--Method--", "File" + filePath$Name + "Does not exist!"); return true; } } /** * Read local files */ 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 bufferreader = 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();//Decrypt the read device ID } }
//Read uuid fileOper = new FileOper(this); try { if(fileOper.fileIsExists(Environment.getExternalStorageDirectory().getAbsolutePath() + uuidfileName)){ UseMac.saveBitmap(); } }catch(Exception e){ System.out.println("base64Code:::" + e.toString()); //Exception handling }
3.1.Modification
public static final String main(Context context) { //return TVMac(context); String uuid = ""; try { uuid = readKey(); } catch (IOException e) { e.printStackTrace(); } return uuid; }