The article directories

  • Basic: Build an Android project from scratch
  • Step up: Customize the desired functionality
    • Custom property configuration
    • Building named
    • Tomcat configures the download address
    • Generate qr code
    • Sending Email Notifications
    • Apk reinforcement
    • Added code review functionality
  • Some problem solving
    • Update information OBTAINED
    • Your project path contains non-ASCII characters
    • SonarQube server [127.0.0.1:9000] can not be reached
  • Other Settings
    • Change the initial password of admin
    • Delete redundant credentials
    • Project Workspace modification
    • How to check Jenkins built-in parameters
    • Example Modify the APK output path

Basic: Build an Android project from scratch

1. Download and install Jenkins

(1),Install tomcat

(2),Download Jenkins



After downloading it, you will find a.war file and place it in the Webapps folder in the Apache directory



Browser inputhttp://127.0.0.1:8080/jenkins





Skip the plug-in installation first



Then set the account and so on. After the configuration, you can see the Jenkins management interface



2. Plug-in installation





Check the following plug-ins

Git

Gradle

Email Extension

description setter

Build Name and Description Setter

user build vars

PostBuildScript

Branch API

SSH

Scriptler

Git Parameter

OWASP Markup Formatter: Enables description to display HTML, such as qr codes and download links

Click “Down Now and Install after restart” to download and restart Jenkins



Under the Installed TAB you can see the Installed plug-ins, more than you Installed yourself, because many dependent plug-ins are automatically downloaded



3, configuration,

Manage Jenkins -> Global Tools Configuration

Set the JDK



Set up Git



Gradle can be set to a fixed version. I don’t want to set Gradle to a fixed version



②, Manage Jenkins -> Configure System

Check theEnvironment variablesTo addANDROID_HOMEVariable, this value is the SDK path, you can go to the system variable and see what is it



4. Project configuration

① Click on the left New Item to create a New Item

Enter a project name and select Freestyle Project



Source Code Management

Select Git and fill in the project address



Credentials add A user. Enter the Git account information



(3), the Build

Select Invoke Gradle Script in Build and fill in Taskclean assembleRelease --stacktrace --debug(Clean build folder, compile and Release package, print stack log, debug mode)



5. Project construction

Click “Save” to enter the project home page. Click “Build Now” to start building. The “Build History” list will appear



If the circle turns red, the build failed. Click to go to the Build details page, and then click Console Output on the left to view the log Output





Because the information is more, you can search directlyWhat went wrongFind the cause of the error

If the circle turns blue, the build is successfulWorkspace -> app/build/outpusFind the apk



Step up: Customize the desired functionality

Custom property configuration

That completes the simple deployment and build. But that’s not the end of it. We want to configure the parameters to meet some requirements, such as different versions of the package according to the channel, different packages according to the Tag, etc. Jenkins parameterization is built in the project gradle.properties. We have VERSION_CODE and VERSION_NAME

COMPILE_SDK_VERSION=29
BUILD_TOOLS_VERSION=29.02.
APPLICATION_ID=com.szy.supermarket
MIN_SDK_VERSION=19
TARGET_SDK_VERSION=29
VERSION_CODE=1
VERSION_NAME=1.0. 0
MAVEN_URL=https://dl.bintray.com/yishopcustomer/maven/
android.useAndroidX=true
android.enableJetifier=true
Copy the code

This is used in build.gradle

apply plugin: 'com.android.application'. android { ...... defaultConfig { multiDexEnabledtrue
        applicationId APPLICATION_ID
        minSdkVersion MIN_SDK_VERSION
        targetSdkVersion TARGET_SDK_VERSION
        versionCode VERSION_CODE as int
        versionName VERSION_NAME
        ndk {
            abiFilters 'armeabi'
        }
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"}... productFlavors { szy { applicationId'com.xx.xx'
            manifestPlaceholders = [
                    app_name     : "Cloud Shop official". ]  } szytest { applicationId'com.xx.xx'
            manifestPlaceholders = [
                    app_name     : "Cloud Shop Test". ] }}}...Copy the code

Project Settings home -> General -> Check This project is parameterized



Let’s start adding parameters

Parameter names The parameter types Parameter Value List
GIT_TAG Git Parameter Dev, master, etc
BUILD_TYPE Choice Release or Debug
PRODUCT_FLAVORS Choice Xiaomi, Huawei, etc
VERSION_NAME String 1.0.0









We’ll reference it in the build below, so find it firstBuildTag, change the Tasks property value to:clean assemble${PRODUCT_FLAVORS}${BUILD_TYPE}



Also click Advanced in the lower right corner… , select the following options



This option is required for VERSION_NAME and VERSION_CODE because these parameters need to be injected into the Configuration of the Android project, and the option in the red box can help us hack into the gradle.properties file to replace the values. The build.gradle file can reference the gradle.properties file directly, so the above two parameters will change when Jenkins is packing

Source Code ManagementModify the packaged version as shown in the figure below:



After setting the parameters,Build NowThe choices becomeBuild with Parameters, repackaging the page looks like this

Building named

The original name is just the build number and has no recognition



Change to Build number _ Builder name _ Build channel version _ Build type _APP version and findBuild Environment, select Set Build Name and enter Build Name#${BUILD_NUMBER}_${BUILD_USER}_${PRODUCT_FLAVORS}_${BUILD_TYPE}_${VERSION_NAME}



After a successful build again, the name changes to

Tomcat configures the download address

Tomcat installation directory -> conf -> server. XML

<Context reloadable="true" docBase="D: \ apache tomcat - 9.0.36 \ webapps \ app" crossContext="true" path=""/>
Copy the code

DocBase is the absolute path to save apK files. By default, we pack them in the directory \app\build\outputs\apk\szytest\debug. We can modify them ourselves. Method Look at other Settings in this article – change the APK output path to a relative address that is accessed in the address bar

After adding this sentence, restart Tomcat, open the browser and input IP :port/ APK name, you can download apK, for example, I input 127.0.0.1:8080/ app-szytest-debug_5.apk in the browser and you can directly download APK

Generate qr code

Qrcode: PIP install Pillow PIP install myqr qrcode: PIP install Pillow

Use the command line to generate two-dimensional code myQR To generate two-dimensional code content -n specifies the two-dimensional code name -d specifies the two-dimensional code storage location

So we in the Build of Windows batch command (add) step on finally, add the following code myqr http://192.168.3.215:8080/%apkName%_%BUILD_ID%.apk – n % BUILD_ID %. JPG -d %outputs%/qrcode

Replace IP with your local IP address



It would have been inD: \ apache tomcat - 9.0.36 \ webapps \ app \ qrcodeBelow generate the qr code image named BUIID_ID. JPG



The next step is to show the qr code and findPost-build Actions, add Set Build description

Add the following code to Description, that is, add a QR code display and a click to download link

<img src='http://192.168.3.215:8080/qrcode/${BUILD_ID}. JPG' style='width:200px; height:200px'>
<br/>
<a href='http://192.168.3.215:8080/app-$- ${BUILD_TYPE} _ {PRODUCT_FLAVORS} ${BUILD_ID}. The apk'>Click on the download</a>
Copy the code

To display HTML in Build History, you also need to addManage Jenkins -> Configure Global SecurityChange the Markup Formatter in to Safe Html (depends onOWASP Markup FormatterPlugin, otherwise there is no Safe HTML option.



The package shows the QR code and the download link

Sending Email Notifications

Here take QQ mailbox as an example

First of all,Manage Jenkins -> Configure System -> Jenkins Location

System Admin E-mail address Enter the QQ mailbox



thenManage Jenkins -> Configure System -> E-mail NotificationFill in the information to test



A few things to note:

Mail Server AddressYou can find it in the help center of the email box by searching SMTP. For example,Qq email

Your passwordThe POP3/SMTP service needs to be enabled in Settings -> Account to obtain the authorization code, and fill this authorization code into the email password



After filling in successfully, send test email, fill in the above after successExtended E-mail NotificationModule, the content is the same as the previous ok, the difference has the following

Default mail type:



The default recipient is separated by commas (,) :



Email Title and Content:



Default Content is the email Content:

<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title>${PROJECT_NAME}- ${BUILD_NUMBER} build log</title>
</head>
 
<body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4"
    offset="0">
    <table width="95%" cellpadding="0" cellspacing="0"
        style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">
        <tr>
            <td>(This email is automatically issued by the program, please do not reply!)</td>
        </tr>
        <tr>
            <td><br />
            <b><font color="#0B610B">Build information ($BUILD_STATUS)</font></b>
            <hr size="2" width="100%" align="center" /></td>
        </tr>
        <tr>
            <td>
                <ul>
                    <li>Project name: ${PROJECT_NAME}</li>
                    <li>Build number: the ${BUILD_NUMBER} build</li>
                    <li>${CAUSE}</li>
                    <li>Build log:<a href="${BUILD_URL}console">Click to view</a></li>
                    <li>Working Directory:<a href="${PROJECT_URL}ws">Click to view</a></li>
                    <li>Allure Report:<a href="${BUILD_URL}allure">Click to view</a></li>
                </ul>
            </td>
        </tr>
        <tr>
            <td><b><font color="#0B610B">Build log (last 100 lines):</font></b>
            <hr size="2" width="100%" align="center" /></td>
        </tr>
        <tr>
            <td><textarea cols="80" rows="30" readonly="readonly"
                    style="font-family: Courier New">${BUILD_LOG, maxLines=100}</textarea>
            </td>
        </tr>
    </table>
</body>
</html>
Copy the code

Click on the lower right corner of Default Triggers to set the timing of mail delivery



Then there are the actions that need to be taken after the project is built, i.ePost-build ActionsAdded an Editable Email Notification in







Send a message as shown below:

Apk reinforcement

The 360 reinforcement is used here for demonstration. Follow the instructions in the command Line Hardening mode chapter of the 360 Hardening Assistant user manual. First let’s test it on the machine

Open CMD and usejava -jar jiagu.jar -login <user name> <password>The login



usejava -jar jiagu.jar -importsign <keystore_path> <keystore_password> <alias> <alias_password>Import signature keystore information



Hardening will invalidate the signature of the original APK package. Therefore, you need to re-sign the APK package using the original application keystore signature file so that the APK file can be properly installed and used



Finally, the signature is successful





So let’s put it in Jenkins, first in JenkinsGeneralAdd a Boolean Parameter to indicate whether to harden



On the Build TAB, in the batch command

set outputs=D:\apache-tomcat9 -.0.36\webapps\app
set apkName=app-%PRODUCT_FLAVORS%-%BUILD_TYPE%
set storeFile=D:\YishopSellerKey.jks
set storePassword=szyapp1234
set keyAlias=yishopseller

del /q /s %outputs%\jiagu\*.*

if %IS_JIAGU%==true goto A else goto B

:A
java -jar "D:\jiagu\jiagu.jar" -login [email protected] yxx@123456
java -jar "D:\jiagu\jiagu.jar" -importsign %storeFile% %storePassword% %keyAlias% %storePassword%
java -jar "D:\jiagu\jiagu.jar" -jiagu %WORKSPACE%\app\build\outputs\apk\%PRODUCT_FLAVORS%\%BUILD_TYPE%\%apkName%.apk %outputs%\jiagu -autosign

for /r  %outputs%\jiagu\ %%i in (*.apk) do copy %%i %outputs%\%apkName%_%BUILD_ID%.apk

if "%errorlevel%"= ="0" goto C
if "%errorlevel%"= ="1" goto A

:B
copy%WORKSPACE%\app\build\outputs\apk\%PRODUCT_FLAVORS%\%BUILD_TYPE%\%apkName%.apk %outputs%\%apkName%_%BUILD_ID%.apk goto C  :C myqr http://192.168.3.215:8080/%apkName%_%BUILD_ID%.apk -n %BUILD_ID%.jpg -d %outputs%\qrcode
exit
Copy the code

The hardening operation is added. If the hardening operation is selected, goto A (perform the hardening operation and save the hardening to the Jiagu folder; Then copy the hardened APK to the APP folder; If there are no errors, goto C; If there is an error, re-goto A) If goto B is not hardened (copy apK under build directly to app folder)

This operation is the operation of generating two-dimensional code

Pack again and check harden



After this packaging is successful, the jiagu folder is emptied and a file named *_jiagu_sign.apk is generated during each hardening



This file will then be copied to the app folder

Added code review functionality

1. Install SonarQube first

downloadSonarQubeThe Community version is free

Decompress the file, locate the system version in the bin directory, and open startsonar.bat. For example, I downloaded version 7.8 and unzipped it to disk D. So I need to open itD: \ sonarqube - 7.8 \ bin \ Windows x86-64 \ StartSonar bat

Open a browser and access 127.0.0.1:9000. If the following dialog box is displayed, the installation is successful



2,Install PostgreSQL

3. Configure Sonarqube

Open theD: \ sonarqube - 7.8 \ conf \ sonar properties, find the PostgresQL node added

sonar.jdbc.username=sonar
sonar.jdbc.password=sonar
sonar.jdbc.url=jdbc:postgresql://localhost:5432/sonar
sonar.login=admin
sonar.password=admin
Copy the code

Jdbc.password = SONAR database password (new user created when installing PostgreSQL) Sonar, the JDBC url = JDBC: postgresql: / / localhost: 5432 / sonar database address, Sonar. Login =admin sonarqube Default account sonar.password=admin sonarqube default password

Restart Sonarqube (you can restart your computer and then execute startsonar.bat). If 127.0.0.1:9000 works, you have configured it correctly. If no, check whether the configuration is correct

Then open pgAdmin 4 again and you can see that you already have tables in your sonar database



4. Jenkins install plugins

Search in plug-in managementSonarQube ScannerInstall and restart

Manage Jenkins -> Configure System -> SonarQube Servers enter the following information



Namerandom

Server URLSonarQube address, make sure you put http://

Fill in the first two items first and then save them before filling in the token. The third item is optional. I will not fill in the token here

Server authentication tokenObtain the Sonarqube page as follows





a26158c7386d936ab955c4677fbefee555fb6f15

After copying, click “Add” of the third item and fill in the pop-up page

SonarQube Scanner Manage Jenkins -> Global Tools Configuration

Figure can be installed automatically



6. Task construction

Create a new project





Enter the working directory in General, noting the “/” direction



Select the code you want to review and the source of the code is git, the same as before



Add Invoke Gradle Script to Build



Add Excute SonarQube Scanner to Build



Because Sonarsanner is integrated in Jenkins, the Path to Project Properties path is not required (Sonarscanner canDownload and install it separately, this method is self-reliant. However, add the corresponding configuration in the “Analysis Properties” section

Note the “/” direction of the path

ProjectKey # project sonar. ProjectKey =supermarket # projectName sonar. ProjectName = cloud shop # projectVersion sonar. ProjectVersion =1.0 # language Sonar. Language = Java # Sonar. Sources =${workspace}/app/ SRC #compiled classes of your project sonar.java.binaries=${workspace}/app/build/intermediates/javac/szytestDebug/classesCopy the code

7, Build Now

A sonarqube icon appears in the upper right corner of a successful Build. Click to view it

Some problem solving

Update information OBTAINED



Solutions:

If Advanced is selected on the current page, the update site at the bottom is selected byhttpsInstead ofhttp





Then turn Jenkins back on

Your project path contains non-ASCII characters



What went wrong the build.gradle path contains Chinese characters. Since we created the project under the name “Cloud Shop”, the “cloud Shop” directory is created by default

So just change the project workspace. See the other Settings later in this article to make the changes

SonarQube server [127.0.0.1:9000] can not be reached

SonarQube server [127.0.0.1:9000] can not be reached SonerQube Server configuration needs to be checked in Manage Jenkins -> Configure System -> SonarQube Servers

Other Settings

Change the initial password of admin

The initial password is C:\Users\00lix\.Jenkins \secrets\initialAdminPassword the password is too long, we want to change a simple password, such as 123456, we are in Eclipse

public class Main {
	public static void main(String[] args) {
		// This is encrypted
		String hashed = BCrypt.hashpw("123456", BCrypt.gensalt());
		System.out.println(hashed);

		// This is the decryption method
		if (BCrypt.checkpw("123456", hashed))
			System.out.println("It matches");
		else
			System.out.println("It does not match"); }}Copy the code

To import the JAR package,The jar package download



Then import





To run the program



Open theC:\Users\00lix\.jenkins\users\admin_xxx\config.xmlTo find<passwordHash>Node, replaced by the string#jbcrypt:The rest



Restart Jenkins (close and then open Apache)

Delete redundant credentials

The Credentials in Source Code Management are duplicate, now delete them



Click on the left side of theThe credentialsTo find the deduplication

Project Workspace modification

Workspace is the working directory, generally is Down the source code directory, the default is in C:\Users\00lix\.jenkins\workspace, modify a project workspace can be operated in this way

Enter the project home pageConfigure -> General -> Advanced…



Check theUse custom workspace, fill in the custom workspace

How to check Jenkins built-in parameters

In Project Settings, findBuildTAB, click Advanced… Click the link below



The open link is/jenkins/env-vars.html/You can see the Jenkins built-in parameters

Example Modify the APK output path

inBuildAdd Execute Windows Batch Command under the Add Build step TAB.



Get original pathD:\workspace\SuperMarket\app\build\outputs\apk\szytest\debugTo the specified directoryD: \ apache tomcat -- 9.0.36 \ webapps \ app

Set outputs=D:\apache-tomcat-9.0.36\webapps\app set apkName=app-%PRODUCT_FLAVORS%-%BUILD_TYPE% copy %WORKSPACE%\app\build\outputs\apk\%PRODUCT_FLAVORS%\%BUILD_TYPE%\%apkName%.apk %outputs%\%apkName%_%BUILD_ID%.apkCopy the code

The apK is then copied to the custom path

Android Jenkins+Git+Gradle continuous Integration – SonarQube installation, configuration and use