EntryAbility.ets 8.78 KB

import { FlutterAbility, FlutterEngine,FlutterPlugin, FlutterPluginBinding, EventChannel, EventSink, MethodChannel, MethodCall, MethodResult } from '@ohos/flutter_ohos';
import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant';
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import hilog from '@ohos.hilog';
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@ohos.base';
import { authentication } from '@kit.AccountKit';
import HuaweiLoginPlugin from '../components/HuaweiLoginView';



export default class EntryAbility extends FlutterAbility {
  private TAG: string = "| com.naji.book |";
  // 通道名称
  public CHANNEL:string = "com.naji/book";

  private channel: MethodChannel | null = null;
  private hasRequestedNotificationEnable: boolean = false;
  private pushIntentValue: Object | null = null;

  // private eventChannel?: EventChannel;
  // private eventSink?: EventSink;

  configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    GeneratedPluginRegistrant.registerWith(flutterEngine)
    this.addPlugin(new HuaweiLoginPlugin());
    this.channel = new MethodChannel(flutterEngine.dartExecutor, this.CHANNEL);
    this.channel.setMethodCallHandler({
      onMethodCall: (call: MethodCall, result: MethodResult) => {
        this.handleMethodCall(call, result);
      }
    });

    // this.eventChannel = new EventChannel(flutterEngine.dartExecutor, 'flutter.ohos.tpns/event_click');
    // this.eventChannel.setStreamHandler({
    //   onListen(args: object, events: EventSink): void {
    //     this.eventSink = events;
    //   },
    //   onCancel(args: object): void {
    //     this.eventSink = undefined;
    //   }
    // });
  }


  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    super.onCreate(want, launchParam);
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate' + JSON.stringify(want));
    if (want && want.parameters) {
      try {

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

        const data = want.parameters;

        if (data != null) {
          hilog.info(0x0000, 'testTag', '%{public}s', "onCreate" + 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.eventSink?.success(value);
              // this.channel?.invokeMethod("getIntent",value)


              this.pushIntentValue = value;
              }       });

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

  onForeground(): void {
    super.onForeground();
    this.ensureNotificationEnabled();
  }

  private handleMethodCall(call: MethodCall, result: MethodResult): void {
    switch (call.method) {
      case "getIntent":
        result.success(this.pushIntentValue);
        break;
      case "huaweiLogin":
        this.huaweiLogin(result);
        break;
      default:
        result.notImplemented();
        break;
    }
  }

  private huaweiLogin(result: MethodResult): void {
    const request = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
    request.forceLogin = true;
    request.state = new Date().getTime().toString();

    const controller = new authentication.AuthenticationController(this.context);
    controller.executeRequest(request).then((response: authentication.AuthenticationResponse) => {
      const loginResponse: authentication.LoginWithHuaweiIDResponse =
        response as authentication.LoginWithHuaweiIDResponse;
      const data = loginResponse.data;
      let openID = '';
      let unionID = '';
      let authorizationCode = '';
      let idToken = '';
      if (data != undefined) {
        openID = data.openID;
        unionID = data.unionID;
        authorizationCode = data.authorizationCode ?? '';
        idToken = data.idToken ?? '';
      }

      const resultData: Record<string, string> = {
        'openID': openID,
        'unionID': unionID,
        'authorizationCode': authorizationCode,
        'idToken': idToken
      };
      result.success(resultData);
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag', 'huaweiLogin failed, code: %{public}d, message: %{public}s', err.code, err.message);
      result.error('HUAWEI_LOGIN_ERROR', '华为账号登录失败', err.message);
    });
  }

  private ensureNotificationEnabled(): void {
    if (this.hasRequestedNotificationEnable) {
      return;
    }
    this.hasRequestedNotificationEnable = true;

    notificationManager.isNotificationEnabled().then((enabled: boolean) => {
      hilog.info(0x0000, 'testTag', 'isNotificationEnabled: %{public}s', enabled ? 'true' : 'false');
      if (enabled) {
        return;
      }

      notificationManager.requestEnableNotification(this.context).then(() => {
        hilog.info(0x0000, 'testTag', '%{public}s', 'requestEnableNotification success');
        if (!notificationManager.isNotificationEnabledSync()) {
          notificationManager.openNotificationSettings(this.context).then(() => {
            hilog.info(0x0000, 'testTag', '%{public}s', 'openNotificationSettings success');
          }).catch((err: BusinessError) => {
            hilog.error(0x0000, 'testTag', 'openNotificationSettings failed, code: %{public}d, message: %{public}s', err.code, err.message);
          });
        }
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'testTag', 'requestEnableNotification failed, code: %{public}d, message: %{public}s', err.code, err.message);
        notificationManager.openNotificationSettings(this.context).then(() => {
          hilog.info(0x0000, 'testTag', '%{public}s', 'openNotificationSettings success');
        }).catch((openErr: BusinessError) => {
          hilog.error(0x0000, 'testTag', 'openNotificationSettings failed, code: %{public}d, message: %{public}s', openErr.code, openErr.message);
        });
      });
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag', 'isNotificationEnabled failed, code: %{public}d, message: %{public}s', err.code, err.message);
    });
  }


  // 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 data = TPushHelper.prototype.parseNotificationMessage(want);
  //
  //       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.eventSink?.success(value);
  //             this.channel?.invokeMethod("getIntent",value)
  //
  //           }
  //
  //         });
  //
  //       } else {
  //         hilog.info(0x0000, 'testTag', 'EntryAbility data was null');
  //         this.eventSink?.error(0x0000.toString(), 'EntryAbility data was null', null);
  //       }
  //     } catch (err) {
  //       hilog.error(0x0000, 'testTag', 'TPushHelper  parseNotificationMessage exception', err);
  //       this.eventSink?.error(0x0000.toString(), 'TPushHelper  parseNotificationMessage exception', err);
  //     }
  //   } else {
  //     hilog.info(0x0000, 'testTag', 'EntryAbility want or want.parameters was null');
  //     this.eventSink?.error(0x0000.toString(), 'EntryAbility want or want.parameters was null', null);
  //   }
  //
  //
  // }
}