0

I am developing an app which uses getRunningTasks() function to get the top activity name. But getRunningTasks() is deprecated in Android L. Is there any other way to get the top activity name (not package name) in Lollipop.

android
  • 163
  • 1
  • 15
  • Possible duplicate of [getRunningTasks doesn't work in Android L](http://stackoverflow.com/questions/24625936/getrunningtasks-doesnt-work-in-android-l) – bummi Dec 18 '15 at 09:13
  • I'm also looking for a way to get the activity name, but just found A LOT of ways to get the package name. Did you find some answer? – Joubert Vasconcelos May 17 '16 at 00:41

2 Answers2

1
Class<?> currentClassName; // Declare Globally 

    Activity activity = (Activity) context;//casting context into activity
    try
    {
        currentClassName = Class.forName(activity.getClass().getName()); //getting the current activity's class name from activity object
    }
    catch (ClassNotFoundException e)
    {
        e.printStackTrace();
    }

Please read SO Answer

Community
  • 1
  • 1
IntelliJ Amiya
  • 73,189
  • 14
  • 161
  • 193
1

I found a solution to get top activity name on Lollipop with the new Class UsageStatsManager added in Android L.

First you need the permission

<uses-permission
        android:name="android.permission.PACKAGE_USAGE_STATS"
        tools:ignore="ProtectedPermissions" />

And the user must enable this option.

Then use this method queryEvents()

There is a simple example.

while (true) {
    final long INTERVAL = 1000;
    final long end = System.currentTimeMillis();
    final long begin = end - INTERVAL;
    final UsageEvents usageEvents = manager.queryEvents(begin, end);
    while (usageEvents.hasNextEvent()) {
        UsageEvents.Event event = new UsageEvents.Event();
        usageEvents.getNextEvent(event);
        if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
            Log.d("event", "timestamp : " + event.getTimeStamp());
            Log.d("event", "package name : " + event.getPackageName());
            Log.d("event", "class name : " + event.getClassName());
        }
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

When an activity become to foreground, you can see its class name and package name in Logcat.

Tsich'i
  • 129
  • 11