1. 程式人生 > >Android官方架構組件介紹之應用(四)

Android官方架構組件介紹之應用(四)

怎麽 nbsp 註冊 bool 其他 info get inf prot

講一個項目常見的功能,友盟統計功能

例如一個項目有很多多modlue,每個裏面modlue都有Activity,Activity需要友盟統一,Fragment也需要友盟統計。一般做法就是繼承一個BaseActivity,BaseFragment。

然後在BaseActivity,BaseFragment大概是這樣的

import android.support.v7.app.AppCompatActivity;

public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onStart() {
        
super.onStart(); MobclickAgent.onPageStart(getPageName(this)); } @Override protected void onStop() { super.onStop(); MobclickAgent.onPageEnd(getPageName(this)); } }

技術分享圖片

但是如果你們代碼,引入了其他的AAR代碼,他們aar裏面有Activity,但是你也該不了別人代碼,但是你們需要統計他們Activity,這個時候怎麽辦?

public class ActivityLifecycleMonitorCallback implements
Application.ActivityLifecycleCallbacks { private static final boolean DEBUG = AppEnv.bAppdebug; private static final String TAG = DEBUG ? "ActivityLifecyMonitor" : ActivityLifecyMonitor.class.getSimpleName(); @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (DEBUG) { Log.i(TAG, getPageName(activity) + " onActivityCreated activity="+activity.hashCode()); } } @Override public void onActivityStarted(Activity activity) { if (DEBUG) { Log.i(TAG, getPageName(activity) + " onActivityStarted"); } MobclickAgent.onPageStart(getPageName(activity)); } @Override public void onActivityResumed(Activity activity) { if (DEBUG) { Log.i(TAG, getPageName(activity) + " onActivityResumed"); } MobclickAgent.onResume(activity); } @Override public void onActivityPaused(Activity activity) { if (DEBUG) { Log.i(TAG, getPageName(activity) + " onActivityPaused"); } MobclickAgent.onPause(activity); } @Override public void onActivityStopped(Activity activity) { if (DEBUG) { Log.i(TAG, getPageName(activity) + " onActivityStopped"); } MobclickAgent.onPageEnd(getPageName(activity)); } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { if (DEBUG) { Log.i(TAG, getPageName(activity) + " onActivitySaveInstanceState"); } } @Override public void onActivityDestroyed(Activity activity) { if (DEBUG) { Log.i(TAG, getPageName(activity) + " onActivityDestroyed activity="+activity.hashCode()); } } private String getPageName(Activity activity) { return activity.getClass().getName(); } }

然後在Application裏面註冊

 private void registerActivityLifecycleCallback(Application application) {
        ActivityLifecycleMonitorCallback  activityLifecycleMonitor = new ActivityLifecycleMonitorCallback();
        application.registerActivityLifecycleCallbacks(activityLifecycleMonitor);
    }

Android官方架構組件介紹之應用(四)