ReflectUtil

Posted adamli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ReflectUtil相关的知识,希望对你有一定的参考价值。

package com.android.demo.lileidemo.utils;

import android.app.usage.UsageStats;
import android.util.Log;

import com.android.demo.lileidemo.MyApplication;
import com.android.demo.lileidemo.constant.AppConstants;

import java.lang.reflect.Field;
import java.util.List;

/**
* date: 04/16/2020.
* author: lilei.
*/
public class ReflectUtil {
private static final String TAG = AppConstants.APP_TAG + "ReflectUtil ";

private static UsageStats mUsageStats;
private static String mPackageName;

public static synchronized void testReflect() {
long currentTimeMillis = System.currentTimeMillis();
long hourStartMillis = DateTimeUtil.getHourStartMillis(currentTimeMillis);
long startTimeMillis = 1586941200000L;//hourStartMillis - AppConstants.OPEN_APP_STATS_INTERVAL_MILLIS;
long endTimeMillis = 1586941464278L;
List<UsageStats> listUsageStats = UsageStatsUtil.getUsageStatsList(
MyApplication.getAppContext(), startTimeMillis, endTimeMillis);

for (int i = 0; i < listUsageStats.size(); i++) {
mUsageStats = listUsageStats.get(i);
getAppLaunchCount(mUsageStats);
mPackageName = mUsageStats.getPackageName();
long totalTimeInForeground = mUsageStats.getTotalTimeInForeground();
Log.d(TAG, "collectAllOpenApp() mPackageName:" + mPackageName
+ " totalTimeInForeground:" + totalTimeInForeground
+ " getFirstTimeStamp:" + mUsageStats.getFirstTimeStamp()
+ " getLastTimeStamp:" + mUsageStats.getLastTimeStamp()
+ " getLastTimeUsed:" + mUsageStats.getLastTimeUsed()
+ " startTimeMillis:" + startTimeMillis + " endTimeMillis:" + endTimeMillis);
}
}

private static void getAppLaunchCount(UsageStats usageStats) {
Class<UsageStats> usageStatsClass = UsageStats.class;
try {
//step1 通过方法名称反射
// Method method = usageStatsClass.getDeclaredMethod("getLastTimeUsed",
// (Class[]) null);
// //Open permission.
// method.setAccessible(true);
// Object lastTimeUsed = (Object) method.invoke(usageStats, (Object[]) null);
//


//step2 通过变量名称反射
Class c = usageStats.getClass();
Field field = c.getDeclaredField("mLaunchCount");
//Field field = usageStats.getClass().getDeclaredField("mAppLaunchCount");
field.setAccessible(true);
int launchCount = field.getInt(usageStats);

field = c.getDeclaredField("mLastEvent");
//Field field = usageStats.getClass().getDeclaredField("mAppLaunchCount");
field.setAccessible(true);
int lastEvent = field.getInt(usageStats);

Log.d(TAG, "getAppLaunchCount() *# getPackageName:" + usageStats.getPackageName()
+ " lastEvent:" + lastEvent + " launchCount:" + launchCount);
} catch (Exception e) {
Log.d(TAG, "getAppLaunchCount() error:" + e.toString());
e.printStackTrace();
}
}
}

以上是关于ReflectUtil的主要内容,如果未能解决你的问题,请参考以下文章