性能监控 安卓逻辑.md 16 KB

#安卓

LGCollecter

package com.cgbu.collect;
import android.app.Activity;
import android.content.Context;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileReader;

import android.app.ActivityManager;
import android.os.BatteryManager;
import android.os.Process;
import android.os.SystemClock;

public class LGCollecter {

    private static final String TAG = "LGCollecter";

    // 温度电量数据结构(完整版)
    public static class BatteryInfo {
        public float batteryTemperature;  // 电池温度 (°C)
        public int batteryLevel;          // 电池电量 (%)
        public float batteryVoltage;      // 电池电压 (V)
        public long timestamp;            // 时间戳
        public int thermalState;          // 设备温度状态 (Android: -1)
        public String thermalStateString; // 温度状态描述
    }

    /**
     * 获取真实内存占用(使用PermissionManager进行权限检查)
     */
    public static int getRSSMemoryMBProc() {
        Activity activity = getActivity();
        if (activity == null) {
            Log.e(TAG, "Activity is null, cannot get memory info");
            return -1;
        }

        // 使用PermissionManager检查存储权限
//        if (!PermissionManager.hasStoragePermissions(activity)) {
//            Log.w(TAG, "Storage permissions not granted, cannot read /proc/self/status");
//            return -1;
//        }

        try (BufferedReader br = new BufferedReader(new FileReader("/proc/self/status"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("VmRSS:")) {
                    String[] parts = line.split("\\s+");
                    int kb = Integer.parseInt(parts[1]);
                    Log.w(TAG, "Storage ok");
                    return kb / 1024;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error reading memory info: " + e.getMessage());
        }
        return -1;
    }

    /**
     * 获取系统可用内存百分比(不需要特殊权限)
     */
    public static float getAvailableMemoryPercent() {
        Activity activity = getActivity();
        if (activity == null) {
            Log.e(TAG, "Activity is null, cannot get memory info");
            return -1.0f;
        }

        try {
            ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
            ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
            am.getMemoryInfo(mi);
            return (float)mi.availMem / mi.totalMem * 100;
        } catch (Exception e) {
            Log.e(TAG, "Error getting memory info: " + e.getMessage());
            return -1.0f;
        }
    }

    private static long lastCpuTime = 0;
    private static long lastAppCpuTime = 0;

    /**
     * 获取CPU使用率 (优化版本 - 不需要特殊权限)
     */
    public static float getCPUUsageOptimized() {
        Activity activity = getActivity();
        if (activity == null) {
            Log.e(TAG, "Activity is null, cannot get CPU usage");
            return -1.0f;
        }

        long startTime = System.nanoTime();
        try {
            long currentTime = SystemClock.elapsedRealtime();
            long currentAppTime = Process.getElapsedCpuTime();

            if (lastCpuTime == 0) {
                lastCpuTime = currentTime;
                lastAppCpuTime = currentAppTime;
                long endTime = System.nanoTime();
                Log.d(TAG, "getCPUUsageOptimized耗时: " + (endTime - startTime) / 1000000.0f + "ms (首次调用)");
                return 0.0f;
            }

            long timeDiff = currentTime - lastCpuTime;
            long appTimeDiff = currentAppTime - lastAppCpuTime;

            // 确保有足够的时间间隔来提高准确性
            if (timeDiff < 5000) { // 至少5000ms间隔
                long endTime = System.nanoTime();
                Log.d(TAG, "getCPUUsageOptimized耗时: " + (endTime - startTime) / 1000000.0f + "ms (时间间隔太短: " + timeDiff + "ms)");
                return 0.0f;
            }

            float cpuUsage = 0.0f;
            if (timeDiff > 0) {
                cpuUsage = (float) appTimeDiff / timeDiff * 100.0f;
            }

            lastCpuTime = currentTime;
            lastAppCpuTime = currentAppTime;

            long endTime = System.nanoTime();
            Log.d(TAG, "getCPUUsageOptimized耗时: " + (endTime - startTime) / 1000000.0f + "ms, CPU使用率: " + cpuUsage + "%, 时间间隔: " + timeDiff + "ms");
            return Math.min(cpuUsage, 100.0f);
        } catch (Exception e) {
            long endTime = System.nanoTime();
            Log.e(TAG, "getCPUUsageOptimized耗时: " + (endTime - startTime) / 1000000.0f + "ms, 错误: " + e.getMessage());
            return 0.0f;
        }
    }


    /**
     * 获取电池信息(完整版 - 包含电压和温度状态)
     */
    public static BatteryInfo getBatteryInfo() {
        Activity activity = getActivity();
        if (activity == null) {
            Log.e(TAG, "Activity is null, cannot get battery info");
            return createDefaultBatteryInfo();
        }

        long startTime = System.nanoTime();
        BatteryInfo info = new BatteryInfo();

        try {
            BatteryManager batteryManager = (BatteryManager) activity.getSystemService(Context.BATTERY_SERVICE);

            if (batteryManager != null) {
                // 获取电池电量
                int level = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
                info.batteryLevel = level;

                // 获取电池温度
                try {
                    android.content.IntentFilter ifilter = new android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED);
                    android.content.Intent batteryStatus = activity.registerReceiver(null, ifilter);

                    if (batteryStatus != null) {
                        int temp = batteryStatus.getIntExtra(android.os.BatteryManager.EXTRA_TEMPERATURE, -1);
                        if (temp != -1) {
                            info.batteryTemperature = temp / 10.0f;
                        } else {
                            info.batteryTemperature = 25.0f;
                        }

                        // 获取电池电压
                        int voltage = batteryStatus.getIntExtra(android.os.BatteryManager.EXTRA_VOLTAGE, -1);
                        if (voltage != -1) {
                            info.batteryVoltage = voltage / 1000.0f; // 转换为V
                        } else {
                            info.batteryVoltage = 3.7f;
                        }
                    } else {
                        info.batteryTemperature = 25.0f;
                        info.batteryVoltage = 3.7f;
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Error getting battery temperature/voltage: " + e.getMessage());
                    info.batteryTemperature = 25.0f;
                    info.batteryVoltage = 3.7f;
                }

                // Android不支持温度状态,设置为-1
                info.thermalState = -1;
                info.thermalStateString = "Not Available";
                info.timestamp = System.currentTimeMillis();
            } else {
                Log.e(TAG, "BatteryManager is null");
                return createDefaultBatteryInfo();
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting battery info: " + e.getMessage());
            return createDefaultBatteryInfo();
        }

        long endTime = System.nanoTime();
        Log.d(TAG, "getBatteryInfo耗时: " + (endTime - startTime) / 1000000.0f + "ms, 电量: " + info.batteryLevel + "%, 温度: " + info.batteryTemperature + "°C, 电压: " + info.batteryVoltage + "V");
        return info;
    }

    /**
     * 异步获取电池信息(简化版,不需要特殊权限)
     */
    public static void getBatteryInfoAsync() {
        Activity activity = getActivity();
        if (activity == null) {
            Log.e(TAG, "Activity is null, cannot get battery info async");
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                long startTime = System.nanoTime();
                BatteryInfo info = getBatteryInfo();

                long endTime = System.nanoTime();
                Log.d(TAG, "getBatteryInfoAsync耗时: " + (endTime - startTime) / 1000000.0f + "ms, 电量: " + info.batteryLevel + "%, 温度: " + info.batteryTemperature + "°C");

                // 在主线程中通过SendMessage回传给Unity
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 分别发送电量和温度,避免JSON解析的性能开销
                        String batteryLevelStr = String.valueOf(info.batteryLevel);
                        String batteryTemperatureStr = String.valueOf(info.batteryTemperature);

                        // 通过SendMessage发送给Unity
                        com.unity3d.player.UnityPlayer.UnitySendMessage("LGCollecter", "OnBatteryLevelReceived", batteryLevelStr);
                        com.unity3d.player.UnityPlayer.UnitySendMessage("LGCollecter", "OnBatteryTemperatureReceived", batteryTemperatureStr);
                    }
                });
            }
        }).start();
    }

    /**
     * 获取电池电量字符串(同步方法)
     */
    public static String getBatteryLevelString() {
        try {
            BatteryInfo info = getBatteryInfo();
            return String.valueOf(info.batteryLevel);
        } catch (Exception e) {
            Log.e(TAG, "Error getting battery level string: " + e.getMessage());
            return "0";
        }
    }

    /**
     * 获取电池温度字符串(同步方法)
     */
    public static String getBatteryTemperatureString() {
        try {
            BatteryInfo info = getBatteryInfo();
            return String.valueOf(info.batteryTemperature);
        } catch (Exception e) {
            Log.e(TAG, "Error getting battery temperature string: " + e.getMessage());
            return "25.0";
        }
    }

    /**
     * 创建默认电池信息
     */
    private static BatteryInfo createDefaultBatteryInfo() {
        BatteryInfo info = new BatteryInfo();
        info.batteryLevel = 0;
        info.batteryTemperature = 25.0f;
        info.batteryVoltage = 3.7f;
        info.thermalState = -1;
        info.thermalStateString = "Not Available";
        info.timestamp = System.currentTimeMillis();
        return info;
    }

    /**
     * 获取权限状态信息(使用PermissionManager)
     */
    public static String getPermissionStatus() {
        Activity activity = getActivity();
        if (activity == null) {
            return "Activity is null";
        }

        return PermissionManager.getPermissionStatus(activity);
    }

    /**
     * 检查特定功能所需的权限
     */
    public static boolean checkPermissionsForFeature(String feature) {
        Activity activity = getActivity();
        if (activity == null) {
            return false;
        }

        return PermissionManager.checkPermissionsForFeature(activity, feature);
    }

    /**
     * 申请存储权限
     */
    public static void requestStoragePermissions() {
        Activity activity = getActivity();
        if (activity == null) {
            Log.e(TAG, "Activity is null, cannot request permissions");
            return;
        }

        PermissionManager.requestStoragePermissions(activity);
    }

    // 设置一个 Activity 参数
    private static Activity _unityActivity;

    // 通过反射获取 Unity 的 Activity 的上下文
    private static Activity getActivity(){
        if(null == _unityActivity){
            try{
                Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
                Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype);
                _unityActivity = activity;
            }catch (ClassNotFoundException e){
                Log.e(TAG, "UnityPlayer class not found: " + e.getMessage());
                e.printStackTrace();
            }catch (IllegalAccessException e){
                Log.e(TAG, "Illegal access to UnityPlayer: " + e.getMessage());
                e.printStackTrace();
            }catch (NoSuchFieldException e){
                Log.e(TAG, "currentActivity field not found: " + e.getMessage());
                e.printStackTrace();
            }
        }
        return _unityActivity;
    }
}

PermissionManager

package com.cgbu.collect;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

public class PermissionManager {
    private static final String TAG = "PermissionManager";

    // LGCollecter需要的权限列表
    private static final String[] STORAGE_PERMISSIONS = {
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    /**
     * 检查是否有指定权限
     */
    private static boolean hasPermission(Context context, String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    /**
     * 检查是否有存储权限
     */
    public static boolean hasStoragePermissions(Context context) {
        for (String permission : STORAGE_PERMISSIONS) {
            if (!hasPermission(context, permission)) {
                Log.w(TAG, "Missing storage permission: " + permission);
                return false;
            }
        }
        return true;
    }

    /**
     * 检查特定功能所需的权限
     */
    public static boolean checkPermissionsForFeature(Context context, String feature) {
        switch (feature.toLowerCase()) {
            case "memory":
                return hasStoragePermissions(context);
            case "cpu":
                // CPU使用率获取不需要特殊权限
                return true;
            case "battery":
                // 电池信息获取不需要特殊权限
                return true;
            case "storage":
                return hasStoragePermissions(context);
            default:
                // 默认只检查存储权限(用于内存信息获取)
                return hasStoragePermissions(context);
        }
    }

    /**
     * 获取权限状态信息
     */
    public static String getPermissionStatus(Context context) {
        StringBuilder status = new StringBuilder();
        status.append("Permission Status:\n");

        status.append("Storage Permissions: ").append(hasStoragePermissions(context) ? "GRANTED" : "DENIED").append("\n");
        status.append("CPU Usage: No special permissions required").append("\n");
        status.append("Battery Info: No special permissions required").append("\n");
        status.append("Memory Info: Requires storage permissions");

        return status.toString();
    }

    /**
     * 申请存储权限
     */
    public static void requestStoragePermissions(Context context) {
        if (context == null) {
            Log.e(TAG, "Context is null, cannot request permissions");
            return;
        }

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查是否已经有权限
                if (hasStoragePermissions(context)) {
                    Log.d(TAG, "Storage permissions already granted");
                    return;
                }

                // 申请权限
                if (context instanceof android.app.Activity) {
                    android.app.Activity activity = (android.app.Activity) context;
                    activity.requestPermissions(STORAGE_PERMISSIONS, 1001);
                    Log.d(TAG, "Requested storage permissions");
                } else {
                    Log.e(TAG, "Context is not an Activity, cannot request permissions");
                }
            } else {
                Log.d(TAG, "Permissions automatically granted on API < 23");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error requesting storage permissions: " + e.getMessage());
        }
    }
}