码迷,mamicode.com
首页 > 其他好文 > 详细

ReflectUtil

时间:2020-06-16 14:47:43      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:imp   edm   gen   print   pre   eid   size   catch   syn   

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

标签:imp   edm   gen   print   pre   eid   size   catch   syn   

原文地址:https://www.cnblogs.com/adamli/p/13140749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!