绑定 .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) 文件是 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 Studio 中创建 Android 存档文件的示例,我们将创建一个绑定库textanalyzer.aarWe'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.aar:The 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.aar:In addition, this sample app will retrieve and display an image resource that is packaged in textanalyzer.aar:

Xamarin monkey 图像Xamarin monkey image

此映像资源驻留在res/drawable/monkey.pngtextanalyzer.aarThis 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). 将解决方案命名AarBinding:Name the solution AarBinding:

    创建 AarBindings 项目Create AarBindings project

  2. 该模板包含Jar文件夹在其中添加你。AAR(s) 到绑定库项目。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.aar前面下载的文件,选择它,然后单击添加: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.aarLibraryProjectZipSet the Build Action for textanalyzer.aar to LibraryProjectZip. 在 Visual Studio for Mac 中,右键单击textanalyzer.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

若要使用这个。Xamarin.Android 应用程序中的 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. 将新项目命名BindingTest:Name 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 (其包装基础 JavanumConsonants方法),和NumVowels(其包装基础 JavanumVowels方法)。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. 请注意using语句的命名空间的绑定库 (在这种情况下, Com.Xamarin.Textcounter):Notice 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

请尝试点击计数辅音按钮。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.

若要访问的图像资源,请使用Resource.Drawable映像打包内部名称。AAR。To access an image resource, you use the Resource.Drawable name for the image packed inside the .AAR. 例如,可以引用image.png中。通过使用 AAR 文件@drawable/image:For 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. 若要执行此操作,您可以使用Resource.Layout打包到内的布局的名称。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/drawable/monkey.pngThe 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.axml),并添加ImageView末尾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. 应用程序将启动并显示在左侧的屏幕截图–,点击计数辅音,结果将显示在右侧所示: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:

BindingTest 显示辅音计数BindingTest 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.