Android Eclipse import AS Gradle AAR library Manual
Preface
This is a semi-Technical article. AS we all know, Google is now pushing Android Studio development tools, while Eclipse has been idle for a while, but there are still many Eclipse projects that have not been migrated to the; currently, some new libraries are packaged and released to the public warehouse using AS Gradle, and these libraries cannot be directly used by Eclipse, this article describes how to import one or more libraries to Eclipse.
Purpose
Eclipse is basically a state of waste, which does not mean that Eclipse is not good, after all, it is from Eclipse; it can only be said that it is a new lover. The old lover must have a special charm, so not all of them are now migrated to the AS, and a large part of the projects are on Eclipse.
There is a problem here. Many developers generally generate the AAR library instead of packaging it AS a Jar package, and then publish it to the public repository, AS users can use this library with a simple code.Download-load-compile-runIt's done with Gradle, and Eclipse is not happy ~~
Eclipse is facing an embarrassing situation where it wants to use a new library, but it cannot be used ~~
This article explains how to use a library in a public repository in Eclipse.
Gradle release process warehouse Introduction
In the AS release library, Gradle is used to publish to the corresponding public warehouse. There are many warehouse, and you can also use the server to build the warehouse. There are two particularly OK public warehouse:
Jcenter mavencentral
In the initial google framework, the default repository was mavencentral. However, the repository was changed to jcenter because the publishing process of the mavencentral repository was strict and the operation was not user-friendly.
Therefore, we recommend that you use jcenter. If you publish your library in mavencentral, the library will be synchronized to jcenter within 24 hours after the release is successful, the databases released in jcenter can also be published to the mavencentral repository with one-click operation.
Because of the differences in the above warehouse, if you are using AS, you will see such configuration in the Configuration:
repositories { jcenter()}
repositories { jcenter { url "http://jcenter.bintray.com/" }}
repositories { mavenLocal()}
This is the source of the library used in your project. AS will identify more databases to find the desired files. Of course, the two warehouses can be written to the project configuration at the same time.
Publish to Repository
In my article, there is an article about publishing To the mavencentral Repository: [Publish AAR To Maven] Use Gradle To Publish AAR To the Maven Repository
The above describes the process of publishing to the mavencentral warehouse, and the jcenter process is similar, except that the file encryption process is completed on the server.
Overall:
First, we need to compile the source code of the database to obtain the source code files such as Jar, R, JNI, and xml. Package all files into an aar file signature and release it to the repository for verification and release how to use it
By using this library, you can easily download the AAR file of the corresponding version, add it to the project, and compile it into the project.
From this point, we can see that in actual android use, the aar file is used, but the aar file will be decompiled at this time.
In the AS project configuration, we add the following sentence:
dependencies { compile 'net.qiujuer.genius:ui:1.3.0'}
After compilation, let's take a look at the Build folder of the project:
Here, we can see that the actual use is indeed what we think.
Of course, this is why"Res"Package, because"Genius-ui"The package is referenced by default."Genius-res"Package, so when we use"UI"The package will be downloaded synchronously."Res"Package. For details, see the open-source project Genius-Android. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxibG9ja3F1b3RlPg0KCTxwPk9LLCDSu7j2v + k1xlzytaxb97pmztldx8u1usby6o7xmfdtmc0v7s/issue = "problem">
From the process of the above database, we can see that an AAR database can include jar, aidl, assets, res, R files, and other data; by default, only jar files can be referenced when libraries are referenced in Eclipse.
If we just put the jar file in eclipse, the corresponding resource file will not work properly. Does it solve this problem as long as the resource file is put into eclipse at the same time? No!
As we all know, a resource file will generate an int value corresponding to it in the R file during compilation, and all the actual code uses this int value instead; then all the resource files added above will generate a new value corresponding to it, so the corresponding resources still cannot be found in the library jar, and eventually the APP will crash.
There is a solution to solve this problem, that is, to solidify the INT value corresponding to the resource, so that the resource can generate the specified INT value every time during compilation. Here we use a special android file:"Public. xml"
Public. xml: Specifies the INT value corresponding to the resource.
Implementation download
First, we need to prepare a corresponding aar file. Here I useGenius-androidLibrary UI package to complete this operation.
Download points:
Jcenter mavencentral
Go to mavencentral, search for genius, and find the ui package:
Because the res package is referenced in the UI package, we download both the ui and res packages.
Unpack
Change the suffix to zip and unzip it:
AndroidManifest. xml: Contains permission-service declaration-broadcast registration-activity Declaration and other information. copy the data directly to your project. Aidl: This is generally a standalone service. just create a file in the project according to the corresponding place. Assets: This is generally the font, html, and other data classes. jar is the jar package we need to use directly. R.txt is the int value corresponding to the resource. The main task we need to do is to convert it to public. the content in the Res folder of the xml file can be copied to the res folder of the project. Create a project
To avoid conflicts between the project and its own project, we need to first create a project:
The name is GeniusUI and the package name is: "net. qiujuer. genius. ui"
Why? Because the AndroidManifest. xml extracted above contains the specified package name:
If the package name is not specified here, even if we have written public. although the INT value of the xml file can be solidified, it cannot correspond to our package name. In other words, the corresponding resource file cannot be found in our jar file.
Go to Properties-Android-check (Is Library) to make it a Library project.
Remember that we do not create a project for the RES package here; because resources in the RES package are referenced in the UI library, when the UI library is generated, the resource INT value of the new Res library will be recalculated.
Download the Res package only requires the resource files.
Open the R file (left) in the Res package and the R file (right) in the UI package at the same time ):
We can see that the UI package also contains the INT value corresponding to the color, but its value is not the same as that in the original Res package.
Copy an object
Copy all existing files to the project as shown in the image:
Compile the project once. Generally, as long as all the files are copied correctly, no error should be reported and an R file should be generated at this time, however, the R file is not exactly the same as the value in the original database (Some of them may be the same, which leads to the normal use of some resources.).
Comparison
In this case, compare the R file generated by the project with the R file in the database:
We can find that they are different. Of course, you may also be identical, for example:
What does this mean? This means that resources in this project can be fully used, but under what circumstances will they be different?
Add a color to the values. xml file in the Res project:
#ffecb3
What will this sentence bring? The following error occurs:
This is the problem that the resources I mentioned cannot be properly matched.
The similarities and differences are random. Maybe the original library is just a coincidence.
Public. xml curing
In this case, create the public. xml file in the project's values folder and add:
Compile the project. Now we can view the R file again:
Here we can see that the part we have written is okay, and there has been a problem since 5th, so ah, we need to solidify all the INT values corresponding to R into Public.
Well, now I know the charm of Public files, but it is not that satisfactory to solidify the entire file. I collapsed when I opened the R file of the UI library.
I wiped my hair and sweated more than 500 yuan ~~
No, it's not !!
And I probably looked at the color-number-style-TM and styleable. What is this> ghost? If you have written a custom control, you should know that it is a custom property.
But how is this fixed? More than 500 lines, so the dishes are getting cooler.
Code-based
We are programmers and we are all very lazy, so we use programs to solve them.
Here we can write a small program that converts data from R.txt to public. xml.
Format
First, let's take a look at the corresponding format when the r.txt file is switched to XML.
Color, number, array, ID, String, drawable can be directly converted
int color black 0x7f04000eint dimen font_10 0x7f050000int array loading 0x7f030000int id all 0x7f080009int string g_font_file 0x7f060000int drawable background 0x7f020000
Replace "_" with "." With the style parameter.
int style Genius_Widget_BalloonMarker 0x7f070000
The attr attribute must discard the styleable section.
int attr gAllowTrackClickToDrag 0x7f010022...int[] styleable AbsSeekBar { 0x7f01000c, 0x7f010019, 0x7f01001a, 0x7f01001b, 0x7f01001c, 0x7f01001d, 0x7f01001e, 0x7f01001f, 0x7f010020, 0x7f010021, 0x7f010022, 0x7f010023, 0x7f010024, 0x7f010025, 0x7f010026, 0x7f010027, 0x7f010028, 0x7f010029, 0x7f01002a, 0x7f01002b, 0x7f01002c }int styleable AbsSeekBar_gAllowTrackClickToDrag 10
To getgAllowTrackClickToDragThe INT value. Two methods can be directly converted from the first sentence.
The second method readsstyleable AbsSeekBarAnd then readint styleable AbsSeekBar_gAllowTrackClickToDrag 10The value is obtained according to the 10 subscript.0x7f010022.
Code entity class
static class PublicLine implements Comparable
{ public String type; public String name; public String id; public PublicLine() { } public PublicLine(String type, String name, String id) { this.type = type.trim(); this.name = name.trim(); this.id = id.trim(); } public String getKey() { return type + "_" + name; } @Override public String toString() { return "
"; } @Override public int compareTo(PublicLine o) { int i = this.type.compareTo(o.type); if (i == 0) return this.name.compareTo(o.name); else return i; } }
CompareTo is used for subsequent sorting to prevent output content from being messy. The "getKey ()" method is used to store the primary key values in the Map and avoid duplication. "ToString ()" This is for log output. Overall process
public static void main(String[] args) throws IOException { File in = new File("R.txt"); File out = new File("public.xml"); if (!in.exists()) { throw new NullPointerException("R.txt is not null."); } try { out.createNewFile(); } catch (IOException e) { e.printStackTrace(); return; } System.out.println(in.getAbsolutePath()); System.out.println(out.getAbsolutePath()); InputStreamReader read = new InputStreamReader(new FileInputStream(in)); BufferedReader bufferedReader = new BufferedReader(read); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(out)); BufferedWriter bufferedWriter = new BufferedWriter(writer); Map
xml = new HashMap<>(); buildXml(bufferedReader, xml); List
lines = new ArrayList<>(); lines.addAll(xml.values()); Collections.sort(lines); saveFile(lines, bufferedWriter); close(bufferedReader); close(bufferedWriter); System.out.println("End."); }
The entire process is very simple. directly use the current directory to generate two files. r.txt is the input source, and public. xml is the output file. Every time the file is run, a new file is generated.
Then, output the directory information of two files at a time to the console.
Then initialize the Buffer, which goes through two layers of sub-assembly. The final result is: BufferedReader and BufferedWriter. These two purposes are mainly for reading a row, the output is also a line.
Then declare a Map variable to store the set of read and converted objects. Map is used to avoid repeated content.
After that, we declared a List variable and stored the Map value in the List. This step mainly aims to sort the entire set. The Map itself is unordered, in addition, sorting the Map directly is quite complex, so we fill in the List and then sort it.
Then, it is output to the Public file, and then the stream operation is closed.
Read collection
public static void buildXml(BufferedReader reader, Map
xml) { while (true) { String line; try { line = reader.readLine(); if (line == null || line.trim().length() == 0) return; } catch (IOException e) { e.printStackTrace(); continue; } if (line.contains("styleable")) { // skip styleable array continue; } else { // convert other xml String[] split = line.split(" "); if (split.length == 0) continue; String type = split[1]; String name = split[2]; String id = split[3]; if (type.contains("style")) name = name.replace("_", "."); saveToMap(xml, new PublicLine(type, name, id)); } } }
Read each row cyclically. If a blank row is read, exit the loop. Here we use the filter method for attr conversion, therefore, all rows marked with "styleable" can be discarded directly. Normally, we read a row and split it by space. Then we read the values of type, name, and id respectively. If the current type is style
"_"Replace
".". Store the currently recognized information in Map.
If the attr recognition adopts reading the information in the styleable array and then searching for the corresponding INT value by index, the code should be like this:
public static void buildXml(BufferedReader reader, Map
xml) { while (true) { String line; try { line = reader.readLine(); if (line == null || line.trim().length() == 0) return; } catch (IOException e) { e.printStackTrace(); continue; } String[] split = line.split(" "); if (split.length == 0) continue; if (line.contains("int[]")) { // convert attr xml String name = split[2].trim(); line = line.substring(line.indexOf("{") + 1, line.lastIndexOf("}")); System.out.println(line); String[] ids = line.split(","); if (ids.length > 0) { readStyleableXml(reader, xml, ids, name); } } else { // convert other xml String type = split[1]; String name = split[2]; String id = split[3]; if (type.contains("style")) name = name.replace("_", "."); saveToMap(xml, new PublicLine(type, name, id)); } } } @SuppressWarnings("unused") public static void readStyleableXml(BufferedReader reader, Map
xml, String[] ids, String name) { for (String id : ids) { String line; try { line = reader.readLine(); if (line == null) continue; } catch (IOException e) { e.printStackTrace(); continue; } String[] split = line.split(" "); String lName = split[2].substring(split[2].indexOf(name) + name.length() + 1); String lId = ids[Integer.parseInt(split[3].trim())]; saveToMap(xml, new PublicLine("attr", lName, lId)); } }
Here we need another method. In this method, we cyclically read the rows corresponding to the array length following the array length of the current control, and then parse and store the rows.
Storage
public static void saveToMap(Map
xml, PublicLine line) { try { xml.putIfAbsent(line.getKey(), line); System.out.println(">>>: " + line.toString()); } catch (Exception e) { e.printStackTrace(); } }
The storage method is relatively simple. We use the "putIfAbsent" method of Map. This method is used to determine whether the current KEY exists. If it does not exist, it is stored.
Storage
public static void saveFile(List
lines, BufferedWriter writer) throws IOException { // write head writer.append("
"); writer.append("\n"); writer.append("
"); writer.append("\n"); for (PublicLine line : lines) { try { writer.append(" "); writer.append(line.toString()); writer.append("\n"); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } // write footer writer.append("
"); writer.flush(); }
Stored procedures can be divided into storage headers, storage set data, and storage bottom.
Close stream
public static void close(Closeable closeable) { try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } }
The method of closing the stream is simpler, but it is just a separate method.
Effect
In this case, we put the R file in the root directory and run the code once. The console will output:
At this time, a public file has been generated, which corresponds to the R file for a look:
It can be seen that the effect is quite good, and the public file is copied to the library for use directly.
Preview
To test whether it is successful, I follow the open-source LibraryGenius-AndroidThe sample project code in completes an interface layout in Eclipse.
All controls and resources can be used normally.
Last
Here, I generate a jar file from the code. You can download the file and put the R.txt file in the same directory. Run the jar file to obtain the public file.
At the same time, I uploaded all the source files and code to the BeFoot project of GtiHub. All future examples will be updated to this project.
BeFoot import-aar-eclipse ConverToXml. jar
If there is anything wrong, or you are not clear enough, please give me more advice.