一、什么是AAPT2
在Android開發過程中,我們通過Gradle命令,啟動一個構建任務,最終會生成構建產物“APK”文件。常規APK的構建流程如下:
(引用自Google官方文檔)
-
編譯所有的資源文件,生成資源表和R文件;
-
編譯Java文件並把class文件打包為dex文件;
-
打包資源和dex文件,生成未簽名的APK文件;
-
簽名APK生成正式包。
老版本的Android默認使用AAPT編譯器進行資源編譯,從Android Studio 3.0開始,AS默認開啟了 AAPT2 作為資源編譯的編譯器,目前看來,AAPT2也是Android發展的主流趨勢,學習AAPT2的工作原理可以幫助Android開發更好的掌握APK構建流程,從而幫助解決實際開發中遇到的問題。
AAPT2 的可執行文件隨 Android SDK 的 Build Tools 一起發布,在Android Studio的build-tools文件夾中就包含AAPT2工具,目錄為(SDK目錄/build-tools/version/aapt2)。
二、AAPT2如何工作
在看Android編譯流程的時候,我忍不住會想一個問題:
Java文件需要編譯才能生class文件,這個我能明白,但資源文件編譯到底是干什么的?為什么要對資源做編譯?
帶着這個問題,讓我們深入的學習一下AAPT2。和AAPT不同,AAPT2把資源編譯打包過程拆分為兩部分,即編譯和鏈接:
編譯:將資源文件編譯為二進制文件(flat)。
鏈接:將編譯后的文件合並,打包成單獨文件。
通過把資源編譯拆分為兩個部分,AAPT2能夠很好的提升資源編譯的性能。例如,之前一個資源文件發生變動,AAPT需要做一全量編譯,AAPT2只需要重新編譯改變的文件,然后和其他未發生改變的文件進行鏈接即可。
2.1 Compile命令
如上文描述,Complie指令用於編譯資源,AAPT2提供多個選項與Compile命令搭配使用。
Complie的一般用法如下:
aapt2 compile path-to-input-files [options] -o output-directory/
執行命令后,AAPT2會把資源文件編譯為.flat格式的文件,文件對比如下。
Compile命令會對資源文件的路徑做校驗,輸入文件的路徑必須符合以下結構:path/resource-type[-config]/file。
例如,把資源文件保存在“aapt2”文件夾下,使用Compile命令編譯,則會報錯“error: invalid file path '.../aapt2/ic_launcher.png'”。把aapt改成“drawable-hdpi”,編譯正常。
在Android Studio中,可以在app/build/intermediates/res/merged/ 目錄下找到編譯生成的.flat文件。當然Compile也支持編譯多個文件;
aapt2 compile path-to-input-files1 path-to-input-files2 [options] -o output-directory/
編譯整個目錄,需要制定數據文件,編譯產物是一個壓縮文件,包含目錄下所有的資源,通過文件名把資源目錄結構扁平化。
aapt2 compile --dir .../res [options] -o output-directory/resource.ap_
可以看到經過編譯后,資源文件(png,xml ... )會被編譯成一個FLAT格式的文件,直接把FLAT文件拖拽到as中打開,是亂碼的。那么這個FLAT文件到底是什么?
2.2 FLAT文件
FLAT文件是AAPT2編譯的產物文件,也叫做AAPT2容器,文件由文件頭和資源項兩大部分組成:
文件頭
資源項
資源項中,按照 entry_type 值分為兩種類型:
-
當entry_type 的值等於 0x00000000時,為RES_TABLE類型。
-
當entry_type的值等於 0x00000001時,為RES_FILE類型。
RES_TABLE包含的是protobuf格式的 ResourceTable 結構。數據結構如下:
// Top level message representing a resource table.
message ResourceTable {
// 字符串池
StringPool source_pool = 1;
// 用於生成資源id
repeated Package package = 2;
// 資源疊加層相關
repeated Overlayable overlayable = 3;
// 工具版本
repeated ToolFingerprint tool_fingerprint = 4;
}
資源表(ResourceTable)中包含:
StringPool:字符串池,字符串常量池是為了把資源文件中的string復用起來,從而減少體積,資源文件中對應的字符串會被替換為字符串池中的索引。
message StringPool {
bytes data = 1;
}
Package:包含資源id的相關信息
// 資源id的包id部分,在 [0x00, 0xff] 范圍內
message PackageId {
uint32 id = 1;
}
// 資源id的命名規則
message Package {
// [0x02, 0x7f) 簡單的說,由系統使用
// 0x7f 應用使用
// (0x7f, 0xff] 預留Id
PackageId package_id = 1;
// 包名
string package_name = 2;
// 資源類型,對應string, layout, xml, dimen, attr等,其對應的資源id區間為[0x01, 0xff]
repeated Type type = 3;
}
資源id的命令方式遵循0xPPTTEEEE的規則,其中PP對應PackageId,一般應用使用的資源為7f,TT對應的是資源文件夾的名成,最后4位為資源的id,從0開始。
RES_FILE類型格式如下:
RES_FILE類型的FLAT文件結構可以參考下圖;
從上圖展示的文件格式中可以看出,一個FLAT中可以包含多個資源項,在資源項中,Header字段中保存的是protobuf格式序列化的 CompiledFile 內容。在這個結構中,保存了文件名、文件路徑、文件配置和文件類型等信息。data字段中保存資源文件的內容。通過這種方式,一個文件中既保存了文件的外部相關信息,又包含文件的原始內容。
2.3 編譯的源碼
上文,我們學習了編譯命令Compile的用法和編譯產物FLAT文件的文件格式,接下來,我們通過查看代碼,從源碼層面來學習AAPT2的編譯流程,本文源碼地址。
2.3.1 命令執行流程
根據常識,一般函數的入口都是和main有關,打開Main.cpp,可以找到main函數入口;
int main(int argc, char** argv) {
#ifdef _WIN32
......
//參數格式轉換
argv = utf8_argv.get();
#endif
//具體的實現MainImpl中
return MainImpl(argc, argv);
}
在MainImpl中,首先從輸入中獲取參數部分,然后創建一個MainCommand來執行命令。
int MainImpl(int argc, char** argv) {
if (argc < 1) {
return -1;
}
// 從下標1開始的輸入,保存在args中
std::vector<StringPiece> args;
for (int i = 1; i < argc; i++) {
args.push_back(argv[i]);
}
//省略部分代碼,這部分代碼用於打印信息和錯誤處理
//創建一個MainCommand
aapt::MainCommand main_command(&printer, &diagnostics);
// aapt2的守護進程模式,
main_command.AddOptionalSubcommand( aapt::util::make_unique<aapt::DaemonCommand>(&fout, &diagnostics));
// 調用Execute方法執行命令
return main_command.Execute(args, &std::cerr);
}
MainCommand繼承自Command,在MainCommand初始化方法中會添加多個二級命令,通過類名,可以容易的推測出,這些Command和終端通過命令查看的二級命令一一對應。
explicit MainCommand(text::Printer* printer, IDiagnostics* diagnostics)
: Command("aapt2"), diagnostics_(diagnostics) {
//對應Compile 命令
AddOptionalSubcommand(util::make_unique<CompileCommand>(diagnostics));
//對應link 命令
AddOptionalSubcommand(util::make_unique<LinkCommand>(diagnostics));
AddOptionalSubcommand(util::make_unique<DumpCommand>(printer, diagnostics));
AddOptionalSubcommand(util::make_unique<DiffCommand>());
AddOptionalSubcommand(util::make_unique<OptimizeCommand>());
AddOptionalSubcommand(util::make_unique<ConvertCommand>());
AddOptionalSubcommand(util::make_unique<VersionCommand>());
}
AddOptionalSubcommand方法定義在基類Command中,內容比較簡單,把傳入的subCommand保存在數組中。
void Command::AddOptionalSubcommand(std::unique_ptr<Command>&& subcommand, bool experimental) {
subcommand->full_subcommand_name_ = StringPrintf("%s %s", name_.data(), subcommand->name_.data());
if (experimental) {
experimental_subcommands_.push_back(std::move(subcommand));
} else {
subcommands_.push_back(std::move(subcommand));
}
}
接下來,再來分析main_command.Execute的內容,從方法名可以推測這個方法里面有指令執行的相關代碼。在MainCommand中並沒有Execute方法的實現,那應該是在父類中實現了,再到Command類中搜索,果然在這里。
int Command::Execute(const std::vector<StringPiece>& args, std::ostream* out_error) {
TRACE_NAME_ARGS("Command::Execute", args);
std::vector<std::string> file_args;
for (size_t i = 0; i < args.size(); i++) {
const StringPiece& arg = args[i];
// 參數不是 '-'
if (*(arg.data()) != '-') {
//是第一個參數
if (i == 0) {
for (auto& subcommand : subcommands_) {
//判斷是否是子命令
if (arg == subcommand->name_ || (!subcommand->short_name_.empty() && arg == subcommand->short_name_)) {
//執行子命令的Execute 方法,傳入參數向后移動一位
return subcommand->Execute( std::vector<StringPiece>(args.begin() + 1, args.end()), out_error);
}
}
//省略部分代碼
//調用Action方法,在執行二級命令時,file_args保存的是位移后的參數
return Action(file_args);
}
在Execute方法中,會先對參數作判斷,如果參數第一位命中二級命令(Compile,link,.....),則調用二級命令的Execute方法。參考上文編譯命令的示例可知,一般情況下,在這里就會命中二級命令的判斷,從而調用二級命令的Execute方法。
在Command.cpp的同級目錄下,可以找到Compile.cpp,其Execute繼承自父類。但是由於參數已經經過移位,所以最終會執行Action方法。在Compile.cpp中可以找到Action方法,同樣在其他二級命令的實現類中(Link.cpp,Dump.cpp...),其核心處理的處理也都有Action方法中。整體調用的示意圖如下:
在開始看Action代碼之前,我們先看一下Compile.cpp的頭文件Compile.h的內容,在CompileCommand初始化時,會把必須參數和可選參數都初始化定義好。
SetDescription("Compiles resources to be linked into an apk.");
AddRequiredFlag("-o", "Output path", &options_.output_path, Command::kPath);
AddOptionalFlag("--dir", "Directory to scan for resources", &options_.res_dir, Command::kPath);
AddOptionalFlag("--zip", "Zip file containing the res directory to scan for resources", &options_.res_zip, Command::kPath);
AddOptionalFlag("--output-text-symbols", "Generates a text file containing the resource symbols in the\n" "specified file", &options_.generate_text_symbols_path, Command::kPath);
AddOptionalSwitch("--pseudo-localize", "Generate resources for pseudo-locales " "(en-XA and ar-XB)", &options_.pseudolocalize);
AddOptionalSwitch("--no-crunch", "Disables PNG processing", &options_.no_png_crunch);
AddOptionalSwitch("--legacy", "Treat errors that used to be valid in AAPT as warnings", &options_.legacy_mode);
AddOptionalSwitch("--preserve-visibility-of-styleables", "If specified, apply the same visibility rules for\n" "styleables as are used for all other resources.\n" "Otherwise, all stylesables will be made public.", &options_.preserve_visibility_of_styleables);
AddOptionalFlag("--visibility", "Sets the visibility of the compiled resources to the specified\n" "level. Accepted levels: public, private, default", &visibility_);
AddOptionalSwitch("-v", "Enables verbose logging", &options_.verbose);
AddOptionalFlag("--trace-folder", "Generate systrace json trace fragment to specified folder.", &trace_folder_);
官網中列出的編譯選項並不全,使用compile -h打印信息后就會發現打印的信息和代碼中的設置是一致的。
在Action方法的執行流程可以總結為:
1)會根據傳入參數判斷資源類型,並創建對應的文件加載器(file_collection)。
2)根據傳入的輸出路徑判斷輸出文件的類型,並創建對應的歸檔器(archive_writer),archive_writer在后續的調用鏈中一直向下傳遞,最終通過archive_writer把編譯后的文件寫到輸出目錄下。
3)調用Compile方法執行編譯。
過程1,2中涉及的文件讀寫對象如下表。
簡化的主流程代碼如下:
int CompileCommand::Action(const std::vector<std::string>& args) {
//省略部分代碼....
std::unique_ptr<io::IFileCollection> file_collection;
//加載輸入資源,簡化邏輯,下面會省略掉校驗的代碼
if (options_.res_dir && options_.res_zip) {
context.GetDiagnostics()->Error(DiagMessage() << "only one of --dir and --zip can be specified");
return 1;
} else if (options_.res_dir) {
//加載目錄下的資源文件...
file_collection = io::FileCollection::Create(options_.res_dir.value(), &err);
//...
}else if (options_.res_zip) {
//加載壓縮包格式的資源文件...
file_collection = io::ZipFileCollection::Create(options_.res_zip.value(), &err);
//...
} else {
//也是FileCollection,先定義collection,通過循環依次添加輸入文件,再拷貝到file_collection
file_collection = std::move(collection);
}
std::unique_ptr<IArchiveWriter> archive_writer;
//產物輸出文件類型
file::FileType output_file_type = file::GetFileType(options_.output_path);
if (output_file_type == file::FileType::kDirectory) {
//輸出到文件目錄
archive_writer = CreateDirectoryArchiveWriter(context.GetDiagnostics(), options_.output_path);
} else {
//輸出到壓縮包
archive_writer = CreateZipFileArchiveWriter(context.GetDiagnostics(), options_.output_path);
}
if (!archive_writer) {
return 1;
}
return Compile(&context, file_collection.get(), archive_writer.get(), options_);
}
Compile方法中會編譯輸入的資源文件名,每個資源文件的處理方式如下:
-
解析輸入的資源路徑獲取資源名,擴展名等信息;
-
根據path判斷文件類型,然后給compile_func設置不同的編譯函數;
-
生成輸出的文件名。輸出的就是FLAT文件名,會對全路徑拼接,最終生成上文案例中類似的文件名—“drawable-hdpi_ic_launcher.png.flat”;
-
傳入各項參數,調用compile_func方法執行編譯。
ResourcePathData中包含了資源路徑,資源名,資源擴展名等信息,AAPT2會從中獲取資源的類型。
int Compile(IAaptContext* context, io::IFileCollection* inputs, IArchiveWriter* output_writer, CompileOptions& options) {
TRACE_CALL();
bool error = false;
// 編譯輸入的資源文件
auto file_iterator = inputs->Iterator();
while (file_iterator->HasNext()) {
// 省略部分代碼(文件校驗相關...)
std::string err_str;
ResourcePathData path_data;
// 獲取path全名,用於后續文件類型判斷
if (auto maybe_path_data = ExtractResourcePathData(path, inputs->GetDirSeparator(), &err_str)) {
path_data = maybe_path_data.value();
} else {
context->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << err_str);
error = true;
continue;
}
// 根據文件類型,選擇編譯方法,這里的 CompileFile 是函數指針,指向一個編譯方法。
// 使用使用設置為CompileFile方法
auto compile_func = &CompileFile;
// 如果是values目錄下的xml資源,使用 CompileTable 方法編譯,並修改擴展名為arsc
if (path_data.resource_dir == "values" && path_data.extension == "xml") {
compile_func = &CompileTable;
// We use a different extension (not necessary anymore, but avoids altering the existing // build system logic).
path_data.extension = "arsc";
} else if (const ResourceType* type = ParseResourceType(path_data.resource_dir)) {
// 解析資源類型,如果kRaw類型,執行默認的編譯方法,否則執行如下代碼。
if (*type != ResourceType::kRaw) {
//xml路徑或者文件擴展為.xml
if (*type == ResourceType::kXml || path_data.extension == "xml") {
// xml類,使用CompileXml方法編譯
compile_func = &CompileXml;
} else if ((!options.no_png_crunch && path_data.extension == "png") || path_data.extension == "9.png") { //如果后綴名是.png並且開啟png優化或者是點9圖類型
// png類,使用CompilePng方法編譯
compile_func = &CompilePng;
}
}
} else {
// 不合法的類型,輸出錯誤信息,繼續循環
context->GetDiagnostics()->Error(DiagMessage() << "invalid file path '" << path_data.source << "'");
error = true;
continue;
}
// 校驗文件名中是否有.
if (compile_func != &CompileFile && !options.legacy_mode && std::count(path_data.name.begin(), path_data.name.end(), '.') != 0) {
error = true;
context->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "file name cannot contain '.' other than for" << " specifying the extension");
continue;
}
// 生成產物文件名,這個方法會生成完成的flat文件名,例如上文demo中的 drawable-hdpi_ic_launcher.png.flat
const std::string out_path = BuildIntermediateContainerFilename(path_data);
// 執行編譯方法
if (!compile_func(context, options, path_data, file, output_writer, out_path)) {
context->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "file failed to compile"); error = true;
}
}
return error ? 1 : 0;
}
不同的資源類型會有四種編譯函數:
-
CompileFile
-
CompileTable
-
CompileXml
-
CompilePng
raw目錄下的XML文件不會執行CompileXml,猜測是因為raw下的資源是直接復制到APK中,不會做XML優化編譯。values目錄下資源除了執行CompileTable編譯之外,還會修改資源文件的擴展名,可以認為除了CompileFile,其他編譯方法多多少少會對原始資源做處理后,在寫編譯生成的FLAT文件中。這部分的流程如下圖所示:
編譯命令執行的主流程到這里就結束了,通過源碼分析,我們可以知道AAPT2把輸入文件編譯為FLAT文件。下面,我們在進一步分析4個編譯方法。
2.3.2 四種編譯函數
CompileFile
函數中先構造ResourceFile對象和原始文件數據,然后調用 WriteHeaderAndDataToWriter 把數據寫到輸出文件(flat)中。
static bool CompileFile(IAaptContext* context, const CompileOptions& options, const ResourcePathData& path_data, io::IFile* file, IArchiveWriter* writer, const std::string& output_path) {
TRACE_CALL();
if (context->IsVerbose()) {
context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "compiling file");
}
// 定義ResourceFile 對象,保存config,source等信息
ResourceFile res_file;
res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
res_file.config = path_data.config;
res_file.source = path_data.source;
res_file.type = ResourceFile::Type::kUnknown; //這類型下可能有xml,png或者其他的什么,統一設置類型為unknow。
// 原始文件數據
auto data = file->OpenAsData();
if (!data) {
context->GetDiagnostics()->Error(DiagMessage(path_data.source) << "failed to open file ");
return false;
}
return WriteHeaderAndDataToWriter(output_path, res_file, data.get(), writer, context->GetDiagnostics());
}
ResourceFile的內容相對簡單,完成文件相關信息的賦值后就會調用通過WriteHeaderAndDataToWriter方法。
在WriteHeaderAndDataToWriter這個方法中,對之前創建的archive_writer(可在本文搜索,這個歸檔寫創建完成后,會一直傳下來)做一次包裝,經過包裝的ContainerWriter則具備普通文件寫和protobuf格式序列化寫的能力。
pb提供了ZeroCopyStream 接口用戶數據讀寫和序列化/反序列化操作。
WriteHeaderAndDataToWriter的流程可以簡單歸納為:
-
IArchiveWriter.StartEntry,打開文件,做好寫入准備;
-
ContainerWriter.AddResFileEntry,寫入數據;
-
IArchiveWriter.FinishEntry,關閉文件,釋放內存。
static bool WriteHeaderAndDataToWriter(const StringPiece& output_path, const ResourceFile& file, io::KnownSizeInputStream* in, IArchiveWriter* writer, IDiagnostics* diag) {
// 打開文件
if (!writer->StartEntry(output_path, 0)) {
diag->Error(DiagMessage(output_path) << "failed to open file");
return false;
}
// Make sure CopyingOutputStreamAdaptor is deleted before we call writer->FinishEntry().
{
// 對write做一層包裝,用來寫protobuf數據
CopyingOutputStreamAdaptor copying_adaptor(writer);
ContainerWriter container_writer(©ing_adaptor, 1u);
//把file按照protobuf格式序列化,序列化后的文件是 pb_compiled_file,這里的file文件是ResourceFile文件,包含了原始文件的路徑,配置等信息
pb::internal::CompiledFile pb_compiled_file;
SerializeCompiledFileToPb(file, &pb_compiled_file);
// 再把pb_compiled_file 和 in(原始文件) 寫入到產物文件中
if (!container_writer.AddResFileEntry(pb_compiled_file, in)) {
diag->Error(DiagMessage(output_path) << "failed to write entry data");
return false;
}
}
// 退出寫狀態
if (!writer->FinishEntry()) {
diag->Error(DiagMessage(output_path) << "failed to finish writing data");
return false;
}
return true;
}
我們再分別來看這三個方法,首先是StartEntry和FinishEntry,這個方法在Archive.cpp中,ZipFileWriter和DirectoryWriter實現有些區別,但邏輯上是一致的,這里只分析DirectoryWriter的實現。
StartEntry,調用fopen打開文件。
bool StartEntry(const StringPiece& path, uint32_t flags) override {
if (file_) {
return false;
}
std::string full_path = dir_;
file::AppendPath(&full_path, path);
file::mkdirs(file::GetStem(full_path).to_string());
//打開文件
file_ = {::android::base::utf8::fopen(full_path.c_str(), "wb"), fclose};
if (!file_) {
error_ = SystemErrorCodeToString(errno);
return false;
}
return true;
}
FinishEntry,調用reset釋放內存。
bool FinishEntry() override {
if (!file_) {
return false;
}
file_.reset(nullptr);
return true;
}
ContainerWriter類定義在Container.cpp這個類文件中。在ContainerWriter類的構造方法中,可以找到文件頭的寫入代碼,其格式和上文“FLAT格式”一節中介紹的一致。
// 在類的構造方法中,寫入文件頭的信息
ContainerWriter::ContainerWriter(ZeroCopyOutputStream* out, size_t entry_count)
: out_(out), total_entry_count_(entry_count), current_entry_count_(0u) {
CodedOutputStream coded_out(out_);
// 魔法數據,kContainerFormatMagic = 0x54504141u
coded_out.WriteLittleEndian32(kContainerFormatMagic);
// 版本號,kContainerFormatVersion = 1u
coded_out.WriteLittleEndian32(kContainerFormatVersion);
// 容器中包含的條目數 total_entry_count_是在ContainerReader構造時賦值,值由外部傳入
coded_out.WriteLittleEndian32(static_cast<uint32_t>(total_entry_count_));
if (coded_out.HadError()) {
error_ = "failed writing container format header";
}
}
調用ContainerWriter的AddResFileEntry方法,寫入資源項內容。
// file:protobuf格式的信息文件,in:原始文件
bool ContainerWriter::AddResFileEntry(const pb::internal::CompiledFile& file, io::KnownSizeInputStream* in) {
// 判斷條目數量,大於設定數量就直接報錯
if (current_entry_count_ >= total_entry_count_) {
error_ = "too many entries being serialized";
return false;
}
// 條目++
current_entry_count_++;
constexpr const static int kResFileEntryHeaderSize = 12; 、
//輸出流
CodedOutputStream coded_out(out_);
//寫入資源類型
coded_out.WriteLittleEndian32(kResFile);
const ::google::protobuf::uint32
// ResourceFile 文件長度 ,該部分包含了當前文件的路徑,類型,配置等信息
header_size = file.ByteSize();
const int header_padding = CalculatePaddingForAlignment(header_size);
// 原始文件長度
const ::google::protobuf::uint64 data_size = in->TotalSize();
const int data_padding = CalculatePaddingForAlignment(data_size);
// 寫入數據長度,計算公式:kResFileEntryHeaderSize(固定12) + ResourceFile文件長度 + header_padding + 原始文件長度 + data_padding
coded_out.WriteLittleEndian64(kResFileEntryHeaderSize + header_size + header_padding + data_size + data_padding);
// 寫入文件頭長度
coded_out.WriteLittleEndian32(header_size);
// 寫入數據長度
coded_out.WriteLittleEndian64(data_size);
// 寫入“頭信息”
file.SerializeToCodedStream(&coded_out);
// 對齊
WritePadding(header_padding, &coded_out);
// 使用Copy之前需要調用Trim(至於為什么,其實也不太清楚,好在我們學習AAPT2,了解底層API的功能即可。如果有讀者知道,希望賜教)
coded_out.Trim();
// 異常判斷
if (coded_out.HadError()) {
error_ = "failed writing to output"; return false;
} if (!io::Copy(out_, in)) { //資源數據(源碼中也叫payload,可能是png,xml,或者XmlNode)
if (in->HadError()) {
std::ostringstream error;
error << "failed reading from input: " << in->GetError();
error_ = error.str();
} else {
error_ = "failed writing to output";
}
return false;
}
// 對其
WritePadding(data_padding, &coded_out);
if (coded_out.HadError()) {
error_ = "failed writing to output";
return false;
}
return true;
}
這樣,FLAT文件就完成寫入了,並且產物文件除了包含資源內容,還包含了文件名,路徑,配置等信息。
CompilePng
該方法和CompileFile流程上是類似的,區別在於會先對PNG圖片做處理(png優化和9圖處理),處理完成后在寫入FLAT文件。
static bool CompilePng(IAaptContext* context, const CompileOptions& options, const ResourcePathData& path_data, io::IFile* file, IArchiveWriter* writer, const std::string& output_path) {
//..省略部分校驗代碼
BigBuffer buffer(4096);
// 基本一樣的代碼,區別是type不一樣
ResourceFile res_file;
res_file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
res_file.config = path_data.config;
res_file.source = path_data.source;
res_file.type = ResourceFile::Type::kPng;
{
// 讀取資源內容到data中
auto data = file->OpenAsData();
// 讀取結果校驗
if (!data) {
context->GetDiagnostics()->Error(DiagMessage(path_data.source) << "failed to open file ");
return false;
}
// 用來保存輸出流
BigBuffer crunched_png_buffer(4096);
io::BigBufferOutputStream crunched_png_buffer_out(&crunched_png_buffer);
// 對PNG圖片做優化
const StringPiece content(reinterpret_cast<const char*>(data->data()), data->size());
PngChunkFilter png_chunk_filter(content);
std::unique_ptr<Image> image = ReadPng(context, path_data.source, &png_chunk_filter);
if (!image) {
return false;
}
// 處理.9圖
std::unique_ptr<NinePatch> nine_patch;
if (path_data.extension == "9.png") {
std::string err;
nine_patch = NinePatch::Create(image->rows.get(), image->width, image->height, &err);
if (!nine_patch) {
context->GetDiagnostics()->Error(DiagMessage() << err); return false;
}
// 移除1像素的邊框
image->width -= 2;
image->height -= 2;
memmove(image->rows.get(), image->rows.get() + 1, image->height * sizeof(uint8_t**));
for (int32_t h = 0; h < image->height; h++) {
memmove(image->rows[h], image->rows[h] + 4, image->width * 4);
} if (context->IsVerbose()) {
context->GetDiagnostics()->Note(DiagMessage(path_data.source) << "9-patch: " << *nine_patch);
}
}
// 保存處理后的png到 &crunched_png_buffer_out
if (!WritePng(context, image.get(), nine_patch.get(), &crunched_png_buffer_out, {})) {
return false;
}
// ...省略部分圖片校驗代碼,這部分代碼會比較優化后的圖片和原圖片的大小,如果優化后比原圖片大,則使用原圖片。(PNG優化后是有可能比原圖片還大的)
}
io::BigBufferInputStream buffer_in(&buffer);
// 和 CompileFile 調用相同的方法,寫入flat文件,資源文件內容是
return WriteHeaderAndDataToWriter(output_path, res_file, &buffer_in, writer, context->GetDiagnostics());
}
AAPT2 對於 PNG 圖片的壓縮可以分為三個方面:
-
RGB 是否可以轉化成灰度;
-
透明通道是否可以刪除;
-
是不是最多只有 256 色(Indexed_color 優化)。
PNG優化,有興趣的同學可以看看
在完成PNG處理后,同樣會調用WriteHeaderAndDataToWriter來寫數據,這部分內容可閱讀上文分析,不再贅述。
CompileXml
該方法先會解析XML,然后創建XmlResource,其中包含了資源名,配置,類型等信息。通過FlattenXmlToOutStream函數寫入輸出文件。
static bool CompileXml(IAaptContext* context, const CompileOptions& options,
const ResourcePathData& path_data, io::IFile* file, IArchiveWriter* writer,
const std::string& output_path) {
// ...省略校驗代碼
std::unique_ptr<xml::XmlResource> xmlres;
{
// 打開xml文件
auto fin = file->OpenInputStream();
// ...省略校驗代碼
// 解析XML
xmlres = xml::Inflate(fin.get(), context->GetDiagnostics(), path_data.source);
if (!xmlres) {
return false;
}
}
//
xmlres->file.name = ResourceName({}, *ParseResourceType(path_data.resource_dir), path_data.name);
xmlres->file.config = path_data.config;
xmlres->file.source = path_data.source;
xmlres->file.type = ResourceFile::Type::kProtoXml;
// 判斷id類型的資源是否有id合法(是否有id異常,如果有提示“has an invalid entry name”)
XmlIdCollector collector;
if (!collector.Consume(context, xmlres.get())) {
return false;
}
// 處理aapt:attr內嵌資源
InlineXmlFormatParser inline_xml_format_parser;
if (!inline_xml_format_parser.Consume(context, xmlres.get())) {
return false;
}
// 打開輸出文件
if (!writer->StartEntry(output_path, 0)) {
context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to open file");
return false;
}
std::vector<std::unique_ptr<xml::XmlResource>>& inline_documents =
inline_xml_format_parser.GetExtractedInlineXmlDocuments();
{
// 和CompileFile 類似,創建可處理protobuf格式的writer,用於protobuf格式序列化
CopyingOutputStreamAdaptor copying_adaptor(writer);
ContainerWriter container_writer(©ing_adaptor, 1u + inline_documents.size());
if (!FlattenXmlToOutStream(output_path, *xmlres, &container_writer,
context->GetDiagnostics())) {
return false;
}
// 處理內嵌的元素(aapt:attr)
for (const std::unique_ptr<xml::XmlResource>& inline_xml_doc : inline_documents) {
if (!FlattenXmlToOutStream(output_path, *inline_xml_doc, &container_writer,
context->GetDiagnostics())) {
return false;
}
}
}
// 釋放內存
if (!writer->FinishEntry()) {
context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to finish writing data");
return false;
}
// 編譯選項部分,省略
return true;
}
在編譯XML方法中,並沒有像前面兩個方法那樣創建ResourceFile,而是創建了XmlResource,用於保存XML資源的相關信息,其結構包含如下內容:
在執行Inflate方法后,XmlResource 中會包含資源信息和XML的dom樹信息。InlineXmlFormatParser是用於解析出內聯屬性aapt:attr。
使用 AAPT 的內嵌資源格式,可以在同一 XML 文件中定義所有多種資源,如果不需要資源復用的話,這種方式更加緊湊。XML 標記告訴 AAPT,該標記的子標記應被視為資源並提取到其自己的資源文件中。屬性名稱中的值用於指定在父標記內使用內嵌資源的位置。AAPT 會為所有內嵌資源生成資源文件和名稱。使用此內嵌格式構建的應用可與所有版本的 Android 兼容。——官方文檔
解析后的FlattenXmlToOutStream 中首先會調用SerializeCompiledFileToPb方法,把資源文件的相關信息轉化成protobuf格式,然后在調用SerializeXmlToPb把之前解析的Element 節點信息轉換成XmlNode(protobuf結構,同樣定義在 Resources),然后再把生成XmlNode轉換成字符串。最后,再通過上文的AddResFileEntry方法添加到FLAT文件的資源項中。這里可以看出,通過XML生成的FLAT文件文件,存在一個FLAT文件中可包含多個資源項。
static bool FlattenXmlToOutStream(const StringPiece& output_path, const xml::XmlResource& xmlres,
ContainerWriter* container_writer, IDiagnostics* diag) {
// 序列化CompiledFile部分
pb::internal::CompiledFile pb_compiled_file;
SerializeCompiledFileToPb(xmlres.file, &pb_compiled_file);
// 序列化XmlNode部分
pb::XmlNode pb_xml_node;
SerializeXmlToPb(*xmlres.root, &pb_xml_node);
// 專程string格式的流,這里可以再找源碼看看
std::string serialized_xml = pb_xml_node.SerializeAsString();
io::StringInputStream serialized_in(serialized_xml);
// 保存到資源項中
if (!container_writer->AddResFileEntry(pb_compiled_file, &serialized_in)) {
diag->Error(DiagMessage(output_path) << "failed to write entry data");
return false;
}
return true;
}
protobuf格式處理的方法(SerializeXmlToPb)在ProtoSerialize.cpp中,其通過遍歷和遞歸的方式實現節點結構的復制,有興趣的讀者的可以查看源碼。
CompileTable
CompileTable函數用於處理values下的資源,從上文中可知,values下的資源在編譯時會被修改擴展為arsc。最終輸出的文件名為*.arsc.flat,效果如下圖:
在函數開始,會讀取資源文件,完成xml解析並保存為ResourceTable結構,然后在通過SerializeTableToPb將其轉換成protobuf格式的pb::ResourceTable,然后調用SerializeWithCachedSizes把protobuf格式的table序列化到輸出文件。
static bool CompileTable(IAaptContext* context, const CompileOptions& options,
const ResourcePathData& path_data, io::IFile* file, IArchiveWriter* writer,
const std::string& output_path) {
// Filenames starting with "donottranslate" are not localizable
bool translatable_file = path_data.name.find("donottranslate") != 0;
ResourceTable table;
{
// 讀取文件
auto fin = file->OpenInputStream();
if (fin->HadError()) {
context->GetDiagnostics()->Error(DiagMessage(path_data.source)
<< "failed to open file: " << fin->GetError());
return false;
}
// 創建XmlPullParser,設置很多handler,用於xml解析
xml::XmlPullParser xml_parser(fin.get());
// 設置解析選項
ResourceParserOptions parser_options;
parser_options.error_on_positional_arguments = !options.legacy_mode;
parser_options.preserve_visibility_of_styleables = options.preserve_visibility_of_styleables;
parser_options.translatable = translatable_file;
parser_options.visibility = options.visibility;
// 創建ResourceParser,並把結果保存到ResourceTable中
ResourceParser res_parser(context->GetDiagnostics(), &table, path_data.source, path_data.config,
parser_options);
// 執行解析
if (!res_parser.Parse(&xml_parser)) {
return false;
}
}
// 省略部分校驗代碼
// 打開輸出文件
if (!writer->StartEntry(output_path, 0)) {
context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to open");
return false;
}
{
// 和前面一樣,創建ContainerWriter 用於寫文件
CopyingOutputStreamAdaptor copying_adaptor(writer);
ContainerWriter container_writer(©ing_adaptor, 1u);
pb::ResourceTable pb_table;
// 把ResourceTable序列化為pb::ResourceTable
SerializeTableToPb(table, &pb_table, context->GetDiagnostics());
// 寫入數據項pb::ResourceTable
if (!container_writer.AddResTableEntry(pb_table)) {
context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to write");
return false;
}
}
if (!writer->FinishEntry()) {
context->GetDiagnostics()->Error(DiagMessage(output_path) << "failed to finish entry");
return false;
}
// ...省略部分代碼...
}
return true;
}
三、問題和總結
通過上文的學習,我們知道AAPT2是Android資源打包的構建工具,它把資源編譯分為編譯和鏈接兩個部分。其中,編譯是把不同的資源文件,統一編譯生成針對 Android 平台進行過優化的二進制格式(flat)。FLAT文件除了包含原始資源文件的內容,還有該資源來源,類型等信息,這樣一個文件中包含資源所需的所有信息,於其它依賴接耦。
在本文的開頭,我們有如下的問題:
Java文件需要編譯才能生.class文件,這個我能明白,但資源文件編譯到底是干什么的?為什么要對資源做編譯?
那么,本文的答案是:AAPT2的編譯時把資源文件編譯為FLAT文件,而且從資源項的文件結構可以知道,FLAT文件中部分數據是原始的資源內容,一部分是文件的相關信息。通過編譯,生成的中間文件包含的信息比較全面,可用於增量編譯。另外,網上的一些資料還表示,二進制的資源體積更小,且加載更快。
AAPT2通過編譯,實現把資源文件編譯成FLAT文件,接下來則通過鏈接,來生成R文件和資源表。由於篇幅問題,鏈接的過程將在下篇文章中分析。
四、參考文檔
3.https://booster.johnsonlee.io
作者:vivo互聯網前端團隊-Shi Xiang