Google は、現在のフォアグラウンド アプリケーション パッケージを取得するためのすべてのドアを最終的に閉じたようです。
Lollipop の更新後、この回答getRunningTasks(int maxNum)
のおかげで殺され、Lollipop 以降のフォアグラウンド アプリケーション パッケージを取得するためにこのコードを使用しました。
final int PROCESS_STATE_TOP = 2;
RunningAppProcessInfo currentInfo = null;
Field field = null;
try {
field = RunningAppProcessInfo.class.getDeclaredField("processState");
} catch (Exception ignored) {
}
ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appList = am.getRunningAppProcesses();
for (RunningAppProcessInfo app : appList) {
if (app.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
app.importanceReasonCode == 0 ) {
Integer state = null;
try {
state = field.getInt( app );
} catch (Exception ignored) {
}
if (state != null && state == PROCESS_STATE_TOP) {
currentInfo = app;
break;
}
}
}
return currentInfo;
Android 5.1.1 以降 (6.0 Marshmallow)getRunningAppProcesses()
も同様に殺されているようです。独自のアプリケーション パッケージのリストを返すようになりました。
使用統計マネージャー
ここで説明されているように新しいUsageStatsManager
API を使用できますが、すべてのアプリケーションで機能するとは限りません。一部のシステム アプリケーションは同じパッケージを返します
com.google.android.googlequicksearchbox
AccessibilityService(2017年12月:Googleによる利用禁止予定)
一部のアプリケーションはAccessibilityService
(ここで見られるように) を使用しますが、いくつかの欠点があります。
現在実行中のアプリケーション パッケージを取得する別の方法はありますか?