绑定 .AARBinding an .AAR

本演练提供了从 Android 创建 Xamarin Android Java 绑定库的分步说明。AAR 文件。This walkthrough provides step-by-step instructions for creating a Xamarin.Android Java Bindings Library from an Android .AAR file.

概述Overview

Android 存档(。AAR) file 是 Android 库的文件格式。The Android Archive (.AAR) file is the file format for Android libraries. 无.AAR 文件是一个。包含以下内容的 ZIP 存档:An .AAR file is a .ZIP archive that contains the following:

  • 已编译的 Java 代码Compiled Java code
  • 资源 IdResource IDs
  • 资源Resources
  • 元数据(例如,活动声明、权限)Meta-data (for example, Activity declarations, permissions)

在本指南中,我们将逐步介绍为单一的绑定库创建基础知识。AAR 文件。In this guide, we'll step through the basics of creating a Bindings Library for a single .AAR file. 有关一般情况下的 Java 库绑定概述(带有基本的代码示例),请参阅绑定 Java 库For an overview of Java library binding in general (with a basic code example), see Binding a Java Library.

重要

绑定项目只能包含一个。AAR 文件。A binding project can only include one .AAR file. 如果为。AAR 依赖关系。AAR,则这些依赖项应包含在其自己的绑定项目中,然后引用这些依赖项。If the .AAR dependencies on other .AAR, then those dependencies should be contained in their own binding project and then referenced. 请参阅Bug 44573See Bug 44573.

演练Walkthrough

我们将为示例 Android 存档文件创建一个绑定库,该文件是在 Android Studio, aar中创建的。We'll create a Bindings Library for an example Android archive file that was created in Android Studio, textanalyzer.aar. 此.AAR 包含一个TextCounter类,其静态方法用于计算字符串中元音和辅音的数目。This .AAR contains a TextCounter class with static methods that count the number of vowels and consonants in a string. 此外, textanalyzer aar包含一个图像资源,用于帮助显示计数结果。In addition, textanalyzer.aar contains an image resource to help display the counting results.

我们将使用以下步骤从中创建绑定库。AAR 文件:We'll use the following steps to create a Bindings Library from the .AAR file:

  1. 创建新的 Java 绑定库项目。Create a new Java Bindings Library project.

  2. 添加单个。AAR 文件。Add a single .AAR file to the project. 绑定项目只能包含一个。AAR.A binding project may only contain a single .AAR.

  3. 为设置相应的生成操作。AAR 文件。Set the appropriate build action for the .AAR file.

  4. 选择一个目标框架。AAR 支持。Choose a target framework that the .AAR supports.

  5. 生成绑定库。Build the Bindings Library.

一旦创建了绑定库,我们将开发一个小型 Android 应用程序,该应用程序会提示用户输入文本字符串,然后调用。用于分析文本的 AAR 方法,从中检索图像。AAR,并显示与图像一起显示的结果。Once we've created the Bindings Library, we'll develop a small Android app that prompts the user for a text string, calls .AAR methods to analyze the text, retrieves the image from the .AAR, and displays the results along with the image.

示例应用将访问TextCounter textanalyzer 的类 。 aarThe sample app will access the TextCounter class of textanalyzer.aar:

package com.xamarin.textcounter;

public class TextCounter
{
    ...
    public static int numVowels (String text) { ... };
    ...
    public static int numConsonants (String text) { ... };
    ...
}

此外,此示例应用将检索并显示打包在 textanalyzer 中的图像资源 。 aarIn addition, this sample app will retrieve and display an image resource that is packaged in textanalyzer.aar:

Xamarin 猴子映像Xamarin monkey image

此图像资源驻留在textanalyzer. aar中的res//猴子。This image resource resides at res/drawable/monkey.png in textanalyzer.aar.

创建绑定库Creating the Bindings Library

在开始执行以下步骤之前,请下载示例textanalyzer. aar Android 存档文件:Before commencing with the steps below, please download the example textanalyzer.aar Android archive file:

  1. 从 "Android 绑定库" 模板开始创建一个新的绑定库项目。Create a new Bindings Library project starting with the Android Bindings Library template. 你可以使用 Visual Studio for Mac 或 Visual Studio (下面的屏幕截图显示 Visual Studio,但 Visual Studio for Mac 非常相似)。You can use either Visual Studio for Mac or Visual Studio (the screenshots below show Visual Studio, but Visual Studio for Mac is very similar). 将解决方案命名为AarBindingName the solution AarBinding:

    创建 AarBindings 项目Create AarBindings project

  2. 该模板包含一个jar文件夹,可在其中添加。AAR 绑定库项目。The template includes a Jars folder where you add your .AAR(s) to the Bindings Library project. 右键单击 " jar " 文件夹,然后选择 "添加 > 现有项Right-click the Jars folder and select Add > Existing Item:

    添加现有项Add existing item

  3. 导航到之前下载的textanalyzer文件,选择它,然后单击 "添加":Navigate to the textanalyzer.aar file downloaded earlier, select it, and click Add:

    添加 textanalayzer。 aarAdd textanalayzer.aar

  4. 验证textanalyzer aar文件是否已成功添加到项目中:Verify that the textanalyzer.aar file was successfully added to the project:

    添加了 textanalyzer aar 文件The textanalyzer.aar file was added

  5. 将 textanalyzer 的生成操作设置为aar LibraryProjectZipSet the Build Action for textanalyzer.aar to LibraryProjectZip. 在 Visual Studio for Mac 中,右键单击 " aar " 以设置生成操作。In Visual Studio for Mac, right-click textanalyzer.aar to set the Build Action. 在 Visual Studio 中,可在 "属性" 窗格中设置生成操作:In Visual Studio, the Build Action can be set in the Properties pane):

    将 textanalyzer aar 生成操作设置为 LibraryProjectZipSetting the textanalyzer.aar build action to LibraryProjectZip

  6. 打开项目属性以配置目标框架Open the project Properties to configure the Target Framework. 如果为。AAR 使用任何 Android Api,将目标框架设置为的 API 级别。AAR 期望。If the .AAR uses any Android APIs, set the Target Framework to the API level that the .AAR expects. (有关目标框架设置和一般 Android API 级别的详细信息,请参阅了解 ANDROID Api 级别。)(For more information about the Target Framework setting and Android API levels in general, see Understanding Android API Levels.)

    设置绑定库的目标 API 级别。Set the target API level for your Bindings Library. 在此示例中,我们可以自由使用最新的平台 API 级别(API 级别23),因为我们的textanalyzer不依赖 Android api:In this example, we are free to use the latest platform API level (API level 23) because our textanalyzer does not have a dependency on Android APIs:

    将目标级别设置为 API 23Setting the target level to API 23

  7. 生成绑定库。Build the Bindings Library. 绑定库项目应成功生成并生成输出。DLL 位于以下位置:AarBinding/bin/Debug/AarBinding.dllThe Bindings Library project should build successfully and produce an output .DLL at the following location: AarBinding/bin/Debug/AarBinding.dll

使用绑定库Using the Bindings Library

使用此。DLL,必须首先添加对绑定库的引用。To consume this .DLL in your Xamarin.Android app, you must first add a reference to the Bindings Library. 使用以下步骤:Use the following steps:

  1. 我们要在与绑定库相同的解决方案中创建此应用程序,以简化本演练。We're creating this app in the same Solution as the Bindings Library to simplify this walkthrough. (使用绑定库的应用程序也可以驻留在不同的解决方案中。)创建新的 Xamarin Android 应用:右键单击该解决方案,然后选择 "添加新项目"。(The app that consumes the Bindings Library could also reside in a different Solution.) Create a new Xamarin.Android app: right-click the Solution and select Add New Project. 将新项目命名为BindingTestName the new project BindingTest:

    创建新的 BindingTest 项目Create new BindingTest project

  2. 右键单击 " BindingTest " 项目的 "引用" 节点,然后选择 "添加引用 ... ":Right-click the References node of the BindingTest project and select Add Reference...:

    单击 "添加引用"Click Add Reference

  3. 选择前面创建的AarBinding项目,然后单击 "确定"Select the AarBinding project created earlier and click OK:

    检查 AAR 绑定项目Check the AAR binding project

  4. 打开BindingTest项目的 "引用" 节点,验证是否存在AarBinding引用:Open the References node of the BindingTest project to verify that the AarBinding reference is present:

    AarBinding 在 "引用" 下列出AarBinding is listed under References

若要查看绑定库项目的内容,可以双击该引用以在对象浏览器中打开它。If you would like to view the contents of the Binding Library project, you can double-click the reference to open it in the Object Browser. 您可以看到Com.Xamarin.Textcounter命名空间的映射内容(从 Java com.xamarin.textanalyzezr包映射),并且您可以TextCounter查看类的成员:You can see the mapped contents of the Com.Xamarin.Textcounter namespace (mapped from the Java com.xamarin.textanalyzezr package) and you can view the members of the TextCounter class:

查看对象浏览器Viewing the Object Browser

上面的屏幕截图突出显示TextAnalyzer了该示例应用程序将调用的NumConsonants两个方法:(包装numConsonants基础 java 方法) NumVowels和(包装基础 java numVowels方法)。The above screenshot highlights the two TextAnalyzer methods that the example app will call: NumConsonants (which wraps the underlying Java numConsonants method), and NumVowels (which wraps the underlying Java numVowels method).

访问.AAR 类型Accessing .AAR Types

添加指向绑定库的应用的引用后,可以在中访问 Java 类型。AAR 访问C#类型(感谢C#包装)。After you add a reference to your app that points to the Binding Library, you can access Java types in the .AAR as you would access C# types (thanks to the C# wrappers). C#应用代码可以调用TextAnalyzer方法,如以下示例中所示:C# app code can call TextAnalyzer methods as illustrated in this example:

using Com.Xamarin.Textcounter;
...
int numVowels = TextCounter.NumVowels (myText);
int numConsonants = TextCounter.NumConsonants (myText);

在上面的示例中,我们将TextCounter在类中调用静态方法。In the above example, we're calling static methods in the TextCounter class. 但是,还可以实例化类和调用实例方法。However, you can also instantiate classes and call instance methods. 例如,如果你的。AAR 包装一个具有实例Employee方法buildFullName的名为的类,可以实例MyClass化并使用它,如下所示:For example, if your .AAR wraps a class called Employee that has the instance method buildFullName, you can instantiate MyClass and use it as seen here:

var employee = new Com.MyCompany.MyProject.Employee();
var name = employee.BuildFullName ();

以下步骤将代码添加到应用程序,以便它提示用户输入文本,使用TextCounter分析文本,然后显示结果。The following steps add code to the app so that it prompts the user for text, uses TextCounter to analyze the text, and then displays the results.

BindingTest布局(main.axml)替换为以下 XML。Replace the BindingTest layout (Main.axml) with the following XML. 此布局包含一个EditText用于文本输入的,两个按钮用于启动元音和辅音计数:This layout has an EditText for text input and two buttons for initiating vowel and consonant counts:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation             ="vertical"
    android:layout_width            ="fill_parent"
    android:layout_height           ="fill_parent" >
    <TextView
        android:text                ="Text to analyze:"
        android:textSize            ="24dp"
        android:layout_marginTop    ="30dp"
        android:layout_gravity      ="center"
        android:layout_width        ="wrap_content"
        android:layout_height       ="wrap_content" />
    <EditText
        android:id                  ="@+id/input"
        android:text                ="I can use my .AAR file from C#!"
        android:layout_marginTop    ="10dp"
        android:layout_gravity      ="center"
        android:layout_width        ="300dp"
        android:layout_height       ="wrap_content"/>
    <Button
        android:id                  ="@+id/vowels"
        android:layout_marginTop    ="30dp"
        android:layout_width        ="240dp"
        android:layout_height       ="wrap_content"
        android:layout_gravity      ="center"
        android:text                ="Count Vowels" />
    <Button
        android:id                  ="@+id/consonants"
        android:layout_width        ="240dp"
        android:layout_height       ="wrap_content"
        android:layout_gravity      ="center"
        android:text                ="Count Consonants" />
</LinearLayout>

MainActivity.cs的内容替换为以下代码。Replace the contents of MainActivity.cs with the following code. 如本示例中所示,按钮事件处理程序调用TextCounter驻留在中的包装方法。AAR 并使用 toast 来显示结果。As seen in this example, the button event handlers call wrapped TextCounter methods that reside in the .AAR and use toasts to display the results. 请注意绑定库的命名空间的Com.Xamarin.Textcounter语句(在本例中为):usingNotice the using statement for the namespace of the bound library (in this case, Com.Xamarin.Textcounter):

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Views.InputMethods;
using Com.Xamarin.Textcounter;

namespace BindingTest
{
    [Activity(Label = "BindingTest", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        InputMethodManager imm;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            imm = (InputMethodManager)GetSystemService(Context.InputMethodService);

            var vowelsBtn = FindViewById<Button>(Resource.Id.vowels);
            var consonBtn = FindViewById<Button>(Resource.Id.consonants);
            var edittext = FindViewById<EditText>(Resource.Id.input);
            edittext.InputType = Android.Text.InputTypes.TextVariationPassword;

            edittext.KeyPress += (sender, e) =>
            {
                imm.HideSoftInputFromWindow(edittext.WindowToken, HideSoftInputFlags.NotAlways);
                e.Handled = true;
            };

            vowelsBtn.Click += (sender, e) =>
            {
                int count = TextCounter.NumVowels(edittext.Text);
                string msg = count + " vowels found.";
                Toast.MakeText (this, msg, ToastLength.Short).Show ();
            };

            consonBtn.Click += (sender, e) =>
            {
                int count = TextCounter.NumConsonants(edittext.Text);
                string msg = count + " consonants found.";
                Toast.MakeText (this, msg, ToastLength.Short).Show ();
            };

        }
    }
}

编译并运行BindingTest项目。Compile and run the BindingTest project. 此应用将开始,并在左侧显示屏幕截图( EditText用一些文本进行初始化,但你可以点击它进行更改)。The app will start and present the screenshot on the left (the EditText is initialized with some text, but you can tap it to change it). 点击 "计数元音" 时,toast 将显示元音的数目,如下所示:When you tap COUNT VOWELS, a toast displays the number of vowels as shown on the right:

运行 BindingTest 的屏幕截图Screenshots from running BindingTest

尝试点击COUNT 辅音按钮。Try tapping the COUNT CONSONANTS button. 此外,您还可以修改文本行并再次点击这些按钮以测试不同的元音和辅音计数。Also, you can modify the line of text and tap these buttons again to test for different vowel and consonant counts.

访问.AAR 资源Accessing .AAR Resources

Xamarin 工具合并了R数据。AAR 到应用的资源类中。The Xamarin tooling merges the R data from the .AAR into your app's Resource class. 因此,您可以访问。使用与访问项目资源路径中的资源相同的方式,从布局(和代码隐藏)中 AAR 资源。As a result, you can access .AAR resources from your layout (and from code-behind) in the same way as you would access resources that are in the Resources path of your project.

若要访问图像资源,请使用资源。 在中打包的映像的名称。AAR.To access an image resource, you use the Resource.Drawable name for the image packed inside the .AAR. 例如,可以在中引用 .png 。AAR 文件,使用@drawable/imageFor example, you can reference image.png in the .AAR file by using @drawable/image:

<ImageView android:src="@drawable/image" ... />

你还可以访问驻留在中的资源布局。AAR.You can also access resource layouts that reside in the .AAR. 为此,请使用资源. 布局中打包的布局的名称。AAR.To do this, you use the Resource.Layout name for the layout packaged inside the .AAR. 例如:For example:

var a = new ArrayAdapter<string>(this, Resource.Layout.row_layout, ...);

Textanalyzer. aar示例包含位于res/可绘制/猴子的图像文件。The textanalyzer.aar example contains an image file that resides at res/drawable/monkey.png. 让我们访问此映像资源,并将其用于示例应用:Let's access this image resource and use it in our example app:

编辑BindingTest布局(main.axmlImageView ,并将添加到LinearLayout容器末尾。Edit the BindingTest layout (Main.axml) and add an ImageView to the end of the LinearLayout container. ImageView显示的图像位于 @drawable/monkey** ; 此映像将加载的资源部分从textanalyzer.aar**:This ImageView displays the image found at **@drawable/monkey**; this image will be loaded from the resource section of textanalyzer.aar:

    ...
    <ImageView
        android:src                 ="@drawable/monkey"
        android:layout_marginTop    ="40dp"
        android:layout_width        ="200dp"
        android:layout_height       ="200dp"
        android:layout_gravity      ="center" />

</LinearLayout>

编译并运行BindingTest项目。Compile and run the BindingTest project. 点击COUNT 辅音时,该应用将启动并在–左侧显示屏幕截图,结果显示在右侧:The app will start and present the screenshot on the left – when you tap COUNT CONSONANTS, the results are displayed as shown on the right:

显示辅音计数的 BindingTestBindingTest displaying consonant count

祝贺你!Congratulations! 已成功绑定 Java 库。AAR!You've successfully bound a Java library .AAR!

总结Summary

在本演练中,我们创建了的绑定库。AAR 文件,将绑定库添加到最小测试应用,并运行应用以验证C#代码是否可以调用驻留在中的 Java 代码。AAR 文件。In this walkthrough, we created a Bindings Library for an .AAR file, added the Bindings Library to a minimal test app, and ran the app to verify that our C# code can call Java code residing in the .AAR file. 此外,我们还扩展了应用程序以访问和显示驻留在中的图像资源。AAR 文件。In addition, we extended the app to access and display an image resource that resides in the .AAR file.