1. 程式人生 > >android獲取友盟渠道名以及獲取application中的meta-data

android獲取友盟渠道名以及獲取application中的meta-data

獲取友盟渠道名

/**
     * 獲取渠道名
     * @param ctx 此處習慣性的設定為activity,實際上context就可以
     * @return 如果沒有獲取成功,那麼返回值為空
     */
    public static String getChannelName(Activity ctx) {
        if (ctx == null) {
            return null;
        }
        String channelName = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                //注意此處為ApplicationInfo 而不是 ActivityInfo,因為友盟設定的meta-data是在application標籤中,而不是某activity標籤中,所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
<span style="white-space:pre">			</span>//key換成說需要的key
                        channelName = applicationInfo.metaData.getString(key);
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelName;
    }

提取為通用方法:
  /**
     * 獲取application中指定的meta-data
     * @return 如果沒有獲取成功(沒有對應值,或者異常),則返回值為空
     */
    public static String getAppMetaData(Context ctx, String key) {
        if (ctx == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(key);
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData;
    }