鸿蒙开源组件——弱引用内存安全的 Handler

jacksky
发布于 2021-11-15 18:28
浏览
0收藏

ohos-weak-handler

项目介绍

  • 项目名称:ohos-weak-handler
  • 所属系列:openharmony第三方组件适配移植
  • 功能:Memory safer implementation of ohos.eventhandler.EventHandler
  • 项目移植状态:主功能完成
  • 调用差异:无
  • 开发版本:sdk6,DevEco Studio2.2 beta1
  • 基线版本:Release 1.2

效果演示鸿蒙开源组件——弱引用内存安全的 Handler-鸿蒙开发者社区

 

安装教程

在moudle级别下的build.gradle文件中添加依赖

// 添加maven仓库
repositories {
    maven {
        url 'https://s01.oss.sonatype.org/content/repositories/releases/'
    }
}

// 添加依赖库 
dependencies {
    implementation 'com.gitee.chinasoft_ohos:ohos-weak-handler:1.0.1'   
}

如无法运行,删除项目.gradle,.idea,build,gradle,build.gradle文件, 并依据自己的版本创建新项目,将新项目的对应文件复制到根目录下

使用说明

Problem

Original implementation of Handler always keeps hard reference to handler in queue of execution. Any object in Message or Runnable posted to ohos.eventhandler.EventHandler will be hard referenced for some time. If you create anonymous Runnable and call to postTask with large timeout, that Runnable will be held in memory until timeout passes. Even if your Runnable seems small, it indirectly references owner class, which is usually something as big as Activity or Fragment.

You can read more on our blog post.

Solution

WeakHandler is trickier than ohos.eventhandler.EventHandler , it will keep WeakReferences to runnables and messages, and GC could collect them once WeakHandler instance is not referenced any more.

Usage

Use WeakHandler as you normally would use Handler

  • Java 调用示例 **
import com.badoo.mobileDemo.util.WeakHandler;

public class ExampleAbility extends Ability {

    private WeakHandler handler; // We still need at least one hard reference to WeakHandler

     @Override
    public void onStart(Intent intent) {
        handler = new WeakHandler();
        ...
    }

    private void onClick(Component view) {
        handler.postTask(new Runnable() {
            view.setVisibility(Component.VISIBLE);
        }, 5000);
    }
}

测试信息

CodeCheck代码测试无异常
CloudTest代码测试无异常
安全病毒安全检测通过
当前版本demo功能与原组件基本无差异

版本迭代

  • 1.0.1

版权和许可信息

Weak Handler is brought to you by Badoo Trading Limited and it is released under the MIT License.

Created by Dmytro Voronkevych

##Blog Read more on our tech blog or explore our other open source projects

 

ohos-weak-handler-master.zip 497.75K 13次下载
已于2021-11-15 18:28:07修改
收藏
回复
举报
回复
    相关推荐