XgFlutterPlugin.ets 5.09 KB
import {
  FlutterPlugin,
  FlutterPluginBinding,
  MethodCall,
  MethodCallHandler,
  MethodChannel,
  MethodResult,
  AbilityAware,
  AbilityPluginBinding,
  FlutterAbility,
  NewWantListener,
} from '@ohos/flutter_ohos';











import TPushHelper from './helper/TPushHelper';
import { UIAbility,AbilityConstant, common, Want } from '@kit.AbilityKit';
import Log from '@ohos/flutter_ohos/src/main/ets/util/Log';
import { CacheManager } from './helper/CacheManager';
import { TPush } from 'tpns';
import hilog from '@ohos.hilog';


const TAG: string = "TPushOhos";



/** XgFlutterPlugin **/
export default class XgFlutterPlugin implements FlutterPlugin, MethodCallHandler,AbilityAware,NewWantListener{
  private channel: MethodChannel | null = null;
  private applicationContext: Context | null = null;
  private ability: UIAbility | null = null;
  private binding: AbilityPluginBinding | null = null



  constructor() {
  }



  getUniqueClassName(): string {
    return "XgFlutterPlugin"
  }

  onAttachedToAbility(binding: AbilityPluginBinding): void {
    Log.i(TAG, "onAttachedToAbility");
    this.ability = binding.getAbility()
    this.binding = binding
    binding.addOnNewWantListener(this)
  }



  onDetachedFromAbility(): void {
    Log.i(TAG, "onDetachedFromAbility");
    this.ability = null;
    this.binding?.removeOnNewWantListener(this)
    this.binding = null
  }





  onAttachedToEngine(binding: FlutterPluginBinding): void {
    this.applicationContext = binding.getApplicationContext();
    this.channel = new MethodChannel(binding.getBinaryMessenger(), "tpns_flutter_plugin");
    this.channel.setMethodCallHandler(this);
    CacheManager.init(this.applicationContext.getApplicationContext());  //初始化缓存功能
  }



  onDetachedFromEngine(binding: FlutterPluginBinding): void {
    this.applicationContext = null;
    if (this.channel != null) {
      this.channel.setMethodCallHandler(null)
    }
  }
  
  onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onNewWant' + JSON.stringify(want));
    if (want && want.parameters) {
      try {

        // want判断消息是否是腾讯云推送的消息
        const notificationMessage = TPushHelper.parseNotificationMessage(want);

        if(notificationMessage){

        const data = want.parameters;

        if (data != null) {
          hilog.info(0x0000, 'testTag', '%{public}s', "onNewWant" + JSON.stringify(data));
          // 或者使用 Object.keys 方法遍历
          Object.keys(data).forEach(key => {


            if (key.toString() === 'tpnsChanel') {
              // 使用 EventSink 发送数据后,dart断的事件监听回调会收到发送的数据。
              const value = data[key];
              console.log(`Key: ${key}, Value: ${typeof value === 'object' ? JSON.stringify(value) : value}`);
              this.channel?.invokeMethod("getIntent", value)

            }

          });

        } else {
          hilog.info(0x0000, 'testTag', 'EntryAbility data was null');
        }

      }
      } catch (err) {
        hilog.error(0x0000, 'testTag', 'TPushHelper  parseNotificationMessage exception', err);
      }
    } else {
      hilog.info(0x0000, 'testTag', 'EntryAbility want or want.parameters was null');
    }


  }

  onMethodCall(call: MethodCall, result: MethodResult): void {
    if (call.method == "getPlatformVersion") {
      result.success("OpenHarmony ^ ^ ")
    }else if (call.method == "xgToken") {
      result.success(null)
    }else if (call.method == "startXg") {
      const accessId = call.argument("accessId") as string || ""
      const accessKey = call.argument("accessKey") as string || ""
      TPushHelper.init(this.applicationContext!,accessId,accessKey,this.channel,(err, strs) => {

        if(err){
          //注册失败
          console.info(`test ${JSON.stringify(strs)}`)
          result.error('000',strs,err)
        }else{
          // 注册成功
          console.info(`test ${JSON.stringify(strs)}`)
          TPushHelper.register((err, token) => {

            if(token  =='注册失败!'){
              result.error('000','注册失败','注册失败')
            }else{
              this.channel?.invokeMethod("onRegisteredDone",token);
              result.success(token)
            }
          });
        }
      });
    }else if(call.method == "stopXg"){

      TPushHelper.unregister((err, msg) => {

        if(msg  =="反注册失败"){
          result.error('000','反注册失败','反注册失败')
        }else{
          this.channel?.invokeMethod("unRegistered",msg);
          result.success(msg)
        }
      });

    }else  if(call.method == 'setAppBadge'){
      const badgeSum = call.argument("badgeSum") as string || ""
      TPushHelper.setBadge(Number(badgeSum),(err, msg) => {
        if(msg == '设置应用角标失败'){
          result.error('000','设置应用角标失败','设置应用角标失败')
        }else{
          result.success(msg)
        }
      });
    }else  if(call.method == 'resetBadgeNum'){
      TPushHelper.clearBadge();
    } else  {
      result.notImplemented()
    }
  }



 
}