2016年7月10日 星期日

linux 底下安裝 android ndk toolchain

1. 先上官網下載 ndk 檔案:
      http://dl.google.com/android/repository/android-ndk-r12b-linux-x86_64.zip
2. 解壓縮:
      unzip android-ndk-r12b-linux-x86_64.zip
3.  cd android-ndk-r12b/build/tools
4. 執行 make_standalone_toolchain.py 安裝 arm base toolchain, 假設把它安裝到 /tmp/arm 下面
      python make_standalone_toolchain.py --arch= arm --install-dir=/tmp/arm
5. 修改 /etc/profile 加入 PATH, 讓它可找到 toolchain binary:
      export PATH=/tmp/arm/bin:$PATH
6. 簡單寫個 c程式 hello.c, 將他編譯程可執行檔:
      arm-linux-androideabi-gcc  hello.c -o hello
7. 連接上手機, 開啟"開發人員選項"模式, 安全和隱私設定必須將"不明的來源"勾選讓它可以使用. 這樣連接後,  adb devices 連接後會有警告出現, 點擊"接受"或"允許", 透過 USB debug.
8. 上傳 hello 到 android 的內部記憶體(先上傳到 SDCARD, 再複製到目的地), 若上傳到 SDCARD 上是不能被執行的, 另外上傳完還需要將它修改成可執行檔, 因此要有 root 權限:
      adb devices
      adb push hello /sdcard/hello
      adb shell
      su
      cd /data/local
      cp /sdcard/hello .
      ./hello
8. 若沒有 root 的話, 可以透過 app 安裝方式將執行檔放到 assets 目錄下, 在 app 裏面透過 asset manager 開啟檔案, 將它複製到安裝 app 的目錄裏面(Android 4.2 的 FileOutputStream 會被放在 files目錄內):

            InputStream in = context.getAssets().open(filename);
            FileOutputStream out = context.openFileOutput(filename, MODE_WORLD_READABLE);
            int read;
            byte[] buffer = new byte[4096];
            while ((read = in.read(buffer)) > 0) {
               out.write(buffer, 0, read);
            }
            out.close();
            in.close();

再透過 Runtime.getRuntime().exec( ) 執行 chmod 755 改成可執行檔
最後同樣透過 Runtime.getRuntime().exec( ) 讓它執行:

            Process process = Runtime.getRuntime().exec(commandLine);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer output = new StringBuffer();
            char[] buffer = new char[4096];
            int read;
            while ((read = reader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            reader.close();
            process.waitFor();


沒有留言: