android获取电量
❶ Android如何得到电量、温度、电压
package com.LB; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Bundle; import android.widget.TextView; public class Battery extends Activity { private int BatteryN; //目前电量 private int BatteryV; //电池电压 private double BatteryT; //电池温度 private String BatteryStatus; //电池状态 private String BatteryTemp; //电池使用情况 public TextView TV; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // 注册一个系统 BroadcastReceiver,作为访问电池计量之用这个不能直接在AndroidManifest.xml中注册 registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); TV = (TextView)findViewById(R.id.TV); } /* 创建广播接收器 */ private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); /* * 如果捕捉到的action是ACTION_BATTERY_CHANGED, 就运行onBatteryInfoReceiver() */ if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { BatteryN = intent.getIntExtra("level", 0); //目前电量 BatteryV = intent.getIntExtra("voltage", 0); //电池电压 BatteryT = intent.getIntExtra("temperature", 0); //电池温度 switch
❷ Android性能测试(内存、cpu、fps、流量、GPU、电量)——adb篇
3)查看进程列表:adb shell "ps",同时也能获取到应用的UID,方式如下(不需root权限):
u0_a开头的都是Android的应用进程,Android的应用的UID是从10000开始,到19999结束,可以在Process.java中查看到(FIRST_APPLICATION_UID和LAST_APPLICATION_UID),u0_a后面的数字就是该应用的UID值减去FIRST_APPLICATION_UID所得的值,所以,对于截图这个应用进程,它是u0_a155,按前面的规制,它的UID就是155 + FIRST_APPLICATION_UID = 10155。
VSS - Virtual Set Size 虚拟耗用内存(包含共享库占用的内存)
RSS - Resident Set Size 实际使用物理内存(包含共享库占用的内存)
PSS - Proportional Set Size 实际使用的物理内存(比例分配共享库占用的内存)
USS - Unique Set Size 进程独自占用的物理内存(不包含共享库占用的内存)
一般来说内存占用大小有如下规律:VSS >= RSS >= PSS >= USS
使用 adb shell "mpsys meminfo -s <pakagename | pid>"命令,输出结果分以下4部分:
PS:在apk内调用运行获取其他app的内存数据则需要root权限
adb命令:adb shell mpsys gfxinfo <package | pid>
正常情况下帧率应该在16.67ms左右,1秒60帧,执行结果如下:
详细计算方法如下:
还有一个命令是: adb shell mpsys SurfaceFlinger --latency LayerName
其中LayerName在各个不同系统中获取的命令是不一样的
在Android 6系统直接就是SurfaceView
在Android 7系统中可以通过 mpsys window windows | grep mSurface | grep SurfaceView 然后通过数据截取到
在Android 8系统中可以通过 mpsys SurfaceFlinger | grep android包名获取到
执行命令结果如下:
计算方法比较简单,一般打印出来的数据是129行(部分机型打印两次257行,但是第一部分是无效数据,取后半部分),取len-2的第一列数据为end_time,取len-128的第一列数据为start_time
fps = 127/((end_time - start_time) / 1000000.0)
至于为啥要取第一列数据,这里不做过多介绍,欢迎参看这两篇文章
老罗的文章SurfaceView原理
Android性能测试之fps获取
至于为啥要处于1000000,因为命令打印出来的是纳秒单位,要转为毫秒进行计算,127就是因为命令一次打印出来127帧的数据而已
有两种方法可以获取
1) adb shell "top -n 5 | grep <package | pid>" ,第三列就是实时监控的CPU占用率(-n 指定执行次数,不需root权限),这边top命令执行需要2到3s左右,一般可以采用busybox 的top命令执行,效率会快很多
2) adb shell "mpsys cpuinfo | grep <package | pid>"
两种方法直接区别在于,top是持续监控状态,而mpsys cpuinfo获取的实时CPU占用率数据
adb命令:adb shell "mpsys batterystats < package | pid>" (Android 5.0后引入)
获取单个应用的耗电量信息,具体返回结果待研究
adb命令:adb shell "mpsys battery"
出现信息解读:
AC powered:false 是否连接AC(电源)充电线
USB powered:true 是否连接USB(PC或笔记本USB插口)充电
Wireless powered:false 是否使用了无线电源
status: 1 电池状态,2为充电状态,其他为非充电状态
level:58 电量(%)
scale: 100. 电量最大数值
voltage: 3977 当前电压(mV)
current now: -335232. 当前电流(mA)
temperature:355 电池温度,单位为0.1摄氏度
adb 命令:adb shell "mpsys< package | pid> | grep UID" [通过ps命令,获取app的UID(安装后唯一且固定)]
adb shell cat /proc/uid_stat/UID/tcp_rcv [cat为查看命令,读取tcp_rcv获取应用接收流量信息(设备重启后清零)]
adb shell cat /proc/uid_stat/UID/tcp_snd [cat为查看命令,读取tcp_snd获取应用发送流量信息(设备重启后清零)]
计算流量消耗步骤:
或者还有一种方式获取应用流量消耗:
首先判断类型:
cat /sys/class/thermal/thermal_zone*/type
只有红框框出来的是有效的
cat /sys/class/thermal/thermal_zone*/temp
获取CPU温度
mpsys battery | grep temperature 单位0.1摄氏度
获取/proc/stat文件内容(无权限限制)
总的cpu时间片是 total = user+nice+system+idle+iowait+irq+softirq
忙碌时间为 notidle = user+nice+system +iowait+irq+softirq
cpu使用率计算方法为,先取开始的total值和忙碌时间notidle,隔一段时间片,再取一次计算total2,notidle2, cpuuse = (notidle2 – notidle) * 100 / (total2 - total)%
PS:由于Android 8权限收紧,在Android 8系统手机内apk内读取文件内容为空,需要shell权限才可获取文件内容,下同
读/sys/devices/system/cpu/cpuX/cpufreq/scaling_cur_freq文件的值,X不定,看是几核手机,scaling_cur_freq是否存在也不一定,需要判断
至于为啥不取cpuinfo_cur_freq文件的值,原因是android 6,7系统获取的时候,这个文件shell没有读取权限,需要root权限
参考文章: https://blog.csdn.net/long_meng/article/details/45934899
Android 6,7系统可执行
mpsys window windows | grep "mCurrentFocus"
执行结果一般为类似:
mCurrentFocus=Window{81caaa5 u0 com.tencent.mobileqq/com.tencent.mobileqq.activity.SplashActivity}
按照一定规则把com.tencent.mobileqq提取出来即可
直接apk内读取文件即可,不需要shell权限(支持到Android8)
Gpu使用率获取:会得到两个值,(前一个/后一个)*100%=使用率
adb shell cat /sys/class/kgsl/kgsl-3d0/gpubusy
Gpu工作频率:
adb shell cat /sys/class/kgsl/kgsl-3d0/gpuclk
adb shell cat /sys/class/kgsl/kgsl-3d0/devfreq/cur_freq
Gpu最大、最小工作频率:
adb shell cat /sys/class/kgsl/kgsl-3d0/devfreq/max_freq
adb shell cat /sys/class/kgsl/kgsl-3d0/devfreq/min_freq
Gpu可用频率
adb shell cat /sys/class/kgsl/kgsl-3d0/gpu_available_frequencies
adb shell cat /sys/class/kgsl/kgsl-3d0/devfreq/available_frequencies
Gpu可用工作模式:
adb shell cat /sys/class/kgsl/kgsl-3d0/devfreq/available_governors
Gpu当前工作模式:
adb shell cat /sys/class/kgsl/kgsl-3d0/devfreq/governor
❸ android操作系统怎么获得电量
这个是获取电量的android DEMO:
package com.android.batterywaster;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Date;
/**
* So you thought sync used up your battery life.
*/
public class BatteryWaster extends Activity {
TextView mLog;
DateFormat mDateFormat;
IntentFilter mFilter;
PowerManager.WakeLock mWakeLock;
SpinThread mThread;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the layout for this activity. You can find it
// in res/layout/hello_activity.xml
setContentView(R.layout.main);
findViewById(R.id.checkbox).setOnClickListener(mClickListener);
mLog = (TextView)findViewById(R.id.log);
mDateFormat = DateFormat.getInstance();
mFilter = new IntentFilter();
mFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mFilter.addAction(Intent.ACTION_BATTERY_LOW);
mFilter.addAction(Intent.ACTION_BATTERY_OKAY);
mFilter.addAction(Intent.ACTION_POWER_CONNECTED);
PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "BatteryWaster");
mWakeLock.setReferenceCounted(false);
}
@Override
public void onPause() {
stopRunning();
}
View.OnClickListener mClickListener = new View.OnClickListener() {
public void onClick(View v) {
CheckBox checkbox = (CheckBox)v;
if (checkbox.isChecked()) {
startRunning();
} else {
stopRunning();
}
}
};
void startRunning() {
log("Start");
registerReceiver(mReceiver, mFilter);
mWakeLock.acquire();
if (mThread == null) {
mThread = new SpinThread();
mThread.start();
}
}
void stopRunning() {
log("Stop");
unregisterReceiver(mReceiver);
mWakeLock.release();
if (mThread != null) {
mThread.quit();
mThread = null;
}
}
void log(String s) {
mLog.setText(mLog.getText() + "\n" + mDateFormat.format(new Date()) + ": " + s);
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String title = action;
int index = title.lastIndexOf('.');
if (index >= 0) {
title = title.substring(index + 1);
}
if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int icon = intent.getIntExtra(BatteryManager.EXTRA_ICON_SMALL,-1);
log(title + ": level=" + level + "\n" + "icon:" + icon);
} else {
log(title);
}
}
};
class SpinThread extends Thread {
private boolean mStop;
public void quit() {
synchronized (this) {
mStop = true;
}
}
public void run() {
while (true) {
synchronized (this) {
if (mStop) {
return;
}
}
}
}
}
}
这个是layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<CheckBox android:id="@+id/checkbox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="25dp"
android:textSize="18sp"
android:textColor="#ffffffff"
android:text="@string/waste_away"
/>
<ScrollView android:id="@+id/scroll"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
>
<TextView android:id="@+id/log"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:textSize="12sp"
android:textColor="#ffffffff"
/>
</ScrollView>
</LinearLayout>
❹ Android获取系统cpu信息,内存,版本,电量等信息
1、CPU频率,CPU信息:/proc/cpuinfo和/proc/stat
通过读取文件/proc/cpuinfo系统CPU的类型等多种信息。
读取/proc/stat 所有CPU活动的信息来计算CPU使用率
下面我们就来讲讲如何通过代码来获取CPU频率:
复制代码 代码如下:
package com.orange.cpu;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
public class CpuManager {
// 获取CPU最大频率(单位KHZ)
// "/system/bin/cat" 命令行
// "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" 存储最大频率的文件的.路径
public static String getMaxCpuFreq() {
String result = "";
ProcessBuilder cmd;
try {
String[] args = { "/system/bin/cat",
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[24];
while (in.read(re) != -1) {
result = result + new String(re);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
result = "N/A";
}
return result.trim();
}
// 获取CPU最小频率(单位KHZ)
public static String getMinCpuFreq() {
String result = "";
ProcessBuilder cmd;
try {
String[] args = { "/system/bin/cat",
"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" };
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[24];
while (in.read(re) != -1) {
result = result + new String(re);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
result = "N/A";
}
return result.trim();
}
// 实时获取CPU当前频率(单位KHZ)
public static String getCurCpuFreq() {
String result = "N/A";
try {
FileReader fr = new FileReader(
"/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
result = text.trim();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// 获取CPU名字
public static String getCpuName() {
try {
FileReader fr = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
String[] array = text.split(":s+", 2);
for (int i = 0; i < array.length; i++) {
}
return array[1];
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
2、内存:/proc/meminfo
复制代码 代码如下:
public void getTotalMemory() {
String str1 = "/proc/meminfo";
String str2="";
try {
FileReader fr = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
while ((str2 = localBufferedReader.readLine()) != null) {
Log.i(TAG, "---" + str2);
}
} catch (IOException e) {
}
}
3、Rom大小
复制代码 代码如下:
public long[] getRomMemroy() {
long[] romInfo = new long[2];
//Total rom memory
romInfo[0] = getTotalInternalMemorySize();
//Available rom memory
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
romInfo[1] = blockSize * availableBlocks;
getVersion();
return romInfo;
}
public long getTotalInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return totalBlocks * blockSize;
}
4、sdCard大小
复制代码 代码如下:
public long[] getSDCardMemory() {
long[] sdCardInfo=new long[2];
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File sdcardDir = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(sdcardDir.getPath());
long bSize = sf.getBlockSize();
long bCount = sf.getBlockCount();
long availBlocks = sf.getAvailableBlocks();
sdCardInfo[0] = bSize * bCount;//总大小
sdCardInfo[1] = bSize * availBlocks;//可用大小
}
return sdCardInfo;
}
5、电池电量
复制代码 代码如下:
private BroadcastReceiver batteryReceiver=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra("level", 0);
// level加%就是当前电量了
}
};
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
6、系统的版本信息
复制代码 代码如下:
public String[] getVersion(){
String[] version={"null","null","null","null"};
String str1 = "/proc/version";
String str2;
String[] arrayOfString;
try {
FileReader localFileReader = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(
localFileReader, 8192);
str2 = localBufferedReader.readLine();
arrayOfString = str2.split("s+");
version[0]=arrayOfString[2];//KernelVersion
localBufferedReader.close();
} catch (IOException e) {
}
version[1] = Build.VERSION.RELEASE;// firmware version
version[2]=Build.MODEL;//model
version[3]=Build.DISPLAY;//system version
return version;
}
7、mac地址和开机时间
复制代码 代码如下:
public String[] getOtherInfo(){
String[] other={"null","null"};
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if(wifiInfo.getMacAddress()!=null){
other[0]=wifiInfo.getMacAddress();
} else {
other[0] = "Fail";
}
other[1] = getTimes();
return other;
}
private String getTimes() {
long ut = SystemClock.elapsedRealtime() / 1000;
if (ut == 0) {
ut = 1;
}
int m = (int) ((ut / 60) % 60);
int h = (int) ((ut / 3600));
return h + " " + mContext.getString(R.string.info_times_hour) + m + " "
+ mContext.getString(R.string.info_times_minute);
}