在Android Studio中创建.so文件,并在Android中的另一个应用程序中使用它 [英] Create .so file in android studio and used it in another application in Android

查看:113
本文介绍了在Android Studio中创建.so文件,并在Android中的另一个应用程序中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习android ndk.我是新手.我使用添加c ++支持在Android Studio 3.0.1中创建了一个项目.在此应用程序中,用户在活动中输入数字,并使用c ++代码告诉其是否为质数.这是我的活动代码:

I am started learning android ndk. I am new in it. I had created one project in Android studio 3.0.1 using adding c++ support. In this application user enter number in activity and using c++ code it tells whether its prime number or not. Here is my Activity code:

package com.app.androidkt.samplendk;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


EditText number_chk;
Button result_btn;


// Used to load the 'native-lib' library on application startup.
static {
    System.loadLibrary("native-lib");
}

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

    result_btn = (Button)findViewById(R.id.result_btn);
    number_chk = (EditText) findViewById(R.id.number_chk);
    final TextView tv = (TextView) findViewById(R.id.sample_text);



    result_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int number;
            try{
                number = Integer.parseInt(number_chk.getText().toString());
                tv.setText(isPrimeNumber(number));
            }
            catch (Exception e)
            {
                tv.setText("Please enter valid number");
            }
        }
    });

    // Example of a call to a native method


}

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */
//public native String stringFromJNI();
private native String isPrimeNumber(int number);
}

我的native-lib.cpp就像:

my native-lib.cpp is like:

#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring

JNICALL

Java_com_app_androidkt_samplendk_MainActivity_isPrimeNumber(
    JNIEnv *jenv,
    jobject self,
    jint number)
{
std::string result = "Prime Number";
int i;
for(i = 2; i <= number / 2; ++i)
{
    if(number % i == 0)
    {
        result = "Not a Prime Number";
        break;
    }
}
return jenv->NewStringUTF(result.c_str());
}

我的app.gradle如下所示,我对此没有做任何更改:

my app.gradle is like below, I had not changed anything in this:

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.app.androidkt.samplendk"
    minSdkVersion 15
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    externalNativeBuild {
        cmake {
            cppFlags ""
        }
    }
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
   }
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

我的应用程序结构如下:

My application structure is like:

到目前为止,一切都很完美.应用程序运行,并给我预期的结果.现在我想要的是-创建一个新项目并在项目.so文件上方使用,因此在我的新项目中,我不想再次编写c ++逻辑.为此,我计划在该添加目录中以jniLibs的形式创建一个新项目,并复制上述项目的.so文件.但是我在上面的项目中没有.so文件.当我提取上述项目的apk文件时,我只有一个这样的文件.

Upto this everything is perfect. Application runs and give me expected result. Now what i want is - Create new project and use above project .so file so in my new project I don't want to write c++ logic again. For this I am planning create a new Project in that add directory as jniLibs and copy .so file of above project. But I did not got .so file in above project. When I extract apk file of above project then I got only one so file.

  1. 那么如何为上述项目创建.so文件
  2. 如何在另一个项目中使用此.so文件

任何建议和答案将不胜感激.预先感谢.

Any suggestion and answer will be appreciated. Thanks in advance.

推荐答案

最佳做法是不要在MainActivity类中创建本机方法.如果您为isPrimeNumber()和其他可能的本机方法创建单独的小类,则共享工作将更加容易.

The best practice is not to create native methods in the MainActivity class. If you create a separate small class for isPrimeNumber() and possibly other native methods, sharing your work will be easier.

在您的情况下,可以将方法声明为static,因为它不依赖于调用该方法的Java对象.本机静态方法具有更好的性能,并且-再次-更易于共享.

In your case, the method can be declared static, because it does not depend on the Java object that invokes it. Native static methods have better performance, and – again – are easier to share.

Android Studio将所有内置的libnative-lib.so文件放在 app/build/intermediates 目录中.您会在不同的子目录中找到 fat <​​/em>库以及较小的 stripped 文件.您可以将较小的副本复制到第二个项目的 jniLibs 目录中.

Android Studio puts all built libnative-lib.so files in the app/build/intermediates directory. You will find fat libraries and also smaller, stripped, files in different subdirectories. You can copy the smaller ones to the jniLibs directory of the second project.

如果您的C ++使用共享的STL库,例如libgnustl_shared.so,您还必须将其复制到第二个项目的 jniLibs 目录.

If your C++ uses a shared STL library, e.g. libgnustl_shared.so, you must also copy it the the jniLibs directory of the second project.

我们通常通过在gradle脚本中定义 abiFilters 来限制所构建的本机库的变体.您上面发布的脚本没有任何功能,并且从表面上看,它不会创建拆分的APK,因此我无法解释为什么您在APK中仅看到一个libnative-lib.so.

We often restrict the variants of native library we build, by defining abiFilters in the gradle script. The script you posted above does not feature any, and on the face of it, it does not create split APKs, so I cannot explain why you see only one libnative-lib.so in your APK.

请注意,这些天不存在 mips 设备,并且 armeabi (旧的v6变体)也极为罕见.最新的NDK提醒您,长期以来不会支持这些ABI.

Note that mips devices do not exist these days, and armeabi (old v6 variant) are also extremely rare. The latest NDK reminds that these ABIs will not be supported for long.

顺便说一句,您无需将其重命名为ZIP:Android Studio在其菜单中具有 Analyze APK ,并且可以可靠地向您显示文件的内容.

By the way, you don't need to rename it to ZIP: Android Studio has Analyze APK in its menus, and will show you reliably the contents of your file.

这篇关于在Android Studio中创建.so文件,并在Android中的另一个应用程序中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆