本篇博文在我之前的博文中已经提到了,可是监听Activity切换又能够作为一个单独的内容来叙述,因此这里又单独拿了出来进行赘述。

    Activity的切换无非有两种。第一种:启动或者创建一个新的Activity;另外一种:唤醒后台执行的Activity。

因此假设我们可以成功监听到启动或者创建一个Activity,或者唤醒Activity我们就基本完毕了Activity的切换的监听。

  在源代码/frameworks/base/core/java/android/app文件夹下ActivityThread.java中为我们提供了这样一个方法来帮助我们完毕对Activity启动、创建、销毁、暂停、停止。唤醒等生命周期的监听。

  

  1. public void handleMessage(Message msg) {  
  2.             if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));  
  3.             switch (msg.what) {  
  4.                 case LAUNCH_ACTIVITY: {  
  5.                     /// M: enable profiling @{  
  6.                     if ( true == mEnableAppLaunchLog && !mIsUserBuild && false == mTraceEnabled ) {  
  7.                         try {  
  8.                             FileInputStream fprofsts_in = new FileInputStream("/proc/mtprof/status");  
  9.                             if ( fprofsts_in.read()== '3' ) {  
  10.                                 Log.v(TAG, "start Profiling for empty process");  
  11.                                 mTraceEnabled = true;  
  12.                                 Debug.startMethodTracing("/data/data/applaunch"); //applaunch.trace  
  13.                             }  
  14.                         } catch (FileNotFoundException e) {  
  15.                             Slog.e(TAG, "mtprof entry can not be found", e);  
  16.                         } catch (java.io.IOException e) {  
  17.                             Slog.e(TAG, "mtprof entry open failed", e);  
  18.                         }  
  19.                     }  
  20.                     /// @}  
  21.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER | Trace.TRACE_TAG_PERF, "activityStart"); /// M: add TRACE_TAG_PERF for performance debug  
  22.                     ActivityClientRecord r = (ActivityClientRecord)msg.obj;  
  23.   
  24.                     r.packageInfo = getPackageInfoNoCheck(  
  25.                             r.activityInfo.applicationInfo, r.compatInfo);  
  26.                     handleLaunchActivity(r, null);  
  27.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER | Trace.TRACE_TAG_PERF); /// M: add TRACE_TAG_PERF for performance debug  
  28.                 } break;  
  29.                 case RELAUNCH_ACTIVITY: {  
  30.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");  
  31.                     ActivityClientRecord r = (ActivityClientRecord)msg.obj;  
  32.                     handleRelaunchActivity(r);  
  33.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  34.                 } break;  
  35.                 case PAUSE_ACTIVITY:  
  36.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");  
  37.                     handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);  
  38.                     maybeSnapshot();  
  39.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  40.                     break;  
  41.                 case PAUSE_ACTIVITY_FINISHING:  
  42.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");  
  43.                     handlePauseActivity((IBinder)msg.obj, true, msg.arg1 != 0, msg.arg2);  
  44.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  45.                     break;  
  46.                 case STOP_ACTIVITY_SHOW:  
  47.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");  
  48.                     handleStopActivity((IBinder)msg.obj, true, msg.arg2);  
  49.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  50.                     break;  
  51.                 case STOP_ACTIVITY_HIDE:  
  52.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");  
  53.                     handleStopActivity((IBinder)msg.obj, false, msg.arg2);  
  54.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  55.                     break;  
  56.                 case SHOW_WINDOW:  
  57.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityShowWindow");  
  58.                     handleWindowVisibility((IBinder)msg.obj, true);  
  59.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  60.                     break;  
  61.                 case HIDE_WINDOW:  
  62.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityHideWindow");  
  63.                     handleWindowVisibility((IBinder)msg.obj, false);  
  64.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  65.                     break;  
  66.                 case RESUME_ACTIVITY:  
  67.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER | Trace.TRACE_TAG_PERF, "activityResume"); /// M: add TRACE_TAG_PERF for performance debug  
  68.                     handleResumeActivity((IBinder)msg.obj, true,  
  69.                             msg.arg1 != 0true);  
  70.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER | Trace.TRACE_TAG_PERF); /// M: add TRACE_TAG_PERF for performance debug  
  71.                     break;  
  72.                 case SEND_RESULT:  
  73.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDeliverResult");  
  74.                     handleSendResult((ResultData)msg.obj);  
  75.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  76.                     break;  
  77.                 case DESTROY_ACTIVITY:  
  78.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDestroy");  
  79.                     handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,  
  80.                             msg.arg2, false);  
  81.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  82.                     break;  
  83.                 case BIND_APPLICATION:  
  84.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");  
  85.                     AppBindData data = (AppBindData)msg.obj;  
  86.                     handleBindApplication(data);  
  87.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  88.                     break;  
  89.                 case EXIT_APPLICATION:  
  90.                     if (mInitialApplication != null) {  
  91.                         mInitialApplication.onTerminate();  
  92.                     }  
  93.                     Looper.myLooper().quit();  
  94.                     break;  
  95.                 case NEW_INTENT:  
  96.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityNewIntent");  
  97.                     handleNewIntent((NewIntentData)msg.obj);  
  98.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  99.                     break;  
  100.                 case RECEIVER:  
  101.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");  
  102.                     handleReceiver((ReceiverData)msg.obj);  
  103.                     maybeSnapshot();  
  104.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  105.                     break;  
  106.                 case CREATE_SERVICE:  
  107.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceCreate");  
  108.                     handleCreateService((CreateServiceData)msg.obj);  
  109.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  110.                     break;  
  111.                 case BIND_SERVICE:  
  112.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");  
  113.                     handleBindService((BindServiceData)msg.obj);  
  114.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  115.                     break;  
  116.                 case UNBIND_SERVICE:  
  117.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");  
  118.                     handleUnbindService((BindServiceData)msg.obj);  
  119.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  120.                     break;  
  121.                 case SERVICE_ARGS:  
  122.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStart");  
  123.                     handleServiceArgs((ServiceArgsData)msg.obj);  
  124.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  125.                     break;  
  126.                 case STOP_SERVICE:  
  127.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");  
  128.                     handleStopService((IBinder)msg.obj);  
  129.                     maybeSnapshot();  
  130.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  131.                     break;  
  132.                 case REQUEST_THUMBNAIL:  
  133.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "requestThumbnail");  
  134.                     handleRequestThumbnail((IBinder)msg.obj);  
  135.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  136.                     break;  
  137.                 case CONFIGURATION_CHANGED:  
  138.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");  
  139.                     mCurDefaultDisplayDpi = ((Configuration)msg.obj).densityDpi;  
  140.                     handleConfigurationChanged((Configuration)msg.obj, null);  
  141.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  142.                     break;  
  143.                 case CLEAN_UP_CONTEXT:  
  144.                     ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;  
  145.                     cci.context.performFinalCleanup(cci.who, cci.what);  
  146.                     break;  
  147.                 case GC_WHEN_IDLE:  
  148.                     scheduleGcIdler();  
  149.                     break;  
  150.                 case DUMP_SERVICE:  
  151.                     handleDumpService((DumpComponentInfo)msg.obj);  
  152.                     break;  
  153.                 case LOW_MEMORY:  
  154.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");  
  155.                     handleLowMemory();  
  156.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  157.                     break;  
  158.                 case ACTIVITY_CONFIGURATION_CHANGED:  
  159.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityConfigChanged");  
  160.                     handleActivityConfigurationChanged((IBinder)msg.obj);  
  161.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  162.                     break;  
  163.                 case PROFILER_CONTROL:  
  164.                     handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2);  
  165.                     break;  
  166.                 case CREATE_BACKUP_AGENT:  
  167.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");  
  168.                     handleCreateBackupAgent((CreateBackupAgentData)msg.obj);  
  169.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  170.                     break;  
  171.                 case DESTROY_BACKUP_AGENT:  
  172.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");  
  173.                     handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);  
  174.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  175.                     break;  
  176.                 case SUICIDE:  
  177.                     Process.killProcess(Process.myPid());  
  178.                     break;  
  179.                 case REMOVE_PROVIDER:  
  180.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");  
  181.                     completeRemoveProvider((ProviderRefCount)msg.obj);  
  182.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  183.                     break;  
  184.                 case ENABLE_JIT:  
  185.                     ensureJitEnabled();  
  186.                     break;  
  187.                 case DISPATCH_PACKAGE_BROADCAST:  
  188.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");  
  189.                     handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);  
  190.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  191.                     break;  
  192.                 case SCHEDULE_CRASH:  
  193.                     throw new RemoteServiceException((String)msg.obj);  
  194.                 case DUMP_HEAP:  
  195.                     handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);  
  196.                     break;  
  197.                 case DUMP_ACTIVITY:  
  198.                     handleDumpActivity((DumpComponentInfo)msg.obj);  
  199.                     break;  
  200.                 case DUMP_PROVIDER:  
  201.                     handleDumpProvider((DumpComponentInfo)msg.obj);  
  202.                     break;  
  203.                 case SLEEPING:  
  204.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");  
  205.                     handleSleeping((IBinder)msg.obj, msg.arg1 != 0);  
  206.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  207.                     break;  
  208.                 case SET_CORE_SETTINGS:  
  209.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");  
  210.                     handleSetCoreSettings((Bundle) msg.obj);  
  211.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  212.                     break;  
  213.                 case UPDATE_PACKAGE_COMPATIBILITY_INFO:  
  214.                     handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);  
  215.                     break;  
  216.                 case TRIM_MEMORY:  
  217.                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");  
  218.                     handleTrimMemory(msg.arg1);  
  219.                     Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
  220.                     break;  
  221.                 case UNSTABLE_PROVIDER_DIED:  
  222.                     handleUnstableProviderDied((IBinder)msg.obj, false);  
  223.                     break;  
  224.                 case REQUEST_ASSIST_CONTEXT_EXTRAS:  
  225.                     handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);  
  226.                     break;  
  227.                 case TRANSLUCENT_CONVERSION_COMPLETE:  
  228.                     handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);  
  229.                     break;  
  230.                 case INSTALL_PROVIDER:  
  231.                     handleInstallProvider((ProviderInfo) msg.obj);  
  232.                     break;  
  233.             }  
  234.             if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));  
  235.             /// M: ActivityThread log enhancement @{  
  236.             if(!mIsUserBuild && isDebuggableMessage(msg.what)){  
  237.                 Slog.d(TAG, codeToString(msg.what) + " handled "  
  238.                 + ": " + msg.arg1 + " / " + msg.obj);  
  239.             }  
  240.             /// @}  
  241.         }  

    这里我们能够看到。我们能够通过监听LAUNCH_ACTIVITY,RESUME_ACTIVITY等来推断Activity的切换,因此我们能够将通过在ActivityThread.java中将获得顶层栈栈顶Activity的方法在这里调用以实现我们的需求。

    那么这样是否可以完毕我们的需求呢?

    答案是否定的。即使我们可以编译通过,可是在我们測试观察log的时候。并不能得到当前处于活动状态的Activity。那么为什么会出现这样的情况呢?

    通过观察log我们发现,这里我们须要GET_TASK权限,当然我们能够通过加入权限的方式,但这样有风险,那么有没有一个更可靠的方式呢。

    依然是通过观察log,我们发现Android系统会使用一个ActivityClientRecoder类来记录Activity的信息,而这个类在ActivityThread中也得到了应用。因此我们能够通过得到ActivityClientRecoder的对象r来获得Activity对象,在通过Activity对象的getComponent()来得到ComponentName的对象。在ComponentName对象中便封装了应用程序包名和当前处于活动状态的Activity。

    详细实现方式这里不再详细赘述。仅仅是提供获取Activity信息的部分代码进行简单分析一下,大家能够參考一下。

ActivityClientRecord r = (ActivityClientRecord)msg.obj;

Activity a=r.parent;

ComponentName c=a.getComponentName();

String package=c.mPackage;

String className=c.mClass;StrSt

    此外另一种备用的方式,就是我们能够通过得到当前处于活动状态进程信息来推断当前处以活动状态的进程。

    实现方式例如以下:

  1. final ActivityManager am = (ActivityManager)mAppContextImpl.getSystemService(Context.ACTIVITY_SERVICE);  
  2. List<RunningAppProcessInfo> list = am.getRunningAppProcesses();  
  3.   
  4. if (list.size() != 0) {  
  5.     RunningAppProcessInfo topRunningProcess = list.get(0);  
  6.     if(topRunningProcess.processName.equals("com.android.xx.xxxxx")){  
  7.         return true;  
  8.     }  
  9. }  
  10. return false;