android 获取栈顶应用包名
时间: 2023-10-01 20:10:15 浏览: 267
可以使用以下代码获取当前栈顶应用的包名:
```java
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
if (activityManager != null) {
List<ActivityManager.RunningTaskInfo> runningTasks = activityManager.getRunningTasks(1);
if (runningTasks != null && !runningTasks.isEmpty()) {
ComponentName topActivity = runningTasks.get(0).topActivity;
String packageName = topActivity.getPackageName();
// packageName 就是当前栈顶应用的包名
}
}
```
需要注意的是,该方法在 Android 5.0 及以上版本已经被废弃,推荐使用以下方法:
```java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
if (usageStatsManager != null) {
long endTime = System.currentTimeMillis();
long beginTime = endTime - 10000; // 获取最近 10 秒内的应用使用情况
UsageEvents.Event event = new UsageEvents.Event();
UsageEvents usageEvents = usageStatsManager.queryEvents(beginTime, endTime);
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event);
if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
String packageName = event.getPackageName();
// packageName 就是当前栈顶应用的包名
}
}
}
}
```
需要注意的是,使用该方法需要添加权限:
```xml
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions"/>
```
阅读全文