电量辅助监控实战

185 阅读1分钟

运行时能耗

adb pull /system/framework/framework-res.apk

反编译,xml->power_profile

运行时获取使用时长

Aop辅助统计:次数、时间

以WakeLock为例

package com.optimize.performance.wakelock;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.PowerManager;

public class WakeLockUtils {

    private static PowerManager.WakeLock sWakeLock;

    public static void acquire(Context context){
        if(sWakeLock == null){
            sWakeLock = createWakeLock(context);
        }
        if(sWakeLock != null && !sWakeLock.isHeld()){
            sWakeLock.acquire();
        }
    }

    public static void release(){
        
            if(sWakeLock != null && sWakeLock.isHeld()){
                sWakeLock.release();
                sWakeLock = null;
            }
        
    }

    @SuppressLint("InvalidWakeLockTag")
    private static PowerManager.WakeLock createWakeLock(Context context){
        PowerManager pm = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE);
        if(pm != null){
            return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"");
        }
        return null;
    }

}
public static long sStartTime = 0;

    @Insert(value = "acquire")
    @TargetClass(value = "com.optimize.performance.wakelock.WakeLockUtils",scope = Scope.SELF)
    public static void acquire(Context context){
        trace = Log.getStackTraceString(new Throwable());
        sStartTime = System.currentTimeMillis();
        Origin.callVoid();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                WakeLockUtils.release();
            }
        },1000);
    }

    @Insert(value = "release")
    @TargetClass(value = "com.optimize.performance.wakelock.WakeLockUtils",scope = Scope.SELF)
    public static void release(){
        LogUtils.i("PowerManager "+(System.currentTimeMillis() - sStartTime)+"/n"+trace);
        Origin.callVoid();
    }

线程运行时长

超过阈值预警

public static long runTime = 0;

    @Insert(value = "run")
    @TargetClass(value = "java.lang.Runnable",scope = Scope.ALL)
    public void run(){
        runTime = System.currentTimeMillis();
        Origin.callVoid();
        LogUtils.i("runTime "+(System.currentTimeMillis() - runTime));
    }