1. 程式人生 > >友盟多渠道獲取渠道名 附贈多渠道打包檔案

友盟多渠道獲取渠道名 附贈多渠道打包檔案

首次配置清單檔案<AndroidManifest.xml>

<meta-data
                android:name="UMENG_CHANNEL"
                android:value="${UMENG_CHANNEL_VALUE}"/>

這個地方注意 android:value="${UMENG_CHANNEL_VALUE}" 值的配置

要與build.gradle檔案中配置保持一致

productFlavors.all { flavor ->
        flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
    }
下面介紹程式碼獲取渠道名
/**
	 * 獲取渠道名
	 * @param context 此處習慣性的設定為activity,實際上context就可以
	 * @return 如果沒有獲取成功,那麼返回值為空
	 */
	public static String getChannelName(Context context) {
		if (context == null) {
			return null;
		}
		String channelName = null;
		try {
			PackageManager packageManager = context.getPackageManager();
			if (packageManager != null) {
				//注意此處為ApplicationInfo 而不是 ActivityInfo,因為友盟設定的meta-data是在application標籤中,而不是某activity標籤中,所以用ApplicationInfo
				ApplicationInfo applicationInfo = packageManager.
						getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
				if (applicationInfo != null) {
					if (applicationInfo.metaData != null) {
							channelName = String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL"));
					}
				}

			}
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return channelName;
	}
需要注意的地方
channelName = String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL"));
這個地方的 

1. 

UMENG_CHANNEL 這個key要與上面介紹的meta標籤的 android:name="<span style="font-family: Arial, Helvetica, sans-serif;">UMENG_CHANNEL</span>" 的值保持一致

附贈完整多渠道打包檔案

apply plugin: 'com.android.application'
// 得到當前時間的字串 用於發包的時候拼接命名
// 關於語言的實現參考 groovy def定義無型別的變數 返回值無型別的方法
def releaseTime() {
    return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC"))
}

android {
    compileSdkVersion 21
    buildToolsVersion '21.1.2'

    defaultConfig {
        applicationId "com.boohee.*"
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        
        // dex突破65535的限制
        multiDexEnabled true
    }

    lintOptions {
        abortOnError false
		// 防止在釋出的時候出現因MissingTranslation導致Build Failed!
        disable 'MissingTranslation'
	} 
	
	sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
	
	signingConfigs { 
		debug { 
			// No debug config 
		} 
		
		release { 
			storeFile file("keystore位置") 
			storePassword "keystore密碼" 
			keyAlias "keystore別名" 
			keyPassword "密碼" 
		} 
	} 
	
	buildTypes {
		debug { 
			// 顯示Log buildConfigField "boolean", "LOG_DEBUG", "true" 
			versionNameSuffix "-debug" 
			minifyEnabled false 
			zipAlignEnabled false 
			shrinkResources false 
			signingConfig signingConfigs.debug 
		} 
		release { 
			// 不顯示Log buildConfigField "boolean", "LOG_DEBUG", "false" 
			minifyEnabled true 
			zipAlignEnabled true 
			// 移除無用的resource檔案 
			shrinkResources true
			// 指定混淆檔案 前面是預設的 後面是需要自己配置的混淆檔案在關聯第三方的檔案 需要配置的混淆內容
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release

            applicationVariants.all { variant ->
                variant.outputs.each { output ->
                    def outputFile = output.outputFile
                    if (outputFile != null && outputFile.name.endsWith('.apk')) {
                    	// 輸出apk名稱為xxx_v1.0_2015-01-15_wandoujia.apk  xxx可以進行自定義
                        def fileName = "xxx_v${defaultConfig.versionName}_${releaseTime()}_${variant.productFlavors[0].name}.apk"
                        output.outputFile = new File(outputFile.parent, fileName)
                    }
                }
            }
        }
    }

    // 友盟多渠道打包
    productFlavors {
		kuaiyidian{}
		anzhuo{}
		yingyonghui{}
		baidu{}
		wandoujia{}
		-360{}
		anzhi{}
		huawei{}
		lenovo{}
		mumayi{}
		jifeng{}
		yingyongbao{}
		xiaomi{}
		yidong{}
		liantong{}
		dianxin{}
		wangyi{}
		_91{}
		meizu{}
		tf{}
	    }

    productFlavors.all { flavor ->
        flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
    }
}

dependencies {
    // 相關jar library
}


有關於jni檔案的配置 自己新增即可

附贈一份完整的混淆檔案 將下面的程式碼拷貝到  proguard-rules.pro 檔案中
#指定程式碼的壓縮級別
-optimizationpasses 5

#包明不混合大小寫
-dontusemixedcaseclassnames

#不去忽略非公共的庫類
-dontskipnonpubliclibraryclasses

#優化  不優化輸入的類檔案
-dontoptimize

#預校驗
-dontpreverify

#混淆時是否記錄日誌
-verbose

#混淆時所採用的演算法
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

#混淆後,保留原始碼及混淆後代碼對應的資訊及具體行數(umeng後臺異常可以mapping到具體的行數)
-printmapping mapping.txt
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable

#保護註解
-keepattributes *Annotation*

#保持哪些類不被混淆,Activity 、Service ... 類的 子類
-keep public class * extends android.app.Fragment
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
#如果有引用v4包可以新增下面這行
-keep public class * extends android.support.v4.app.Fragment
-keep class com.vvpinche.model.** { *; }
-keep class com.vvpinche.event.** { *; }
#忽略警告
-ignorewarning

-keep public class * extends android.view.View {
    public <init>(android.content.Context);
    public <init>(android.content.Context, android.util.AttributeSet);
    public <init>(android.content.Context, android.util.AttributeSet, int);
    public void set*(...);
}

#保持 native 方法不被混淆
-keepclasseswithmembernames class * {
    native <methods>;
}

#保持自定義控制元件類不被混淆
-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

#保持自定義控制元件類不被混淆
-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}
#保持自定義控制元件類不被混淆
-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}

#保持 Parcelable 不被混淆
-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

#保持 Serializable 不被混淆
-keepnames class * implements java.io.Serializable

#保持 Serializable 不被混淆並且enum 類也不被混淆
-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    !static !transient <fields>;
    !private <fields>;
    !private <methods>;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

#保持列舉 enum 類不被混淆 如果混淆報錯,建議直接使用上面的 -keepclassmembers class * implements java.io.Serializable即可
#-keepclassmembers enum * {
#  public static **[] values();
#  public static ** valueOf(java.lang.String);
#}

-keepclassmembers class * {
    public void *ButtonClicked(android.view.View);
}

#不混淆資源類
-keepclassmembers class **.R$* {
    public static <fields>;
}

#避免混淆泛型 如果混淆報錯建議關掉
#–keepattributes Signature

#移除log 測試了下沒有用還是建議自己定義一個開關控制是否輸出日誌
#-assumenosideeffects class android.util.Log {
#    public static boolean isLoggable(java.lang.String, int);
#    public static int v(...);
#    public static int i(...);
#    public static int w(...);
#    public static int d(...);
#    public static int e(...);
#}

#adapter也不能混淆
-keep public class * extends android.widget.Adapter {*;}

############### 一:(通用不需要修改的配置) google預設推薦不混淆的一些檔案 Activity、Service類的子類和一些公共的配置 ############


############### 二:(第三方Library)


#greenDao

-keep class de.greenrobot.dao.** {*;}

-keepclassmembers class * extends de.greenrobot.dao.AbstractDao {
     public static java.lang.String TABLENAME;
 }
-keep class **$Properties


# OrmLite uses reflection
-keep class com.j256.**
-keepclassmembers class com.j256.** { *; }
-keep enum com.j256.**
-keepclassmembers enum com.j256.** { *; }
-keep interface com.j256.**
-keepclassmembers interface com.j256.** { *; }


#友盟統計
-keepclassmembers class * {
   public <init>(org.json.JSONObject);
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keep public class com.umeng.fb.ui.ThreadView {
}

#-keep public class com.zxxk.spokentraining.migu.R$*{
#    public static final int *;
#}

#-keep public class com.umeng.fb.** { *;}


#支付寶
#-libraryjars libs/alipaysdk.jar
#-libraryjars libs/alipaysecsdk.jar
#-libraryjars libs/alipayutdid.jar
-keep class com.alipay.android.app.IAlixPay{*;}
-keep class com.alipay.android.app.IAlixPay$Stub{*;}

-keep class com.alipay.android.app.IRemoteServiceCallback{*;}
-keep class com.alipay.android.app.IRemoteServiceCallback$Stub{*;}
-keep class com.alipay.sdk.app.PayTask{ public *;}
-keep class com.alipay.sdk.app.AuthTask{ public *;}
-keep class com.alipay.mobilesecuritysdk.*
-keep class com.ut.*

#async-http請求工具
#-libraryjars libs/android-async-http-1.4.6.jar
-keep class com.loopj.android.http{*;}

#百度地圖,替換成自己所用版本的jar包
#-libraryjars libs/baidumapapi_v3_2_0.jar
#-keep class com.baidu.** { *; }
#-keep class vi.com.gdi.bgl.android.**{*;}
-dontwarn com.baidu.mapapi.**
-keep class assets.** {*; }
-keep class com.baidu.** {*; }
-keep class vi.com.gdi.bgl.** {*; }


#環信
-keep class com.easemob.** {*;}
-keep class org.jivesoftware.** {*;}
-keep class org.apache.** {*;}
-dontwarn  com.easemob.**
#2.0.9後的不需要加下面這個keep
#-keep class org.xbill.DNS.** {*;}
#另外,demo中傳送表情的時候使用到反射,需要keep ,SmileUtils,注意前面的包名,
#不要SmileUtils複製到自己的專案下,keep的時候還是寫的demo裡的包名
-keep class com.easemob.chatuidemo.utils.SmileUtils {*;}
#2.0.9後加入語音通話功能,如需使用此功能的api,加入以下keep
-dontwarn ch.imvs.**
-dontwarn org.slf4j.**
-keep class org.ice4j.** {*;}
-keep class net.java.sip.** {*;}
-keep class org.webrtc.voiceengine.** {*;}
-keep class org.bitlet.** {*;}
-keep class org.slf4j.** {*;}
-keep class ch.imvs.** {*;}
-keep class com.vvpinche.chat.util.** {*;}

#eventbus
#-keep class de.greenrobot.event.** { *;}
#-keep class de.greenrobot.event.util.** { *; }
#-keep class de.greenrobot.dao.** { *;}
#-keep class de.greenrobot.dao.async.** { *;}
#-keep class de.greenrobot.dao.identityscope.** { *;}
#-keep class de.greenrobot.dao.internal.** { *;}
#-keep class de.greenrobot.dao.query.** { *;}

#eventbus
-keepclassmembers class ** {
    public void onEvent*(**);
}

# Only required if you use AsyncExecutor
-keepclassmembers class * extends de.greenrobot.event.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}

#gson
#-libraryjars libs/gson-2.3.jar
-keepattributes Signature
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }

#極光推送
-dontwarn cn.jpush.**
-keep class cn.jpush.** { *; }

#七牛雲端儲存
-dontwarn com.qiniu.android.**
-keep class com.qiniu.android.** { *; }

#百度支付
-dontwarn com.baidu.mtjstatsdk.**
-keep class com.baidu.mtjstatsdk.** { *; }

-dontwarn com.baidu.android.pay.**
-keep class com.baidu.android.pay.** { *; }


#shareSDK分享
-dontwarn cn.sharesdk.**
-dontwarn **.R$*
-keep class cn.sharesdk.**{*;}
-keep class com.sina.**{*;}
-keep class **.R$* {*;}
-keep class **.R{*;}

-dontwarn com.nostra13.universalimageloader.**
-keep class com.nostra13.universalimageloader.** { *; }

-dontwarn net.sf.antcontrib.**
-keep class net.sf.antcontrib.** { *; }

-dontwarn com.tencent.mm.**
-keep class com.tencent.mm.** { *; }

-dontwarn com.marsor.common.**
-keep class com.marsor.common.** { *; }

-dontwarn m.framework.**
-keep class m.framework.** { *; }

-dontwarn com.nineoldandroids.**
-keep class com.nineoldandroids.** { *; }

-dontwarn uk.co.senab.photoview.**
-keep class uk.co.senab.photoview.** { *; }

-dontwarn com.squareup.picasso.**
-keep class com.squareup.picasso.** { *; }