鸿蒙开发中,如何获取上下文Context?

鸿蒙开发中该如何获取上下文Context?

阅读 2.6k
2 个回答

Context是应用中对象的上下文,其提供了应用的一些基础信息,例如resourceManager(资源管理)、applicationInfo(当前应用信息)、dir(应用文件路径)、area(文件分区)等,以及应用的一些基本方法,例如createBundleContext()、getApplicationContext()等。UIAbility组件和各种ExtensionAbility派生类组件都有各自不同的Context类。分别有基类Context、ApplicationContext、AbilityStageContext、UIAbilityContext、ExtensionContext、ServiceExtensionContext等Context。
各类Context获取参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides...

在 AbilitySlice和Ability 中可以直接通过 getContext() 方法获取 Context。
自定义一个组件时,通常可以在组件的构造函数中传入 Context

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.rpc.RemoteException;

public class MyCustomComponent extends Component {
    private ohos.rpc.RemoteException context;

    public MyCustomComponent(ohos.rpc.RemoteException context) {
        super(context);
        this.context = context;
        // 可以使用获取到的Context进行后续操作
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        super.onDraw(component, canvas);
        // 使用Context进行绘制等操作
    }
}

在工具类里获取 Context
工具类里获取 Context 通常可以采用静态方法或者单例模式,在初始化时传入 Context

import ohos.rpc.RemoteException;

public class MyUtils {
    private static ohos.rpc.RemoteException context;

    public static void init(ohos.rpc.RemoteException context) {
        MyUtils.context = context;
    }

    public static void doSomething() {
        if (context != null) {
            // 使用Context进行操作
        }
    }
}

在 Ability 或者 AbilitySlice 中初始化工具类:
MyUtils.init(getContext());