android - 使用 NDK 在 Android Studio 1.0.2 中生成 .so 文件

标签 android android-ndk android-studio java-native-interface android-gradle-plugin

我一直致力于根据演练 here 构建一个非常简单的 NDKSample 应用程序. 我的问题是,我无法让 Android Studio 生成 .so 文件,所以我没有库。

我知道 NDK 支持现在已被弃用,今年年初将提供替代方案,但目前似乎没有任何积极因素阻止我使用此功能。当我构建我的项目时,我收到以下警告(不是错误):

WARNING [Project: :app] Current NDK support is deprecated. Alternative will be provided in the future.

我的项目已构建,但是当我运行 .apk 时它崩溃了(正如预期的那样),因为它找不到 libraries/.so 文件。我们希望这些在构建项目时生成,根据示例,这是正确的吗?这是错误:

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.example.ndksample-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libMyLib.so"

关于我的环境

Windows 7,Android Studio 1.0.2,ADB 正在运行 Nexus 5 (emulator-5554)

我的代码

根据示例:

主 Activity.java

package com.example.ndksample;

//import android.support.v7.app.ActionBarActivity;
// This line is not needed as we are not targetting older devices
import android.app.Activity; //Import this app package to use onCreate etc.
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class MainActivity extends Activity {

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv = (TextView) findViewById(R.id.my_textview);
        tv.setText(getStringFromNative());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public native String getStringFromNative();
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:id="@+id/my_textview"
        android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

ma​​in.c

#include "com_example_ndksample_MainActivity.h"
/* Header for class com_example_ndksample_MainActivity */

JNIEXPORT jstring JNICALL Java_com_example_ndksample_app_MainActivity_getStringFromNative
    (JNIEnv * env, jobject obj)
    {
        return (*env)->NewStringUTF(env, "Hello from Kyle");
    }

build.gradle 注:app

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.ndksample"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"

        ndk {
            moduleName "MyLib"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

local.properties

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file should *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
sdk.dir=D\:\\Programs\\Android\\Android SDK
ndk.dir=D\:\\Programs\\Android\\Android NDK

我的问题,如果有人能够提供帮助,请:

最终,如何生成所需的 .so 文件!!??

可能有助于回答主要问题的子问题:

我的目录布局在 app 下有我的 jni 目录(所以 NDKSample/app/jni),这是正确的吗?我被告知here不要将 c 文件放在标准 jni 目录中。我试了一下,在构建项目时,它崩溃了。错误:

*FAILURE:构建失败,出现异常。

  • 出了什么问题: 任务 ':app:compileDebugNdk' 执行失败。

    com.android.ide.common.internal.LoggedErrorException: Failed to run command: D:\Programs\Android\Android NDK\ndk-build.cmd NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=C:\Users\Kyle\AndroidStudioProjects\NDKSample\app\build\intermediates\ndk\debug\Android.mk APP_PLATFORM=android-21 NDK_OUT=C:\Users\Kyle\AndroidStudioProjects\NDKSample\app\build\intermediates\ndk\debug\obj NDK_LIBS_OUT=C:\Users\Kyle\AndroidStudioProjects\NDKSample\app\build\intermediates\ndk\debug\lib APP_ABI=all Error Code: 1*

上面来自 Intel 的示例没有指导我构建 Android.mk 文件,示例没有,他生成了一个工作应用程序。我试过将一个放在 jni 目录中,但它没有帮助。我应该创建一个吗?如果是的话,我应该把它放在哪里

我的目录的下图是否正确? Directories

如有任何帮助,我们将不胜感激。

凯尔

最佳答案

Android Studio 中当前的 NDK 支持很少,因此他们在 1.0 中弃用了它。

使用它时,会自动生成一个 Android.mk 文件,并在您构建项目时编译您的源代码。现在看来编译失败了,但您应该能够从 Gradle 控制台获取初始错误消息。

如果您没有收到任何其他错误消息,我怀疑调用 ndk-build 失败,因为您的 NDK 安装路径 (Android NDK) 中有一个空格

您可以修复当前错误并继续当前设置,或者禁用默认的 NDK 集成,创建 Android.mk/Application.mk 文件并调用 < em>ndk-build(.cmd) 你自己或来自任务:

import org.apache.tools.ant.taskdefs.condition.Os

android {
    sourceSets.main {
        jniLibs.srcDir 'src/main/libs' //set .so files location to libs
        jni.srcDirs = [] //disable automatic ndk-build call
    }

    // call regular ndk-build(.cmd) script from app directory
    task ndkBuild(type: Exec) {
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
        } else {
            commandLine 'ndk-build', '-C', file('src/main').absolutePath
        }
    }
    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn ndkBuild
    }
}

关于android - 使用 NDK 在 Android Studio 1.0.2 中生成 .so 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27774604/

相关文章:

java - 缩放时 Android map V2 瓦片消失

Android Sync Adapter - 手动同步

android - 使用 Robolectric 和 Mockito 模拟 PackageManager

android - 使用 NDK 构建 Android openssl 无法正确生成 arm4 程序集文件

android - "AndroidManifest.xml doesn' t 存在或有不正确的根标签”错误

android - Cordova Android 黑色启动画面

android - 我该如何解决这个致命异常?

sdk - Android SDK 管理器 - 无法删除 4.4W (API20) 包

java - 刷新 ListView 数据库

android - 如何在Android系统应用程序中升级 native 库