UmengStats.ets 1.49 KB
import { preInit, InternalPlugin, setLogEnabled, init, onEventObject, onProfileSignOff,
  onProfileSignIn } from '@umeng/analytics';
import { common } from '@kit.AbilityKit';
import { AccountManagerUtils } from '../utils/AccountManagerUtils';
import { UserDataLocal } from '../utils/UserDataLocal';
import { EmitterUtils } from '../utils/EmitterUtils';

export class UmengStats {

  private static _inited = false

  // 启动时调用
  static preInit(context: common.UIAbilityContext) {

    // 需在 AppScope/resources/rawfile/umconfig.json 配置key和channel
    preInit({
      context: context.getApplicationContext(),
      plugins: [new InternalPlugin()],
      enableLog: true

    });
  }

  // 在用户同意隐私政策后再调用此方法
  static initAfterAgreeProtocol() {
    init();
    UmengStats._inited = true

    UmengStats.onLogin()
    UmengStats.event("testHarmony", {"key1": "value1"})
  }

  // TODO: 登录成功调用
  static onLogin() {
    AccountManagerUtils.isLogin().then((login) => {
      if (!login) { return }

      let userId = UserDataLocal.getUserId()
      if (userId.length > 0) {
        onProfileSignIn("USER", userId)
      }
    })
  }
  // TODO: 退出登录调用
  static onLogout() {
    onProfileSignOff()
  }

  // 属性key,128位以内的非空字符串,value为256位以内的数值或字符串
  static event(eventId: string, param?: Record<string, string | number>) {
    if (!UmengStats._inited) {
      return
    }
    onEventObject(eventId, param);
  }
}