2019-03-30 Android Gradle manifestPlaceholders自定义变量取值

前言

最近写了一个坑爹的方便其他方集成的微信,支付宝分享SDK,其中的appid等参数,本人使用的配置化,就遇到了在Gradle manifestPlaceholders自定义变量取值问题

一.声明变量值

申明变量的原理

看过源码,其实就是一个HashMap的对象,我们在build.gradle中写入,然后映射到AndroidMainfest.xml中,HashMap对象放置在activityInfo.metaData中,我们可以通过activityInfo.metaData.keyset()查看所有设置的值

首先了解,在build.gradle中如何添加变量可以写在如下的位置:

第一种:

defaultConfig {

        applicationId "xxx.xxxxxx.xxxxxx"

        minSdkVersion 20

        targetSdkVersion 18

        versionCode 1

        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        manifestPlaceholders = [

                "WEATCH_APPID": "--------------",

        ]

    }

    buildTypes {

        debug {

            signingConfig signingConfigs.debug

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'

            manifestPlaceholders = [

                    "WEATCH_APPID": "--------------",

            ]

        }

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }

    }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

第二种:

compileSdkVersion 18

    buildToolsVersion '27.0.2'

    defaultConfig {

        applicationId "xxx.xxxxx.xxxxx"

        minSdkVersion 20

        targetSdkVersion 18

        versionCode 1

        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        manifestPlaceholders = [

                "WEATCH_APPID": "dddddddd",

        ]

    }

1

2

3

4

5

6

7

8

9

10

11

12

13

第三种:

  compileSdkVersion 18

    buildToolsVersion '27.0.2'

    defaultConfig {

        applicationId "xxx.xxxxxx.xxxxxxx"

        minSdkVersion 20

        targetSdkVersion 18

        versionCode 1

        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        productFlavors {

            google {

                manifestPlaceholders.put("UMENG_CHANNEL","google")

            }

            baidu {

                manifestPlaceholders.put("UMENG_CHANNEL","baidu")

            }

        }

    }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

二.AndroidMainfest.xml中使用

第一种:直接使用

比如极光receiver

<receiver

            android:name=".jpush.MyReceiver"

            android:enabled="true">

            <intent-filter>

                <!--Required 用户注册SDK的intent-->

                <action android:name="cn.jpush.android.intent.REGISTRATION" />

                <!--Required 用户接收SDK消息的intent-->

                <action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" />

                <!--Required 用户接收SDK通知栏信息的intent-->

                <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" />

                <!--Required 用户打开自定义通知栏的intent-->

                <action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" />

                <!-- 接收网络变化 连接/断开 since 1.6.3 -->

                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

                <!--<action android:name="cn.jpush.android.intent.CONNECTION" />-->

                <category android:name="${JPUSH_PKGNAME}" />

            </intent-filter>

        </receiver>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

比如微信支付

        <!-- 支付回调页面 -->

        <activity

            android:name=".wxapi.WXPayEntryActivity"

            android:exported="true"

            android:launchMode="singleTop">

            <intent-filter>

                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:scheme="${WEATCH_APPID}" />

            </intent-filter>

        </activity>

1

2

3

4

5

6

7

8

9

10

11

三.在Java类中获取[在service,receiver,Activity,Application中获取值]

原理:通过androidMainfest.xml把值反射到对应类标签,设置value的key值,在java类中通过key取值得到value

第一种:Activity类中获取build.gradle申明变量

AndroidMainfest.xml中代码

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="xxx.xxxx.xxxxx">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".PayTestActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

          <meta-data android:name="test" android:value="${WEATCH_APPID}"/>//这一句起到至关重要作用

        </activity>

    </application>

</manifest>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Activity中代码

import android.app.Activity;

import android.content.pm.ActivityInfo;

import android.content.pm.PackageManager;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import com.reach.doooly.utils.StringUtlis;

import com.reachdoooly.pay.utils.ReachLogs;

/**

* Created by Albert on 2018/5/22.

*/

public class PayTestActivity extends Activity {

    private Button ali_pay;//阿里支付

    private Button weachat_pay;//微信支付

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate ( savedInstanceState );

        setContentView ( R.layout.pay_test );

        ActivityInfo activityInfo = null;

        String value ="";

        try {

            activityInfo = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);

            value=activityInfo.metaData.getString("test");

        } catch (PackageManager.NameNotFoundException e) {

        }

        if(!StringUtlis.isEmpty ( value )){

            ReachLogs.e ("fuqinming","appId:"+value);

        }

        weachat_pay = (Button) findViewById ( R.id.wechat_pay );

        weachat_pay.setOnClickListener ( new View.OnClickListener () {

            @Override

            public void onClick(View v) {

              //new NewClass().createNewPay(PayTestActivity.this);

              // Toast.makeText ( PayTestActivity.this, PayUtils.getAppPackageName ( PayTestActivity.this ), Toast.LENGTH_SHORT ).show ();

            }

        } );

    }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

第二种:Application类中获取build.gradle申明变量

AndroidMainfest.xml中代码

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="xxx.xxxx.xxxxx">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".PayTestActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

        <meta-data android:name="test" android:value="${WEATCH_APPID}"/>//这一句起到至关重要作用

    </application>

</manifest>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

在Application中代码

    private void getWeatchAppID(){

          String value ="";

          try {       

              ApplicationInfo applicationInfo=getPackageManager().getApplicationInfo(getPackageName(),PackageManager.GET_META_DATA);

              value=applicationInfo.metaData.getString("test");

          } catch(Exception e) {

            value="";

          }

      }

1

2

3

4

5

6

7

8

9

第三种:在SERVICE,RECEIVER中获取

这两种基本上差不多就不分开写了,就只写一种,另外一种赵淼画瓢即可。

在AndroidMainfest.xml中代码

<receiver

            android:name=".jpush.MyReceiver"

            android:enabled="true">

            <intent-filter>

                <!--Required 用户注册SDK的intent-->

                <action android:name="cn.jpush.android.intent.REGISTRATION" />

                <!--Required 用户接收SDK消息的intent-->

                <action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" />

                <!--Required 用户接收SDK通知栏信息的intent-->

                <action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" />

                <!--Required 用户打开自定义通知栏的intent-->

                <action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" />

                <!-- 接收网络变化 连接/断开 since 1.6.3 -->

                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

                <!--<action android:name="cn.jpush.android.intent.CONNECTION" />-->

                <category android:name="${JPUSH_PKGNAME}" />

            </intent-filter>

            <meta-data android:name="test" android:value="${WEATCH_APPID}"/>//这一句起到至关重要作用

        </receiver>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

在receiver类中代码

    private void getWeatchAppID(){

          String value ="";

          try {       

              ApplicationInfo applicationInfo=activity.getPackageManager().getServiceInfo(ComponentName,PackageManager.GET_META_DATA);

              ApplicationInfo applicationInfo=activity.getPackageManager().getReceiverInfo(ComponentName,PackageManager.GET_META_DATA);

              //只有这里不同,亲们注意哈getReceiverInfo,getServiceInfo

              value=applicationInfo.metaData.getString("test");

          } catch(Exception e) {

            value="";

          }

      }

1

2

3

4

5

6

7

8

9

10

11

4.特别需要注意

因为在我的项目中,是在core包中写入appID与appSercert等信息,就需要特别注意,我的代码是在core包中有一个父Activity,如何在父activity中获取appid,需要特别注意

import android.app.Activity;

import android.content.pm.ApplicationInfo;

import android.content.pm.PackageManager;

import android.widget.Toast;

import com.tencent.mm.opensdk.modelbase.BaseReq;

import com.tencent.mm.opensdk.modelbase.BaseResp;

import com.tencent.mm.opensdk.modelpay.PayReq;

import com.tencent.mm.opensdk.openapi.IWXAPI;

import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**

* 微信支付base类

*/

public class WeatchPayBaseActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;

    private PayReq payReq;//微信支付

    public void initWXAPI(Activity context) {

        String APP_ID ="";

        ReachLogs.e ("fuqinming","packagename:"+getPackageName ());

        -----第一种写法----

        try {

            ApplicationInfo activityInfo =this.getPackageManager().getApplicationInfo(this.getPackageName (), PackageManager.GET_META_DATA);

            APP_ID=activityInfo.metaData.getString("WEATCG_APPID");

        } catch (Exception e) {

        }

        if(null == APP_ID || "".equals ( APP_ID.trim () ) || "null".equals ( APP_ID.trim () )){

            ReachLogs.e ("fuqinming","appId:");

        }else{

            ReachLogs.e ("fuqinming","appId:"+APP_ID);

        }

        ----第二种写法----

        try {

            ApplicationInfo appInfo = getPackageManager ().getApplicationInfo ( getPackageName (),

                            PackageManager.GET_META_DATA );

            APP_ID=appInfo.metaData.getString("WEATCH_APPID");

        }catch (Exception e){

        }

        ReachLogs.e ("fuqinming","APP_ID:"+APP_ID);

        payReq = new PayReq ();

        if (null == APP_ID || "".equals ( APP_ID.trim () ) || "null".equals ( APP_ID.trim () )) {

            throw new NullPointerException ();

        }

        // 初始化分享

        api = WXAPIFactory.createWXAPI ( context, APP_ID, true );

        api.handleIntent ( context.getIntent (), this );

        api.registerApp ( APP_ID );

    }

    @Override

    public void onReq(BaseReq baseReq) {

    }

    /***

    * 微信支付[NATIVIE TO HTML]

    *

    * @param weachPayVo

    * @add 2017-10-10

    */

    public void wechatPay(WeachPayBeanVo weachPayVo) {

        if(payReq==null){

            throw new NullPointerException ("payReq The object is not set");

        }

        if (payReq != null && weachPayVo != null && !WeacthConsts.isEmpty(weachPayVo.getAppid()) && !WeacthConsts.isEmpty(weachPayVo.getNoncestr())

                && !WeacthConsts.isEmpty(weachPayVo.getPackageValue()) && !WeacthConsts.isEmpty(weachPayVo.getPartnerid())

                && !WeacthConsts.isEmpty(weachPayVo.getPrepayid()) && !WeacthConsts.isEmpty(weachPayVo.getSign())

                && !WeacthConsts.isEmpty(weachPayVo.getTimestamp())) {

            payReq.appId = weachPayVo.getAppid();

            payReq.partnerId = weachPayVo.getPartnerid();// 微信支付分配的商户号

            payReq.prepayId = weachPayVo.getPrepayid();// 微信返回的支付交易会话ID

            payReq.packageValue = weachPayVo.getPackageValue();// 扩展字段占时填固定

            payReq.nonceStr = weachPayVo.getNoncestr();// 随机字符串

            payReq.timeStamp = weachPayVo.getTimestamp();// 时间戳

            payReq.sign = weachPayVo.getSign();// 签名

            api.sendReq(payReq);

        } else {

            Toast.makeText (this,getString(R.string.error_order_msg),Toast.LENGTH_SHORT);

        }

    }

    // 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法

    public void onResp(BaseResp resp) {

    }

}

---------------------

作者:CherryChen88

来源:CSDN

原文:https://blog.csdn.net/ONLYMETAGAIN/article/details/80497789

版权声明:本文为博主原创文章,转载请附上博文链接!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,857评论 0 17
  • 本文重点介绍应用程序的启动过程,应用程序的启动过程实际上就是应用程序中的默认Activity的启动过程,本文将详细...
    天宇sonny阅读 3,126评论 1 0
  • ¥开启¥ 【加群QQ聊天源码】 〖2017-08-25 15:24:36〗 《import "android.ne...
    小菜c阅读 9,755评论 0 5
  • 1 进程启动过程 Android应用程序框架层创建的应用程序进程具有两个特点,一是进程的入口函数是Activit...
    Kevin_Junbaozi阅读 9,432评论 0 23
  • 这组照片是我非常喜欢的 很多人都说婚纱照在婚礼上用过一次就压箱底了 但是我们拍摄婚纱照的原意是让这份幸福的记录永远...
    Sunshine六姐阅读 1,693评论 0 1

友情链接更多精彩内容