Android 5.0 (including versions earlier than 5.0) obtains the top-stack application package name and android package name.

Source: Internet
Author: User

Android 5.0 (including versions earlier than 5.0) obtains the top-stack application package name and android package name.

  1. /**
  2. * Get the package name (available in both versions)
  3. *
  4. * @ Return
  5. */
  6. Public String getTaskPackname (){
  7. ActivityManager. RunningAppProcessInfo currentInfo = null;
  8. Field field = null;
  9. Int START_TASK_TO_FRONT = 2;
  10. String currentApp = "CurrentNULL ";
  11. If (android. OS. Build. VERSION. SDK_INT> = android. OS. Build. VERSION_CODES.LOLLIPOP ){
  12. Try {
  13. Field = ActivityManager. RunningAppProcessInfo. class. getDeclaredField ("processState ");
  14. } Catch (Exception e ){
  15. E. printStackTrace ();
  16. }
  17. ActivityManager am = (ActivityManager) mContext. getSystemService (Context. ACTIVITY_SERVICE );
  18. List <RunningAppProcessInfo> appList = am. getRunningAppProcesses ();
  19. For (ActivityManager. RunningAppProcessInfo app: appList ){
  20. If (app. importance = ActivityManager. RunningAppProcessInfo. IMPORTANCE_FOREGROUND ){
  21. Integer state = null;
  22. Try {
  23. State = field. getInt (app );
  24. } Catch (Exception e ){
  25. E. printStackTrace ();
  26. }
  27. If (state! = Null & state = START_TASK_TO_FRONT ){
  28. CurrentInfo = app;
  29. Break;
  30. }
  31. }
  32. }
  33. If (currentInfo! = Null ){
  34. CurrentApp = currentInfo. processName;
  35. }
  36. } Else {
  37. ActivityManager am = (ActivityManager) mContext. getSystemService (Context. ACTIVITY_SERVICE );
  38. List <ActivityManager. RunningAppProcessInfo> tasks = am. getRunningAppProcesses ();
  39. CurrentApp = tasks. get (0). processName;
  40. }
  41. Log. e ("TAG", "Current App in foreground is:" + currentApp );
  42. Return currentApp;
  43. }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.