首页 > 其他分享 >harmony_flutter_wakelock(锁屏状态)

harmony_flutter_wakelock(锁屏状态)

时间:2024-12-19 09:13:26浏览次数:4  
标签:Map return error 锁屏 harmony ohos message null wakelock

harmony_flutter_wakelock(锁屏状态)

一.MethodChannel

1.flutter端代码

  • 创建MethodChannel

    **static** WakelockPlatformInterface _instance = MethodChannelWakelock();
    
  • 接收ohos端传递过来的状态值

import 'dart:async';
import 'dart:typed_data' show Uint8List, Int32List, Int64List, Float64List;

import 'package:flutter/foundation.dart' show WriteBuffer, ReadBuffer;
import 'package:flutter/services.dart';

class ToggleMessage {
  bool? enable;

  Object encode() {
    final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
    pigeonMap['enable'] = enable;
    return pigeonMap;
  }

  static ToggleMessage decode(Object message) {
    final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
    return ToggleMessage()..enable = pigeonMap['enable'] as bool?;
  }
}

class IsEnabledMessage {
  bool? enabled;

  Object encode() {
    final Map<Object?, Object?> pigeonMap = <Object?, Object?>{};
    pigeonMap['enabled'] = enabled;
    return pigeonMap;
  }

  static IsEnabledMessage decode(Object message) {
    final Map<Object?, Object?> pigeonMap = message as Map<Object?, Object?>;
    return IsEnabledMessage()..enabled = pigeonMap['enabled'] as bool?;
  }
}

class _WakelockApiCodec extends StandardMessageCodec {
  const _WakelockApiCodec();
  @override
  void writeValue(WriteBuffer buffer, Object? value) {
    if (value is IsEnabledMessage) {
      buffer.putUint8(128);
      writeValue(buffer, value.encode());
    } else if (value is ToggleMessage) {
      buffer.putUint8(129);
      writeValue(buffer, value.encode());
    } else {
      super.writeValue(buffer, value);
    }
  }

  @override
  Object? readValueOfType(int type, ReadBuffer buffer) {
    switch (type) {
      case 128:
        return IsEnabledMessage.decode(readValue(buffer)!);

      case 129:
        return ToggleMessage.decode(readValue(buffer)!);

      default:
        return super.readValueOfType(type, buffer);
    }
  }
}

class WakelockApi {
  /// Constructor for [WakelockApi].  The [binaryMessenger] named argument is
  /// available for dependency injection.  If it is left null, the default
  /// BinaryMessenger will be used which routes to the host platform.
  WakelockApi({BinaryMessenger? binaryMessenger})
      : _binaryMessenger = binaryMessenger;

  final BinaryMessenger? _binaryMessenger;

  static const MessageCodec<Object?> codec = _WakelockApiCodec();

  Future<void> toggle(ToggleMessage arg_msg) async {
    final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
        'dev.flutter.pigeon.WakelockApi.toggle', codec,
        binaryMessenger: _binaryMessenger);
    final Map<Object?, Object?>? replyMap =
        await channel.send(<Object>[arg_msg]) as Map<Object?, Object?>?;
    if (replyMap == null) {
      throw PlatformException(
        code: 'channel-error',
        message: 'Unable to establish connection on channel.',
        details: null,
      );
    } else if (replyMap['error'] != null) {
      final Map<Object?, Object?> error =
          (replyMap['error'] as Map<Object?, Object?>?)!;
      throw PlatformException(
        code: (error['code'] as String?)!,
        message: error['message'] as String?,
        details: error['details'],
      );
    } else {
      return;
    }
  }

  Future<IsEnabledMessage> isEnabled() async {
    final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
        'dev.flutter.pigeon.WakelockApi.isEnabled', codec,
        binaryMessenger: _binaryMessenger);
    final Map<Object?, Object?>? replyMap =
        await channel.send(null) as Map<Object?, Object?>?;
    if (replyMap == null) {
      throw PlatformException(
        code: 'channel-error',
        message: 'Unable to establish connection on channel.',
        details: null,
      );
    } else if (replyMap['error'] != null) {
      final Map<Object?, Object?> error =
          (replyMap['error'] as Map<Object?, Object?>?)!;
      throw PlatformException(
        code: (error['code'] as String?)!,
        message: error['message'] as String?,
        details: error['details'],
      );
    } else {
      return (replyMap['result'] as IsEnabledMessage?)!;
    }
  }
}

2.ohos端代码

  • 继承FlutterPlugin实现onAttachedToEngine方法
  • 创建MethodChannel实例device_util
  • setMethodCallHandler
  • 通过result回传参数
import AbilityAware from '@ohos/flutter_ohos/src/main/ets/embedding/engine/plugins/ability/AbilityAware';
import { AbilityPluginBinding } from '@ohos/flutter_ohos/src/main/ets/embedding/engine/plugins/ability/AbilityPluginBinding';
import {
  FlutterPlugin,
  FlutterPluginBinding
} from '@ohos/flutter_ohos/src/main/ets/embedding/engine/plugins/FlutterPlugin';
import { Messages } from './Messages';
import { Wakelock } from './Wakelock';

const TAG = "WakelockPlugin"

export class WakelockPlugin implements FlutterPlugin, AbilityAware {
  private pluginBinding : FlutterPluginBinding | null = null;
  private wakelock : Wakelock | null = null;

  getUniqueClassName(): string {
    return "WakelockPlugin"
  }

  onAttachedToAbility(binding: AbilityPluginBinding): void {
    this.wakelock = new Wakelock(binding.getAbility().context);
    if (this.pluginBinding != null) {
      Messages.setup(this.pluginBinding.getBinaryMessenger(), this.wakelock);
    }
  }

  onDetachedFromAbility(): void {
    this.wakelock = null;
  }

  onAttachedToEngine(binding: FlutterPluginBinding): void {
    this.pluginBinding = binding;
  }

  onDetachedFromEngine(binding: FlutterPluginBinding): void {
    this.pluginBinding = null;
  }
}

通过@ohos.windowr获取相对应得参数实现

import { Log, Any } from '@ohos/flutter_ohos';
import { IsEnabledMessage, ToggleMessage } from './Messages';
import common from '@ohos.app.ability.common';
import window from '@ohos.window';

const TAG = "Wakelock.ohos";

export interface WakelockApi {
  toggle(msg: ToggleMessage): Promise<void>;

  isEnabled(): IsEnabledMessage;
}

export class Wakelock implements WakelockApi {
  private enabled: boolean = false;
  context?: common.UIAbilityContext;

  constructor(context: common.UIAbilityContext) {
    this.context = context;
  }

  toggle(message: ToggleMessage): Promise<void> {
    if (!this.context) {
      throw new NoAbilityError();
    }
    return new Promise<void>((resolve, reject) => {
      window.getLastWindow(this.context).then((data) => {
        return Promise.resolve(data);
      }).then((windowClass: window.Window) => {
        let isKeepScreenOn: boolean = message.enable as boolean;
        Log.i(TAG, "message=" + message.enable);
        Log.i(TAG, "this.enabled=" + this.enabled);
        Log.i(TAG, "isKeepScreenOn=" + isKeepScreenOn);
        windowClass.setWindowKeepScreenOn(isKeepScreenOn).then(() => {
          Log.i(TAG, "setWindowKeepScreenOn success");
          this.enabled = isKeepScreenOn;
          resolve();
        }).catch((err: Any) => {
          this.enabled = false;
          reject(err);
          Log.e(TAG, "setWindowKeepScreenOn error: " + JSON.stringify(err));
        })
      }).catch((err: Any) => {
        this.enabled = false;
        reject(err);
        Log.i(TAG, "setWindowKeepScreenOn other error: " + JSON.stringify(err));
      })
    })
  }

  isEnabled(): IsEnabledMessage {
    if (this.context == null) {
      throw new NoAbilityError()
    }
    let msg = new IsEnabledMessage();
    msg.enabled = this.enabled;
    return msg;
  }
}

export class NoAbilityError extends Error {
  constructor() {
    super("wakelock requires a foreground Ability.")
  }
}

标签:Map,return,error,锁屏,harmony,ohos,message,null,wakelock
From: https://www.cnblogs.com/hongmengos/p/18616318

相关文章

  • harmony_flutter_qrcode(生成二维码)
    harmony_flutter_qrcode(生成二维码)一.MethodChannel1.flutter端代码创建MethodChannel接收ohos端传递过来的状态值classRecognitionManager{staticconstMethodChannel_channel=constMethodChannel('recognition_qrcode');staticFuture<String>ge......
  • harmony_flutter video_trimmer实现视频剪辑
    harmony_fluttervideo_trimmer实现视频剪辑简介videotrimmer是在OpenHarmony环境下,提供视频剪辑能力的三方库安装教程ohpminstall@ohos/videotrimmerOpenHarmonyohpm环境配置等更多内容,请参考如何安装OpenHarmonyohpm包。使用介绍构建VideoTrimmerOption对象:ge......
  • HarmonyOS Next 系统能力调用简易指南
    《HarmonyOSNext系统能力调用简易指南》HarmonyOSNext作为华为鸿蒙操作系统的下一代重要演进,为开发者带来了更强大、更高效且更具创新性的系统能力。在这篇文章中,我们将深入探讨如何简易地调用HarmonyOSNext的一些关键系统能力,并通过代码示例帮助您快速上手。一、基础环......
  • flutter_harmonyOS编写自己的插件(一)
    flutter_harmonyOS编写自己的插件(一)一.注册自己的插件融入ohos工程1.EntryAbility端代码exportdefaultclassEntryAbilityextendsFlutterAbility{configureFlutterEngine(flutterEngine:FlutterEngine){super.configureFlutterEngine(flutterEngine)flut......
  • flutter_harmonyOS编写自己的插件(二)
    flutter_harmonyOS编写自己的插件(二)一.做自己的支付宝插件回调和事件1.HarmonyOS官方文档地址https://opendocs.alipay.com/open/0f71b5?pathHash=bedc38ba1.安装说明鸿蒙官方仓库-支付宝支付SDKohpminstall@cashier_alipay/cashiersdk注意:SDK版本>=15.8.27......
  • HarmonyOS实现仿造小米商城
    项目简介以下代码实现了小米商城的仿造编写,可以实现用户登录和注册,以及小米系列商品的展示和个人信息的展示。app尚不完全后续会加入更多功能。编程软件DevEcoStudio工程目录 └─main  ├─ets  │ ├─common  │ │ ├─constants  │ │......
  • 用WPF实现桌面锁屏壁纸的应用
    用WPF实现桌面锁屏壁纸的应用目录用WPF实现桌面锁屏壁纸的应用需求分析需求方案实现App.xamlApp.xaml.csMainWindow.xamlMainWindow.xaml.csImportImageHelper.csKeyboardHookLib.cs壁纸需求分析需求存取数据库二进制文件轮播图片显示系统时间滑动解锁禁用键盘......
  • harmony_flutter_更新Flutter插件项目结构
    更新Flutter插件项目结构更新内容flutter插件项目中的ohos目录,将从鸿蒙工程project结构,替换为鸿蒙工程module结构。flutter工程中引用的har文件,统一放到ohos/har目录下。更新后需要删除ohos插件中的旧模块目录。更新步骤以flutter_flutter中的integration_test为例......
  • HarmonyOS鸿蒙开发 - 解决上下两栏白边 - 沉浸式效果
    鸿蒙应用开发从入门到入行预览器上下两栏白边自从HarmonyOS升级到release版后,很多同学会问猫林老师:为什么他的预览器上下有白边,为什么明明根容器写了宽高百分百但没铺满。如下图白边原因其实上面的白边,称之为状态栏。上面会放手机wifi信号、电池电量等信息。一般情况下......
  • harmony_flutter_videoCompress(视频压缩)
    harmony_flutter_videoCompress(视频压缩)一.MethodChannel1.flutter端代码创建MethodChannel交互通道video_compress接收ohos端传递过来的进度finalcompressProgress$=ObservableBuilder<double>();final_channel=constMethodChannel('video_compress');@......