美文网首页
Gradle 之常用配置(六)

Gradle 之常用配置(六)

作者: PuHJ | 来源:发表于2019-04-12 10:10 被阅读0次

    一、resValue

    在不同的模式下,生成不同的资源XML。这相当于在res / values中指定资源。这样可以在不同的版本环境下,有不同的资源值。

    下面是resValue的方法:

        /**
         * Adds a new generated resource.
         *
         * <p>This is equivalent to specifying a resource in res/values.
         *
         * <p>See <a href="http://developer.android.com/guide/topics/resources/available-resources.html">Resource Types</a>.
         *
         * @param type the type of the resource
         * @param name the name of the resource
         * @param value the value of the resource
         */
        public void resValue(
                @NonNull String type,
                @NonNull String name,
                @NonNull String value) {
            ClassField alreadyPresent = getResValues().get(name);
            if (alreadyPresent != null) {
                String message =
                        String.format(
                                "BuildType(%s): resValue '%s' value is being replaced: %s -> %s",
                                getName(), name, alreadyPresent.getValue(), value);
                errorReporter.handleSyncWarning(null, SyncIssue.TYPE_GENERIC, message);
            }
            addResValue(new ClassFieldImpl(type, name, value));
        }
    

    从源码中可以看到,resValue中需要三个参数,他们分别是如下意思:

    • type : 表示资源的类型,可配置以下:
      | format | 描述 | 例子|
      | ------------- |:-------------:|:-------------:|
      |reference|某一个资源的引用|<attr name = "background" format = "reference" />使用 :android:background = "@drawable/back"|
      |color|颜色值|<attr name = "textColor" format = "color" />|
      |boolean|布尔值|<attr name = "focusable" format = "boolean" />|
      |dimension|尺寸大小|<attr name = "layout_width" format = "dimension" /> 使用 : android:layout_width = "1dp"|
      |float|浮点值| |
      |integer|整型||
      |string|字符串||
      |fraction|百分数|<attr name = "pivotX" format = "fraction" /> 使用 : android:pivotX = "200%"|
      |enum|枚举值| <attr name="orientation"> <enum name="horizontal" value="0" /> <enum name="vertical" value="1" /> </attr> |
      |flag|按位或| <attr name="windowSoftInputMode"> <flag name = "stateUnspecified" value = "0" /> </attr>|
    • name : 表示资源名称
    • value : 表示资源的值

    例子:

        buildTypes {
            debug {
                resValue "integer", "AppName", "0x23"
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    

    在这里设置了一个integer型的资源,相应的在build/generated/res/resValues/debug/values该目录下有个generated.xml文件。

    内容:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <!-- Automatically generated file. DO NOT MODIFY -->
    
        <!-- Values from build type: debug -->
        <integer name="AppName">0x23</integer>
    
    </resources>
    

    对该资源的引用和android中设置的一致。

    二、buildConfigField

    在BuildConfig文件生成对应的静态变量,可以根据该静态变量决定当前采用何种模式。

    如:系统提供的public static final boolean DEBUG = Boolean.parseBoolean("true");

    可通过BuildConfig.DEBUG 来判断当前是否是debug模式,这样就可以在debug代码中做些定制的任务。最常见的debug下log模式.

       /**
         * Adds a new field to the generated BuildConfig class.
         *
         * <p>The field is generated as: {@code <type> <name> = <value>;}
         *
         * <p>This means each of these must have valid Java content. If the type is a String, then the
         * value should include quotes.
         *
         * @param type the type of the field
         * @param name the name of the field
         * @param value the value of the field
         */
        public void buildConfigField(
                @NonNull String type,
                @NonNull String name,
                @NonNull String value) {
            ClassField alreadyPresent = getBuildConfigFields().get(name);
            if (alreadyPresent != null) {
                String message =
                        String.format(
                                "BuildType(%s): buildConfigField '%s' value is being replaced: %s -> %s",
                                getName(), name, alreadyPresent.getValue(), value);
                errorReporter.handleSyncWarning(null, SyncIssue.TYPE_GENERIC, message);
            }
            addBuildConfigField(new ClassFieldImpl(type, name, value));
        }
    

    除了系统提供的默认的键值对以外,用户还可以自定义增加相应的键值对。

    用法:

        buildTypes {
            debug {
                buildConfigField "int", "CUSTOM_VERSION", "0"
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    

    这样在debug模式下,当前module下面就会有对应的数值。

    public final class BuildConfig {
      public static final boolean DEBUG = Boolean.parseBoolean("true");
      public static final String APPLICATION_ID = "com.szyd.myapplication";
      public static final String BUILD_TYPE = "debug";
      public static final String FLAVOR = "";
      public static final int VERSION_CODE = 1;
      public static final String VERSION_NAME = "1.0";
      // Fields from build type: debug
      public static final int CUSTOM_VERSION = 0;
    }
    

    三、manifestPlaceholders和meta-data

    manifestPlaceholders中文是占位符,在build脚本中设置相应的键值对,在AndroidManifest.xml中的meta-data中引用key。所以meta-data中的value在不同的模式下,value不一样。

    1)、编写build中manifestPlaceholders

    manifestPlaceholders的方法如下,可以看到参数接收的是Map对象。

        /**
         * Sets a new set of manifest placeholders.
         *
         * <p>See <a href="https://developer.android.com/studio/build/manifest-build-variables.html">
         *     Inject Build Variables into the Manifest</a>.
         */
        public void setManifestPlaceholders(@NonNull Map<String, Object> manifestPlaceholders) {
            mManifestPlaceholders.clear();
            this.mManifestPlaceholders.putAll(manifestPlaceholders);
        }
    

    所以第一步设置不同的manifestPlaceholders值:在debug和release两个模式下同一个key设置了不同的值。

        buildTypes {
            debug {
                manifestPlaceholders = [key: "value1"]
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
            release {
                manifestPlaceholders = [key: "value2"]
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
    
        }
    

    2)、AndroidManifest.xml中设置meta-data

    meta-data中标签可在Application、Activity等下面设置,意味着meta-data标签是附属在该对象下。

    如下:在Activity中设置了meta-data

        <application
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme"
            tools:ignore="GoogleAppIndexingWarning">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
    
                <meta-data android:name="myValue"
                    android:resource="12"
                    android:value="headword${key}append_word"/>
            </activity>
    
    
        </application>
    

    通过${key}来获取到当前模式下的值,name意味着唯一的id,最终通过name来访问。

    先看meta-data下可以设置哪些内容:

    • android:name : 相当于meta-data的id,外界通过该name访问
    • android:resource : meta-data的资源,类型为int
    • android:value : meta-data中存储的值

    3)、代码使用

    因为meta-data中在Activity设置的,所以生成的是ActivityInfo。

            ActivityInfo activityInfo = null;
            try {
                activityInfo = getPackageManager().getActivityInfo(MainActivity.this.getComponentName(), PackageManager.GET_META_DATA);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (activityInfo == null || activityInfo.metaData == null)
                return;
            String value = activityInfo.metaData.getString("myValue");
            int resource = activityInfo.metaData.getInt("myValue");
    

    源码中activityInfo.metaData是Bundle类对象。android:value是String类型,android:resource作为资源便是int类型的资源id。

    相关文章

      网友评论

          本文标题:Gradle 之常用配置(六)

          本文链接:https://www.haomeiwen.com/subject/tenpiqtx.html