1/** 2 * Copyright (c) 2024-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import resourceManager from '@ohos.resourceManager'; 17import common from '@ohos.app.ability.common'; 18import { StringUtil } from './StringUtil'; 19import Logger from './Logger'; 20 21const TAG = 'ResourceUtil' 22 23class ResourceUtil { 24 /** 25 * Obtains the resource name 26 * @param resource Resource file 27 * @returns Resource File Name 28 */ 29 30 getResourceString(context: object, resource: Resource, params?: Array<string | number>): string { 31 let resourceString: string = ''; 32 try { 33 if (params && params.length) { 34 resourceString = getContext(context).resourceManager.getStringSync(resource.id, ...params); 35 } else { 36 resourceString = getContext(context).resourceManager.getStringSync(resource.id); 37 } 38 } catch (error) { 39 Logger.error(TAG, `getResourceString error = ${JSON.stringify(error)}`) 40 } 41 return resourceString 42 } 43 44 /** 45 * Get the specified package name resource manager 46 * @params bundleName Application package name 47 * @params context context 48 */ 49 50 getBundleResourceManager(bundleName: string, context: common.Context | null): resourceManager.ResourceManager | null { 51 if (context === null || StringUtil.isEmpty(bundleName)) { 52 Logger.error(TAG, 'getBundleResourceManager error'); 53 return null; 54 } 55 try { 56 let bundleContext = context.createBundleContext(bundleName); 57 if (bundleContext === null || bundleContext === undefined) { 58 Logger.error(TAG, 'get bundleContext failed') 59 return null; 60 } 61 return bundleContext.resourceManager; 62 } catch (error) { 63 Logger.error(TAG, `get bundleContext faild, error message : ${JSON.stringify(error)}}`) 64 return null; 65 } 66 } 67 68 getFloatNumber(resource: Resource): number { 69 let context = getContext(this) as common.UIAbilityContext; 70 return px2vp(context.resourceManager.getNumber(resource.id)) 71 } 72} 73 74let resourceUtil = new ResourceUtil(); 75 76export default resourceUtil as ResourceUtil;