Android 5.0 (including versions earlier than 5.0) obtains the top-stack application package name and android package name.
- /**
- * Get the package name (available in both versions)
- *
- * @ Return
- */
- Public String getTaskPackname (){
- ActivityManager. RunningAppProcessInfo currentInfo = null;
- Field field = null;
- Int START_TASK_TO_FRONT = 2;
- String currentApp = "CurrentNULL ";
- If (android. OS. Build. VERSION. SDK_INT> = android. OS. Build. VERSION_CODES.LOLLIPOP ){
- Try {
- Field = ActivityManager. RunningAppProcessInfo. class. getDeclaredField ("processState ");
- } Catch (Exception e ){
- E. printStackTrace ();
- }
- ActivityManager am = (ActivityManager) mContext. getSystemService (Context. ACTIVITY_SERVICE );
- List <RunningAppProcessInfo> appList = am. getRunningAppProcesses ();
- For (ActivityManager. RunningAppProcessInfo app: appList ){
- If (app. importance = ActivityManager. RunningAppProcessInfo. IMPORTANCE_FOREGROUND ){
- Integer state = null;
- Try {
- State = field. getInt (app );
- } Catch (Exception e ){
- E. printStackTrace ();
- }
- If (state! = Null & state = START_TASK_TO_FRONT ){
- CurrentInfo = app;
- Break;
- }
- }
- }
- If (currentInfo! = Null ){
- CurrentApp = currentInfo. processName;
- }
- } Else {
- ActivityManager am = (ActivityManager) mContext. getSystemService (Context. ACTIVITY_SERVICE );
- List <ActivityManager. RunningAppProcessInfo> tasks = am. getRunningAppProcesses ();
- CurrentApp = tasks. get (0). processName;
- }
- Log. e ("TAG", "Current App in foreground is:" + currentApp );
- Return currentApp;
- }