这里是一个全新的系列--进程化
组件化模块化延伸后,还能到达进程化。
当你能活用组件化模块化,明白其中的关联之后,再深入探究下去,就会走到进程这一步。
从基础出发,我们说一下进程信息,下面全部使用kotlin编写的api。
获取内存容量
fun getTotalMemSize():Long{
var size=0L
//系统内存文件
val file = File("/proc/meminfo")
try {
val buffer = BufferedReader(InputStreamReader(FileInputStream(file)))
var memInfo = buffer.readLine()
val startIndex = memInfo.indexOf(":")
val endIndex =memInfo.indexOf("k")
memInfo = memInfo.substring(startIndex+1,endIndex).trim()
size = memInfo.toLong()
size *= 1024
buffer.close()
}catch (e:IOException){
e.printStackTrace()
}
return size
}
获取可用内存
fun getAviableMemSize(context:Context):Long{
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
var mi = ActivityManager.MemoryInfo()
am.getMemoryInfo(mi)
return mi.availMem
}
获取当前进程id
fun getCurrentProcessId():Int{
return android.os.Process.myPid()
}
获取当前进程名
fun getCurrentProcessName():String{
var processName = UNKNOWN_PROCESS_NAME
try {
val file = File("/proc/"+ getCurrentProcessId()+"/cmdline")
val buffer = BufferedReader(FileReader(file))
processName = buffer.readLine().trim()
buffer.close()
}catch (e:Exception){
e.printStackTrace()
}
return processName
}
fun getCurrentProcessName():String{
var processName = UNKNOWN_PROCESS_NAME
try {
val file = File("/proc/"+ getCurrentProcessId()+"/cmdline")
val buffer = BufferedReader(FileReader(file))
processName = buffer.readLine().trim()
buffer.close()
}catch (e:Exception){
e.printStackTrace()
}
return processName
}
获取进程名
fun getCurrentProcessName(pid:Int):String{
var processName = UNKNOWN_PROCESS_NAME
try {
val file = File("/proc/"+ pid+"/cmdline")
val buffer = BufferedReader(FileReader(file))
processName = buffer.readLine().trim()
buffer.close()
}catch (e:Exception){
e.printStackTrace()
}
return processName
}
fun getProcessName(context:Context,pid:Int):String{
var processName = getCurrentProcessName(pid)
if (UNKNOWN_PROCESS_NAME .equals(processName)){
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val runningApps = am.runningAppProcesses
if (runningApps!=null){
for (info in runningApps){
if(info.pid == pid) return info.processName
}
}
}
return processName
}
使用命令获取adb手机进程
连接电脑,使用adb shell连接手机。
然后使用ps可以查看全部进程的信息。
这里请注意linux目录中有个/proc的目录,这里记载运行的进程,如果没有root手机取得最高权限是无法查看到进程信息的。
image.png
通过代码获取全部的进程信息
这里需要使用ActivityManager 和PackageManager获取运行进程信息的列表
在5.0以前使用一下的方法来获取
```
/**
* 获取所有进程信息(5.0以前)
*/
fun getTaskInfos(context:Context):List?{
val activityManager:ActivityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager