Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

用 Eclipse 與 NDK 打造一個帶 Native 程式碼的 Service

編輯:初階開發

NDK 是 Google 提供給「需要在 App 裡寫 C/C++」場景的開發工具。之所以需要它,是因為 Android 採用自個兒改寫的 C 函式庫(Bionic),並搭配自己的編譯器與連結器,想拿通用 toolchain 去編 Android 裡的 C/C++ 程式碼會相當痛苦。

早期只能把程式碼塞進整個 Android 原始碼樹,借用 Android Build System 編譯(可參考 development/samples 下的 PlatformLibrary 與 SimpleJNI 兩個範例),缺點是得先建立完整的建置環境,第一次全量編譯非常耗時。NDK 則提供了一套相對輕量的 Build System:你只要依規定給定應用位置、Native 程式碼位置與要編的模組,它就能產出 Shared Library,並自動複製到 SDK 的開發環境下,方便後續打包成 APK。詳細說明可見 NDK 的 docs 目錄。

以下是一個實際操作過的小實驗:整體結構基本上就是一個 Eclipse 下的 Service 專案,只是 Service 裡用到的 shared library 改由 NDK 產生。

實驗環境:Ubuntu、SDK 1.5r2、NDK 1.5r1、Eclipse 3.4(含 ADT plugin)。

一、建立專案與 AIDL 介面

在 Eclipse 中新建 Android Project,專案名 MyServer,套件名 ndk.sample.myservice。接著在 src/ndk.sample.myservice 下新增 aidl 檔 IMyService.aidl,Eclipse 會自動在 gen 目錄產生對應的 IMyService.java:

package ndk.sample.myservice;

interface IMyService {
    String getGreetings(in String toName);
}

二、實作 Service

package ndk.sample.myservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    private final IMyService.Stub binder = new IMyService.Stub() {
        public String getGreetings(String toName) {
            return get_greetings(toName);
        }
    };

    @Override public void onCreate()  { Log.v("MyService", "Lifecycle - onCreate"); }
    @Override public void onDestroy() { Log.v("MyService", "Lifecycle - onDestroy"); }

    @Override
    public void onStart(Intent intent, int startId) {
        Log.v("MyService", "Lifecycle - onStart: id = " + Integer.toString(startId));
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.v("MyService", "Lifecycle - onBind");
        return this.binder;
    }

    @Override public void onRebind(Intent intent) { Log.v("MyService", "Lifecycle - onRebind"); }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.v("MyService", "Lifecycle - onUnbind");
        return false;
    }

    static { System.loadLibrary("mynativecodes"); }

    public native String get_greetings(String toName);
}

注意最末兩行:static 區塊載入 native 函式庫,再用 native 關鍵字宣告方法本體,實作則在 C 端。

三、實作測試用的用戶端

public class TestClient extends Activity {
    private TextView tvGreetings;
    private EditText etName;
    private IMyService service;

    private ServiceConnection connection = new ServiceConnection() {
        @Override public void onServiceConnected(ComponentName className, IBinder iservice) {
            service = IMyService.Stub.asInterface(iservice);
        }
        @Override public void onServiceDisconnected(ComponentName className) {
            service = null;
        }
    };

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

        tvGreetings = (TextView) findViewById(R.id.tvGreetings);
        etName = (EditText) findViewById(R.id.etName);

        Button btnHello = (Button) findViewById(R.id.btnHello);
        btnHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String toName = etName.getText().toString();
                try {
                    String greetings = service.getGreetings(toName);
                    tvGreetings.setText(greetings);
                    etName.setText("");
                } catch (RemoteException e) {
                    Log.e("TestClient", "error", e);
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        boolean rc = bindService(new Intent(IMyService.class.getName()),
                                 connection, BIND_AUTO_CREATE);
        if (rc == false) Log.v("TestClient", "Fail to bindService");
    }

    @Override
    public void onStop() {
        super.onStop();
        unbindService(connection);
    }
}

跨行程呼叫屬於遠端介面,因此 service.getGreetings() 一定要包在 try-catch 裡處理 RemoteException,這是 AIDL 架構下的固定動作。

四、在 Manifest 註冊 Service

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="ndk.sample.myservice"
    android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".TestClient" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService">
            <intent-filter>
                <action android:name="ndk.sample.myservice.IMyService" />
            </intent-filter>
        </service>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest>

五、加入 NDK 的建置檔

先在專案根目錄新增 Application.mk,宣告要編譯哪些模組:

APP_PROJECT_PATH := $(call my-dir)
APP_MODULES := mynativecodes

接著建立 jni 目錄,產生 JNI 標頭檔:

$ cd MyServer/jni
$ javah -jni -classpath ../bin ndk.sample.myservice.MyService

會得到 ndk_sample_myservice_MyService.h。然後在同一個目錄下寫 mynative.c:

#include "ndk_sample_myservice_MyService.h"
#include <stdio.h>
#include <string.h>

JNIEXPORT jstring JNICALL Java_ndk_sample_myservice_MyService_get_1greetings
  (JNIEnv *env, jobject obj, jstring name)
{
    // 為簡化示範,使用固定大小的緩衝區
    char buf[128];
    const char *str;

    str = (*env)->GetStringUTFChars(env, name, NULL);
    if (str == NULL) {
        return NULL;
    }

    if (strlen(str) == 0) {
        sprintf(buf, "Who are you?");
    } else {
        sprintf(buf, "Hello, %s!!!", str);
    }

    (*env)->ReleaseStringUTFChars(env, name, str);
    return (*env)->NewStringUTF(env, buf);
}

GetStringUTFChars 取得的記憶體必須以 ReleaseStringUTFChars 釋放,否則會造成資源洩漏。另外 Java 端的方法名 get_greetings 在 JNI 函式名中會被轉成 get_1greetings,底線要寫成 _1,這也是新手最常卡住的地方。

最後在同一目錄補上 android.mk:

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

LOCAL_MODULE := mynativecodes
LOCAL_SRC_FILES := mynative.c

include $(BUILD_SHARED_LIBRARY)

六、編譯與打包

回到 NDK 目錄,建立指向應用與函式庫的連線。NDK 並不要求你把程式碼放進它的目錄,但必须在 sources 與 apps 底下建立指向 Application.mk 與 android.mk 所在路徑的 symbolic link:

$ cd <android-ndk>/sources
$ ln -s <my-service-dir> myservice
$ cd ../apps
$ ln -s <my-service-dir>/jni/ mynativecodes
$ cd ..
$ make APP=myservice V=1

APP 指定要編的應用(路徑名),是必填參數;V=1 則是顯示完整編譯指令,方便除錯。編譯成功後,libs/armeabi 下會產生 libmynativecodes.so,Eclipse 的專案樹中也能看到。最後照一般流程把 MyServer 打包成 APK 即可。

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