如何限制对Android库的某些API的访问 [英] How to limit access to some APIs of Android library

查看:126
本文介绍了如何限制对Android库的某些API的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建android库,以便使用该库的应用程序无法访问其所有类.我该怎么办?

I want to build android library so that all its classes except of one will be not accessible for an application that will use this library. How I can do it?

推荐答案

如果您的SDK捆绑为JAR文件(而不是AAR),则可以通过创建两个JAR文件(一个是常规库,另一个是剥离的-代表API).让我们来看一个例子.

If your SDK is bundled as JAR file (instead of AAR), you can mimic internal APIs hiding in the same way as it is done in Android SDK by creating two JAR files (one will be regular library, and second stripped - which will represent the API). Let's see an example.

完整库(我将其称为 sdk-runtime.jar )将由一个类组成:Api.java:

Full library (I'll call it sdk-runtime.jar) will consist of a single class: Api.java:

package info.osom.sdk;

public class Api {
    public static void init() {
        System.out.println("Api.init()");
        anotherPublicMethod();
    }

    public static void anotherPublicMethod() {
        System.out.println("Api.anotherPublicMethod()");
    }
}

剥离的库(我将其称为 sdk-api.jar )将隐藏anotherPublicMethod(),并仅公开init()方法:

Stripped library (I'll call it sdk-api.jar) will hide the anotherPublicMethod(), and expose only the init() method:

package info.osom.sdk;

public class Api {
    public static void init() {
        throw new RuntimeException("stub!");
    }
}

指示您的SDK使用方按照以下方式配置其应用程序依赖项:

Instruct your SDK consumers to configure their application dependencies as following:

dependencies {
    provided files('libs/sdk-api.jar')
    apk files('libs/sdk-runtime.jar')
}

根据文档:

provided配置将依赖项添加到编译中 仅classpath(不会添加到APK).
注意::如果要创建Android应用模块,则不能将provided用于AAR依赖项,而不能用于JAR.在Android库中 模块,您可以将其用于JAR和AAR.

provided configuration adds the dependency to the compilation classpath only (it is not added to the APK).
Note: If you're creating an Android app module, you cannot use provided for AAR dependencies, only for JARs. In an Android library module, you can use it for both JARs and AARs.

apk配置仅将依赖项添加到APK(不会将其添加到 编译类路径).
注意:您只能将apk用于JAR二进制依赖项.它不支持库模块或AAR二进制依赖项.

apk configuration adds the dependency to the APK only (it is not added to the compilation classpath).
Note: You can use apk only for JAR binary dependencies. It does not support library modules or AAR binary dependencies.

由于我已经从sdk-api.jar中删除了anotherPublicMethod(),因此它不适用于SDK使用者:

Since I've stripped the anotherPublicMethod() from sdk-api.jar, it won't be available for SDK consumer:

我创建了一个简单的应用程序项目,该项目使用了高于SDK.

I've created a simple application project that consumes the above SDK.

这篇关于如何限制对Android库的某些API的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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