Gradle obfuscation + package Jar package basics, gradle obfuscation package jar
This article is an original article. For more information, see the source.
The source code will be included at the end of the article. If you need it, you can download it.
Generally, we need to write Android apps with the following requirements: (1) code obfuscation; (2) Modularization; (3) provide JAR packages to third parties. The following sections will be introduced to users who are new to Android or who are new to Android Studio (.
Quote:
(1) AS uses the Gradle build tool to easily configure our apps, such AS versions, support for the lowest API level, code obfuscation files, and third-party libraries, for more information about the syntax, see other friends' articles.
(2) AS provides module programming, so that we can stratify and clarify the APP architecture. For personal recommendations, refer to the next article.
Instance body:
This example is only used for demonstration. The focus is on code obfuscation and JAR packaging. Therefore, the functions are simplified and a lot of logic code is omitted.
Basic Requirement: accept the user's login request, simulate the completion of the login request to the server, and prompt the login result.
1. Create a project
Project directory structure:
In my personal habits, each module is created as a level. The module (android library) Description:
App: User Module, user interaction interface, user resources, and other models: entity module player: core business module utils: auxiliary class module.
Tip: when creating a module, note that the module type is Android Library. Otherwise, some functions will be affected.
Ii. Coding
(1) model Module
User Logon Information entity:
1 package xiaoshubao. model; 2 3/** 4 * Author: schoolbag 5 * Date: 2016/6/16 6 * version: V1.0 7 * Description: 8 */9 public class UserModel {10 String userName; 11 String pwd; 12 13 public void setUserName (String userName) {14 this. userName = userName; 15} 16 17 public void setPwd (String pwd) {18 this. pwd = pwd; 19} 20 21 public String getUserName () {22 return userName; 23} 24 25 public String getPwd () {26 return pwd; 27} 28}View Code
Other entities do not post code. The final code structure of the model layer is as follows:
HttpMsgCallback: http callback request Interface
Parent: Non-Practical Class, required for code obfuscation
UserLoginCallback: User Logon result callback Interface
(2) utils module:
Network Access helper class (HttpUtils ):
1 package xiaoshubao. utils; 2 3 import java. util. hashMap; 4 import java. util. map; 5 6 import xiaoshubao. model. httpMsgCallback; 7 import xiaoshubao. model. parent; 8 9/** 10 * Author: schoolbag 11 * Date: 2015/12/1812 * version: V1.013 * description: http Communication with the server 14 */15 public class HttpUtils implements Parent {16 private static final String TAG = "HttpUtils "; 17 18/*** send a Post request to the server HTTP20 * 21 * @ param strUrlPath server address 22 * @ param params Request body parameter 23 * @ return Error Code 24 */25 private static string httpPostData (String strUrlPath, map <String, String> params) {26 27 return "true "; 28} 29 30/** 31 * Send a registration message to the http server 32 * @ param serverUrl server address 33 * @ param params Request body parameter 34 * @ param httpMsgCallback execution result callback 35*/36 public static void sendPostMsgToServer (final String serverUrl, final HashMap params, final HttpMsgCallback httpMsgCallback) {37 Thread thread = new Thread (new Runnable () {38 @ Override39 public void run () {40 try {41 Thread. sleep (2*1000); // simulate sending network request 42} catch (InterruptedException e) {43 e. printStackTrace (); 44} 45 String result = HttpUtils. httpPostData (serverUrl, params); 46 httpMsgCallback. httpPostCallBack (result); 47} 48}); 49 thread. start (); 50} 51}View Code
(3) player Module
UserLogin class (User Logon Service class ):
1 package xiaoshubao. player; 2 3 import java. util. hashMap; 4 5 import xiaoshubao. model. httpMsgCallback; 6 import xiaoshubao. model. parent; 7 import xiaoshubao. model. userLoginCallback; 8 import xiaoshubao. model. userModel; 9 import xiaoshubao. utils. httpUtils; 10 11/** 12 * Author: schoolbag 13 * Date: 2016/6/1614 * version: V1.015 * Description: 16 */17 public class UserLogin implements Parent {18 UserLoginCallback userLoginCallb Ack; 19 public UserLogin (UserLoginCallback userLoginCallback) {20 this. userLoginCallback = userLoginCallback; 21} 22 23/** 24 * user Logon 25 * @ param user information 26 */27 public void login (UserModel user) {28 userLogin (user ); 29} 30 private void userLogin (UserModel user) {31 HashMap hashMap = new HashMap (); 32 hashMap. put ("userName", user. getUserName (); 33 hashMap. put ("pwd", user. getPwd (); 34 HttpUtils. sendPostMsgToServ Er ("XXXXX", hashMap, httpMsgCallback); 35} 36 HttpMsgCallback httpMsgCallback = new HttpMsgCallback () {37 @ Override38 public void httpPostCallBack (String json) {39 if (json. contains ("true") & null! = UserLoginCallback) {40 userLoginCallback. loginResult (true); 41} else if (null! = UserLoginCallback) {42 userLoginCallback. loginResult (false); 43} 44} 45}; 46 private void fun1 () {} 47 private void fun2 () {} 48}View Code
3. code obfuscation
For code obfuscation in AS, you need to set it in the build. gradle file and the proguard-rules.pro file (you can use the jd-gui tool to compare the effects before and after obfuscation ):
(1) build. gradle File
MinifyEnabled: Indicates whether to enable obfuscation. The default value is false.
ProguardFiles: obfuscated configuration files, typically using the default proguard-rules.pro file in the project.
(2) proguard-rules.pro documents
For details about obfuscation settings, refer to the progurad official website.
Pay attention to the red box in the figure, because all jar packages require external interfaces (modules without external interfaces generally do not make sense), there are multiple ways to set external interface classes:
A:-keep public class *, for example:
-Keep public class *{
Public protected *;
}
B :.
A module generally has many class files. When obfuscation, we hope that the class names of all the class files except for the external interface classes will also be confused. Then we can create a separate base class or interface, let the external interface class inherit the base class or interface.
C:-keep public class XXX. The specific classes are not obfuscated. For example:
-Keep public class xiaoshubao. player. UserLogin {
Public protected *;
}
4. Package a jar package
1) proguard-rules.pro Configuration
Configure the basic attributes for generating the JAR package as follows:
The above code is simple and will not be described.
(2) generate a JAR package
Switch to the current project directory in the CMD command line and execute the gradlew makeJar command.
A jar package is generated successfully. If it is generated for the first time using gradlew, it may take about a few minutes to update the package online.
If an error occurs during configuration or class reference, the CMD window will prompt you to modify the configuration according to the error message.
(3) Merge JAR packages
The gradlew makeJar command will generate the JAR packages of these three modules in the directories of model, uitls, and palyer. If we need to provide sdks to third parties, the Three JAR packages may be inconvenient, so there is a need to merge into a JAR package.
We know that the JAR package is actually a common compressed package. Therefore, after extracting the Three JAR packages, the file is as follows:
Note: The META-INF configuration file, which obfuscated the palyer and utils modules while the model module is not obfuscated (or can be obfuscated by configuration), so only one META-INF file is generated, if multiple modules are not obfuscated and multiple META-INF files are generated, the JAR package merging using this method will cause problems.
The directory file in the xiaoshubao folder is as follows:
Compress the META-INF and xiaoshubao files together to generate a zip file and rename it as a. jar file. The result is as follows:
V. Third-party use
Import the MyUserManager. jar package to the test project (non-JAR package source code project) as follows:
Tip: sometimes there is no downward triangle symbol in front of the JAR package, you cannot open the JAR package to view the class files in it, and an error will be reported when you use the class in the JAR package, restart the project, as shown in.
(1) logon interface:
(2) logon code:
1 package xiaoshubao. jartest; 2 3 import android. content. context; 4 import android. OS. bundle; 5 import android. OS. message; 6 import android. support. v7.app. appCompatActivity; 7 import android. view. view; 8 import android. widget. editText; 9 import android. widget. toast; 10 11 import xiaoshubao. model. userLoginCallback; 12 import xiaoshubao. model. userModel; 13 import xiaoshubao. player. userLogin; 14 15 public Class MainActivity extends AppCompatActivity {16 Context context; 17 MyHandler handler; 18 @ Override19 protected void onCreate (Bundle savedInstanceState) {20 super. onCreate (savedInstanceState); 21 setContentView (R. layout. activity_main); 22 context = this; 23 handler = new MyHandler (); 24} 25 public void btn_loginClick (View v) {26 UserLogin userLogin = new UserLogin (userLoginCallback); 27 UserModel userM Odel = new UserModel (); 28 String userName = (EditText) findViewById (R. id. etUserName )). getText (). toString (). trim (); 29 userModel. setUserName (userName); 30 String pwd = (EditText) findViewById (R. id. etPwd )). getText (). toString (). trim (); 31 userModel. setPwd (pwd); 32 userLogin. login (userModel); 33} 34 35 UserLoginCallback userLoginCallback = new UserLoginCallback () {36 @ Override37 public void loginResult (B Oolean result) {38 Message msg = Message. obtain (); 39 msg. what = 7634; 40 if (result) {41 msg. obj = "Logon successful! "; 42} else {43 msg. obj =" Logon Failed! "; 44} 45 handler. sendMessage (msg); 46} 47}; 48 49 public class MyHandler extends android. OS. handler {50 @ Override51 public void handleMessage (Message msg) {52 switch (msg. what) {53 case 7634: 54 Toast. makeText (context, msg. obj. toString (), Toast. LENGTH_LONG ). show (); 55} 56} 57} 58}View Code
(3) Running Effect
Code obfuscation is the simplest and most basic Android APP security protection. Other APP security-related technologies will be introduced later.
DEMO of this instance (MyApplication4 source code project, JarTest simulates a third-party project ).