如何在Lollipop获得热门活动名称?
((ActivityManager)getSystemService(Context.ACTIVITY_SERVICE)).
getRunningTasks(1).get(0).topActivity
Lollipop不再提供:
* @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method
* is no longer available to third party
* applications: the introduction of document-centric recents means
* it can leak person information to the caller. For backwards compatibility,
* it will still retu rn a small subset of its data: at least the caller's
* own tasks, and possibly some other tasks
* such as home that are known to not be sensitive.
在MyActivity中调用onResume
MyApplication.getInstance().saveCurentActivity(MyActivity.this)
saveCurentActivity(Activity a) {
this.activityName = a.getClass().getSimpleName();
}
不是一个好主意,因为错误时可以销毁MyApplication(例如,NPE)。
答案 0 :(得分:1)
此代码对我有用。
ActivityManager activityManager = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
String currentTopActivity = taskInfo.get(0).topActivity.getClassName();
它将提供TopActivity。
答案 1 :(得分:1)
这对我有用:
long end = System.currentTimeMillis();
long INTERVAL=2000;
long begin = end - INTERVAL;
if (Build.VERSION.SDK_INT >= 21) {
UsageStatsManager us = (UsageStatsManager) MyServices.this.getSystemService(Context.USAGE_STATS_SERVICE);
UsageEvents usageEvents = us.queryEvents(begin, end);
while (usageEvents.hasNextEvent()) {
UsageEvents.Event event = new UsageEvents.Event();
usageEvents.getNextEvent(event);
if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
Log.e("event", "timestamp : " + event.getTimeStamp());
Log.e("event", "package name : " + event.getPackageName());
Log.e("event", "Class name : " + event.getClassName());
//You can find activity name as Class name
}
}
}
答案 2 :(得分:0)
我不熟悉您正在使用的原始API,但您可以使用可以通过{{注册的ActivityLifecycleCallbacks跟踪您的应用中的活动生命周期更改3}}。每当创建,启动,恢复等活动时,它都会收到通知。您可以使用readOnly: false
和onActivityResumed
挂钩跟踪当前活动。