How to get running application activity Name in android 5.0(L)?

后端 未结 3 438
旧巷少年郎
旧巷少年郎 2020-12-09 12:07

I am using the following code to get the current running activity name in android.

ActivityManager am = (ActivityManager) aContext
                .getSystem         


        
3条回答
  •  [愿得一人]
    2020-12-09 12:24

    You can use this:

    String packageName = "";
    String className = "";
    
    UsageStatsManager usageStatsManager = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
    
    if (usageStatsManager != null)
    {
       UsageEvents queryEvents = usageStatsManager.queryEvents(System.currentTimeMillis() - 10000, System.currentTimeMillis());
    
       if (queryEvents != null) 
       {
          UsageEvents.Event event = new UsageEvents.Event();
    
          while (queryEvents.hasNextEvent()) 
          {
              UsageEvents.Event eventAux = new UsageEvents.Event();
              queryEvents2.getNextEvent(eventAux);
    
              if (eventAux.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND)
              {
                  event = eventAux;
              }
          }
    
          packageName = event.getPackageName();
          className = event.getClassName();
       }
    }
    

    You need the android.permission.PACKAGE_USAGE_STATS, which is a system-level permission and will not be granted to third-party apps. However, declaring the permission implies intention to use the API and the user of the device can grant permission through the Settings application.

    Or you can do:

    pm grant com.your.package android.permission.PACKAGE_USAGE_STATS
    

提交回复
热议问题