Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

動手做:開發 Android 應用來使用自訂的系統服務

編輯:關於 Android 程式設計

當你已經有一個註冊到 ServiceManager 的系統服務(例如前面實作的 freg 服務),接下來要做的就是寫一個應用下來呼叫它。整體來說,Java 層完全不需要知道服務實在 C++ 還是 Java,只要拿到 Binder 代理即可。

一、建立專案結構

~/android-2.3_r1/packages/experimental/Freg
     ----AndroidManifest.xml
     ----Android.mk
     ----src/shy/luo/freg/Freg.java
     ----res/layout/main.xml
     ----res/values/strings.xml
     ----res/drawable/icon.png

二、Freg.java

package shy.luo.freg;

import android.app.Activity;
import android.os.Bundle;
import android.os.ServiceManager;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Freg extends Activity implements OnClickListener {

    private final static String LOG_TAG = "shy.luo.freg.FregActivity";
    private IFregService fregService = null;
    private EditText valueText = null;
    private Button readButton = null;
    private Button writeButton = null;
    private Button clearButton = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        fregService = IFregService.Stub.asInterface(
                ServiceManager.getService("freg"));

        valueText = (EditText) findViewById(R.id.edit_value);
        readButton = (Button) findViewById(R.id.button_read);
        writeButton = (Button) findViewById(R.id.button_write);
        clearButton = (Button) findViewById(R.id.button_clear);

        readButton.setOnClickListener(this);
        writeButton.setOnClickListener(this);
        clearButton.setOnClickListener(this);

        Log.i(LOG_TAG, "Freg Activity Created");
    }

    @Override
    public void onClick(View v) {
        if (v.equals(readButton)) {
            try {
                int val = fregService.getVal();
                valueText.setText(String.valueOf(val));
            } catch (RemoteException e) {
                Log.e(LOG_TAG, "Remote Exception while reading value from freg service.");
            }
        } else if (v.equals(writeButton)) {
            try {
                int val = Integer.parseInt(valueText.getText().toString());
                fregService.setVal(val);
            } catch (RemoteException e) {
                Log.e(LOG_TAG, "Remote Exception while writing value to freg service.");
            }
        } else if (v.equals(clearButton)) {
            valueText.setText("");
        }
    }
}

這裡的關鍵是 IFregService.Stub.asInterface(ServiceManager.getService("freg"))。它把 ServiceManager 中查到的 Binder 物件包裝成本地介面,之後所有呼叫都透過 Binder 走到服務進程。也因為是跨進程呼叫,每一個方法都要處理 RemoteException,這是與呼叫本地方法最大的不同。

三、布局與資源檔

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/value" />
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edit_value"
            android:hint="@string/hint" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">
        <Button android:id="@+id/button_read"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/read" />
        <Button android:id="@+id/button_write"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/write" />
        <Button android:id="@+id/button_clear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/clear" />
    </LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Freg</string>
    <string name="value">Value</string>
    <string name="hint">Please input a value...</string>
    <string name="read">Read</string>
    <string name="write">Write</string>
    <string name="clear">Clear</string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="shy.luo.freg"
    android:versionCode="1"
    android:versionName="1.0">
    <intent-filter>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</manifest>

由於是放在 AOSP 平台裡編譯的系統應用,AndroidManifest 可以寫得這麼精簡,intent-filter 與 activity 資訊會由平台統一處理。

四、Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE_TAGS := optional
LOCAL_SRC_FILES := $(call all-subdir-java-files)
LOCAL_PACKAGE_NAME := Freg

include $(BUILD_PACKAGE)

五、編譯與部署

在專案目錄執行 mm 即可編譯成 apk:

產物 Freg.apk 位於 out/target/product/generic/system/app 中。

編譯輸出

接著把 Freg.apk 重新打包進 system.img,該映像檔同樣位於 out/target/product/generic 目錄下。

燒機後執行:

執行結果如下:

在輸入框填數字並按下 Write,再按 Read,就能讀回剛剛寫入的值。這條鏈路完整走過了「應用 → Binder → ServiceManager → 服務 → HAL → 驅動 → 硬體」,是理解 Android 分層架構很好的一個練習。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved