利用adb工具android真機環境運行cpp(無需root)

想學習下android下的epoll,可惜macos是基於unix的,無epoll庫支持

那就直接寫cpp到真機上運行吧


項目結構如下圖所示


項目文件爲

android_helloandroid

|-------jni

|-------|-------helloandroid.cpp

|-------|-------Android.mk

|-------build.sh


helloandroid.cpp文件內容爲

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
	printf("%s\n","halo" );
	return 0;
}



Android.mk文件內容爲

# Copyright (C) 2009 The Android 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
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
#
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := helloandroid
LOCAL_SRC_FILES := helloandroid.cpp
LOCAL_STATIC_LIBRARIES := libc

include $(BUILD_EXECUTABLE)
* 注意最後一行爲BUILD_EXECUTABLE


運行腳本build.sh爲

#!/bin/bash
export MODULE_NAME="helloandroid"
ndk-build
adb push libs/armeabi/${MODULE_NAME} /data/local
echo ""
echo "------ run ${MODULE_NAME} -------"
echo ""
adb shell /data/local/${MODULE_NAME}
rm -r libs
rm -r obj
echo ""


注意需要設置環境變量

我設置在了mac的用戶文件裏

~/.bash_profile

export ANDROID_SDK_ROOT=/programes/android-sdk-macosx
export ANDROID_NDK_ROOT=/programes/android-ndk-r9d
export COCOS2DX_ROOT=//files/cocos2d-2.0-x-2.0.4
export NDK_ROOT=/programes/android-ndk-r8c    
export ADB_ROOT=/Applications/Android\ Studio.app/sdk/platform-tools

export PATH=$PATH:$ANDROID_SDK_ROOT
export PATH=$PATH:$ANDROID_NDK_ROOT
export PATH=$PATH:$ADB_ROOT

##
# Your previous /Users/ashqal/.bash_profile file was backed up as /Users/ashqal/.bash_profile.macports-saved_2014-01-14_at_13:20:36
##

# MacPorts Installer addition on 2014-01-14_at_13:20:36: adding an appropriate PATH variable for use with MacPorts.
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
# Finished adapting your PATH environment variable for use with MacPorts.
這樣就可以直接找到adb、ndk-build命令了


最後是打開真機調試模式,插上真機,打開終端,在項目根目錄下運行此build.sh



總結下,

思路就是用ndk-bulid工具的BUILD_EXECUTABLE腳本自動生成android可識別的可運行文件,

然後用adb工具把文件上傳到真機上,

然後用adb shell命令執行此文件


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章