?
👉關于作者
眾所周知,人生是一個漫長的流程,不斷克服困難,不斷反思前進的程序,在這個程序中會產生很多對于人生的質疑和思考,于是我決定將自己的思考,經驗和故事全部分享出來,以此尋找共鳴 !!!
專注于Android/Unity和各種游戲開發技巧,以及各種資源分享(網站、工具、素材、原始碼、游戲等)
有什么需要歡迎私我,交流群讓學習不再孤單,
👉實踐程序
😜方式一
用過linux的都知道有這樣一行命令:cat /proc/meminfo 查詢記憶體使用詳情檔案(查詢CPU使用詳情檔案:cat / proc/cpuinfo),查詢結果如圖:

如果你需要查詢的是手機的記憶體,只要在cat命令前 加 adb shell即可
😜方式二
我們可以通過MemoryInfo獲取(遺憾的是這里只能獲取到剩余記憶體):
/**
* 獲取當前可用記憶體,回傳資料以位元組為單位,
* @author https://zhima.blog.csdn.net/
* @param context 可傳入應用程式背景關系,
* @return 當前可用記憶體,
*/
private static long getAvailableMemory(Context context) {
ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
//利用ActivityManager的getMemoryInfo獲取到記憶體的一些資訊賦給info
getActivityManager(context).getMemoryInfo(info);
long availableSize = info.availMem; //availMem為系統可用記憶體
return availableSize;
} /**
*
* @param context 可傳入應用程式背景關系,
* @return ActivityManager的實體,用于獲取手機可用記憶體,
*/
private static ActivityManager getActivityManager(Context context) {
if (mActivityManager == null) {
mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
}
return mActivityManager;
}
其中除了availMem還用3個引數
long型別 totalMem 內核RAM的總記憶體
long型別 threshold 當系統剩余記憶體低于 threshold 時就看成低記憶體運行
boolean型別 lowMemory 系統是否處于低記憶體運行
注意:不過,這三個沒用過,不知道能不能用,有機會試試!
😜方式三
既然命令列可以打開檔案,那么我們自然能夠想到通過讀取檔案流的方式獲取:
public static String getUsedPercentValue(Context context) {
//記憶體資訊檔案(CPU資訊檔案:/proc/cpuinfo)
String dir = "/proc/meminfo";
try {
FileReader fr = new FileReader(dir);
//創建讀取字符流快取區
BufferedReader br = new BufferedReader(fr, 2048);
//讀取第一行字符
String memoryLine = br.readLine();
String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
memoryLine = br.readLine();
String availableMemoryLine = memoryLine.substring(memoryLine.indexOf("MemFree:"));
br.close();
//獲取總的記憶體,這里需要注意的是replaceAll支持正則運算式"\\D"代表所有的字母字符,只保留數字部分
long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""));
//獲取當前可用記憶體
long availableSize = Integer.parseInt(availableMemoryLine.replaceAll("\\D+", ""));
int percent = (int) ((totalMemorySize - availableSize) / (float) totalMemorySize * 100);
return percent + "%";
} catch (IOException e) {
e.printStackTrace();
}
return "懸浮窗";
}
?
👉其他
📢作者:小空和小芝中的小空
📢轉載說明-務必注明來源:https://zhima.blog.csdn.net/
📢歡迎點贊👍收藏🌟留言📝
?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/342253.html
標籤:其他
上一篇:Swift 基本資料型別
