python調用aapt工具直接獲取包名和tagertSdkversion


背景:

每次海外游戲上架都需要符合google的上架規則,其中適配方面tagetSdkversion有硬性要求,比如需要適配安卓q就需要tagetSdkversion達到28,水平太渣的我每次調用aapt工具都需要在cmd中輸入大量指令,且aapt dump baging指令會返回大量相關以及無關信息,為了方便過濾相應信息,編寫代碼直接獲取相關信息,排除無關信息

以劍網3指尖江湖的安裝包為例

若直接使用aapt工具,返回信息如下圖所示

思路:

re模塊使用正則表達式過濾無關信息,os模塊調用環境變量中的ANDROID_HOME,subprocess創建一個新的進程讓其執行另外的程序,並與它進行通信,獲取標准的輸入、標准輸出、標准錯誤以及返回碼等。 

我們實際需要的相關信息紅框部分,其余都是無關信息,所以需要re模塊去過濾出相關信息

代碼:

# -*- coding: utf-8 -*-
import re
import subprocess
import os

class ApkInfo: def __init__(self, apk_path): self.apkPath = apk_path self.aapt_path = self.get_aapt() @staticmethod def get_aapt(): if "ANDROID_HOME" in os.environ: root_dir = os.path.join(os.environ["ANDROID_HOME"], "build-tools") for path, subdir, files in os.walk(root_dir): if "aapt.exe" in files: return os.path.join(path, "aapt.exe") else: return "ANDROID_HOME not exist" def get_apk_base_info(self): p = subprocess.Popen(self.aapt_path + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) (output, err) = p.communicate() match = re.compile("package: name='(\S+)'").match(output.decode()) if not match: raise Exception("can't get packageinfo") package_name = match.group(1) return package_name def get_apk_activity(self): p = subprocess.Popen(self.aapt_path + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) (output, err) = p.communicate() match = re.compile("launchable-activity: name='(\S+)'").search(output.decode()) if match is not None: return match.group(1) def get_apk_sdkVersion(self): p = subprocess.Popen(self.aapt_path + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) (output, err) = p.communicate() match = re.compile("sdkVersion:'(\S+)'").search(output.decode()) return match.group(1) def get_apk_targetSdkVersion(self): p = subprocess.Popen(self.aapt_path + " dump badging %s" % self.apkPath, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) (output, err) = p.communicate() match = re.compile("targetSdkVersion:'(\S+)'").search(output.decode()) return match.group(1) if __name__ == '__main__': apk_info = ApkInfo(r"apk文件路徑") print("Activity:%s"%apk_info.get_apk_activity()) print("apkName:%s"%apk_info.get_apk_base_info()) print("sdkVersion:%s"%apk_info.get_apk_sdkVersion()) print("targetSdkVersion:%s"%apk_info.get_apk_targetSdkVersion())

 在pycharm中直接運行,結果如下圖所示

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM