3

如何在 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)。

4

3 回答 3

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      

                        }

                    }
                }
于 2016-12-30T20:24:53.613 回答
1

这段代码对我有用。

ActivityManager activityManager = (ActivityManager)    context.getSystemService(Activity.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
String currentTopActivity = taskInfo.get(0).topActivity.getClassName();

它会给TopActivity。

于 2015-12-18T12:53:21.417 回答
0

我不熟悉您使用的原始 API,但您可以使用可以通过Application.registerActivityLifecycleCallbacks注册的ActivityLifecycleCallbacks来跟踪应用程序中的Activity 生命周期更改。每当创建、启动、恢复 Activity 等时,它都会收到通知。您可以使用and钩子跟踪当前的 Activity。onActivityResumedonActivityPaused

于 2015-12-18T12:35:27.170 回答