Jollen 的 Android 系統管理雜記, #4: C 如何取得 property

jollen 發表於 May 21, 2010 6:19 PM

上一則日記提到 Android property 的設定。在 Android 作業系統裡,取得 property 是很重要的工作。不管是 Android 框架層(使用 Java 語言),或是 Native 層(使用 C/C++ 語言),都可以看到讀取 property 的程式碼。

以下是一段簡單的範例程式,用以說明如何用 C 來讀取 Android 系統的 property:

/* * Copyright (C) 2010 The Mokoid Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "LED Stub" #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <jni.h> #include <mokoid/led.h> #include <cutils/properties.h> #define HAL_DEFAULT_VARIANT "default" static const char *variant_keys[] = { "ro.hardware", /* This goes first so that it can pick up a different file on the emulator. */ "ro.product.board", "ro.board.platform", "ro.arch" }; #define HAL_VARIANT_KEYS_COUNT (sizeof(variant_keys)/sizeof(variant_keys[0])) int main() { int i; int status; char prop[PATH_MAX]; status = -EINVAL; for (i = 0; (status != 0) && (i < HAL_VARIANT_KEYS_COUNT); i++) { if (property_get(variant_keys[i], prop, NULL) == 0) { continue; } printf("Your property is: %s = %s\n", variant_keys[i], prop); } return 0; }

上述範例,是由 libhardware 的程式碼修改而成。HAL (即 libhardware) 會讀取以下四個 property:

  • ro.hardware
  • ro.product.board
  • ro.board.platform
  • ro.arch

習慣上,我們會以 "ro.product.board" 做為 HAL 模組的 "product name",ro.product.board 決定 HAL 模組的命名方式。例如,當 ro.product.board 為 "mokoid" 時,我們就必須將 HAL 模組命名為 *,並存放於 system/lib/hw 目錄下。

Jollen's Blog 使用 Github issues 與讀者交流討論。請點擊上方的文章專屬 issue,或 open a new issue

您可透過電子郵件,或是 Linkedin 與我連絡。更歡迎使用微信,請搜尋 WeChat ID:jollentw