我的第一个SDK

来源:互联网 发布:c语言入门小程序 编辑:程序博客网 时间:2024/05/21 19:45

一,创建Module编写代码

1,右击项目,选择module


2,选择类型


3,填写包名等信息,finish完成


4,编写MyActivity及布局文件,导入资源

MyActivity:

public class MyActivity extends AppCompatActivity {    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(MResource.getIdByName(this, "layout", "activity_my"));        ImageView imageView = (ImageView) this.findViewById(MResource.getIdByName(this, "id", "iv_change"));        if (imageView != null) {            imageView.setImageResource(MResource.getIdByName(this, "drawable", "flower"));        }    }}
activity_my布局:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="match_parent">    <ImageView        android:layout_width="wrap_content"        android:layout_height="0dp"        android:layout_weight="1"        android:src="@drawable/rabbit"/>    <ImageView        android:id="@+id/iv_change"        android:layout_width="wrap_content"        android:layout_height="0dp"        android:layout_weight="1"        android:src="@drawable/road"/></LinearLayout>
MResource类(通过反射引用资源文件,因为打包时无法将资源文件打包进去,所以需要用这个类来引用资源文件)

public class MResource {    public static int getIdByName(Context context, String className, String resName) {        String packageName = context.getPackageName();        int id = 0;        try {            Class r = Class.forName(packageName + ".R");            Class[] classes = r.getClasses();            Class desireClass = null;            for (Class cls : classes) {                if (cls.getName().split("\\$")[1].equals(className)) {                    desireClass = cls;                    break;                }            }            if (desireClass != null) {                id = desireClass.getField(resName).getInt(desireClass);            }        } catch (Exception e) {            e.printStackTrace();        }        return id;    }}
二,混淆并打包成jar

1,配置library的build.gradle文件,修改以下地方:

将minifyEnabled false 修改成true

buildTypes {        release {            minifyEnabled true            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        }    }
2,打包jar配置

dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {        exclude group: 'com.android.support', module: 'support-annotations'    })    compile 'com.android.support:appcompat-v7:23.4.0'    testCompile 'junit:junit:4.12'}//打jar包配置task makeJar(type: Copy) {    delete 'build/libs/mysdk.jar'    from('build/intermediates/bundles/release/')    into('build/libs/')    include('classes.jar')    rename ('classes.jar', 'mysdk.jar')}makeJar.dependsOn(build)

3,添加混淆

# Add project specific ProGuard rules here.# By default, the flags in this file are appended to flags specified# in C:\Users\senyoung\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt# You can edit the include path and order by changing the proguardFiles# directive in build.gradle.## For more details, see#   http://developer.android.com/guide/developing/tools/proguard.html# Add any project specific keep options here:# If your project uses WebView with JS, uncomment the following# and specify the fully qualified class name to the JavaScript interface# class:#-keepclassmembers class fqcn.of.javascript.interface.for.webview {#   public *;#}# 代码混淆压缩比,在0~7之间,默认为5,一般不做修改-optimizationpasses 5# 混合时不使用大小写混合,混合后的类名为小写-dontusemixedcaseclassnames# 指定不去忽略非公共库的类-dontskipnonpubliclibraryclasses# 这句话能够使我们的项目混淆后产生映射文件# 包含有类名->混淆后类名的映射关系-verbose# 指定不去忽略非公共库的类成员-dontskipnonpubliclibraryclassmembers# 不做预校验,preverify是proguard的四个步骤之一,Android不需要preverify,去掉这一步能够加快混淆速度。-dontpreverify# 保留Annotation不混淆-keepattributes *Annotation*,InnerClasses# 避免混淆泛型-keepattributes Signature# 抛出异常时保留代码行号-keepattributes SourceFile,LineNumberTable# 指定混淆是采用的算法,后面的参数是一个过滤器# 这个过滤器是谷歌推荐的算法,一般不做更改-optimizations !code/simplification/cast,!field/*,!class/merging/*############################################### Android开发中一些需要保留的公共部分############################################### 保留我们使用的四大组件,自定义的Application等等这些类不被混淆# 因为这些子类都有可能被外部调用-keep public class * extends android.app.Activity-keep public class * extends android.app.Appliction-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 * extends android.view.View-keep public class com.android.vending.licensing.ILicensingService# 保留support下的所有类及其内部类-keep class android.support.** {*;}# 保留继承的-keep public class * extends android.support.v4.**-keep public class * extends android.support.v7.**-keep public class * extends android.support.annotation.**# 保留R下面的资源-keep class **.R$* {*;}# 保留本地native方法不被混淆-keepclasseswithmembernames class * {    native <methods>;}# 保留在Activity中的方法参数是view的方法,# 这样以来我们在layout中写的onClick就不会被影响-keepclassmembers class * extends android.app.Activity{    public void *(android.view.View);}# 保留枚举类不被混淆-keepclassmembers enum * {    public static **[] values();    public static ** valueOf(java.lang.String);}# 保留我们自定义控件(继承自View)不被混淆-keep public class * extends android.view.View{    *** get*();    void set*(***);    public <init>(android.content.Context);    public <init>(android.content.Context, android.util.AttributeSet);    public <init>(android.content.Context, android.util.AttributeSet, int);}# 保留Parcelable序列化类不被混淆-keep class * implements android.os.Parcelable {    public static final android.os.Parcelable$Creator *;}# 保留Serializable序列化的类不被混淆-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();}# 对于带有回调函数的onXXEvent、**On*Listener的,不能被混淆-keepclassmembers class * {    void *(**On*Event);    void *(**On*Listener);}# webView处理,项目中没有使用到webView忽略即可-keepclassmembers class fqcn.of.javascript.interface.for.webview {    public *;}-keepclassmembers class * extends android.webkit.webViewClient {    public void *(android.webkit.WebView, java.lang.String, android.graphics.Bitmap);    public boolean *(android.webkit.WebView, java.lang.String);}-keepclassmembers class * extends android.webkit.webViewClient {    public void *(android.webkit.webView, jav.lang.String);}# support-v7-appcompat-keep public class android.support.v7.widget.** { *; }-keep public class android.support.v7.internal.widget.** { *; }-keep public class android.support.v7.internal.view.menu.** { *; }-keep public class * extends android.support.v4.view.ActionProvider {    public <init>(android.content.Context);}#自定义的类混淆--------------------------------------------------------------------------------------keep class com.wesdom.trial.entity.** { *; } #实体类不参与混淆-keep class com.wesdom.trial.dialog.** { *; } #自定义控件不参与混淆-keep class com.wesdom.trial.view.** { *; } #自定义控件不参与混淆# 保持 Parcelable 不被混淆-keep class * implements android.os.Parcelable {  public static final android.os.Parcelable$Creator *;}#自定义的类混淆-------------------------------------------------------------------------------------#support.v4#-libraryjars libs/android-support-v4.jar-keep class android.support.v4.** { *; }-dontwarn android.support.v4.**

4,打包

(1)打包方式1:在AS的Terminal控制台中输入该命令回车:gradlew makeJar


打包完成,并且能看到打出来的jar包


(2),打包方式2:直接在gradle projects中操作

选择mylibrary->other


找到makeJar,双击该选项就开始打包


打包成功:


三,添加用项目中:

将打出来的mysdk.jar添加到项目中,并将要用的资源文件复制到项目的res中,在项目中调用jar包的方法,并且还需要在AndroidManifest.xml中注册调用的Activity


运行效果:

   

github项目地址:https://github.com/kuyue/MyFirstSDK#myfirstsdk

参考文章:

Android Studio 如何打JAR包并解决资源使用问题


0 0
原创粉丝点击