android 改python,如何正确的用python修改AndroidManifest.xml(史上最详细教程)
寫在前面的話
AndroidManifest.xml這個文件如果你搞過android相關的東西(如果沒搞過,我希望你去搞一下), 你一定很熟悉. 我們在工作可能會有一些動態修改或者獲取manifest里面的值的情況, 那么今天濤哥就帶你研究一下.
開始寫腳本
準備
我們把腳本放到跟AndroidManifest.xml同級的目錄
下面我們來看一下manifest的基本結構
package="com.test.me"
android:versionCode="481"
android:versionName="3.1.1">
android:name=".Application"
android:icon="@drawable/icon"
android:label="@string/app_name" >
android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name"
android:screenOrientation="landscape" >
android:name="com.test.TestService"
android:exported="true"
android:process=":DownloadingService" >
因為manifest是一個xml文件. 所以我們就得需要用到能解析xml的庫. 這里面我們使用xml.etree.cElementTree庫
import xml.etree.cElementTree as ET #引用庫,并簡寫成ET
#變量
SPACE = '{http://schemas.android.com/apk/res/android}' #這個后面會講
打開AndroidManifest.xml
curPath = os.getcwd() + '/' #獲取當前目錄的絕對路徑
tree = ET.parse(curPath + 'AndroidManifest.xml') #打開xml
root = tree.getroot() #找到manifest的根文件
print(root.tag) #我們輸出一下就知道root目錄就是manifest目錄
print(root.attrib) #輸出一下root目錄的成員
我們來看一下root.attrib的輸出:
{'{http://schemas.android.com/apk/res/android}versionName': '1.0', '{http://schemas.android.com/apk/res/android}versionCode': '1', 'package': 'com.carrot.iceworld.channel'}
在versionName和versionCode前面的是什么? 沒錯, 就是我們上面配置的SPACE,所以如果我們要想正確的獲取到值,別忘了加上.
獲取和修改versionName和versionCode
通過上面我們可以看到, versionName和versionCode都是屬于manifest根目錄的成員
#獲取
versionName = root.get(SPACE + 'versionName')
versionCode = root.get(SPACE + 'versionCode')
#修改
root.set(SPACE + 'versionName', '9.9.9')
root.set(SPACE + 'versionCode', '999')
#寫入
tree.write('manifest的絕對路徑')
處理權限
因為權限屬性(uses-permission)在manifest一級子屬性
for child in root.iter('uses-permission'):
#1.輸出所有權限
print(child.get(SPACE + 'name'))
#2.刪除某一個權限
if (child.get(SPACE + 'name') == 'android.permission.INTERNET'):
root.remove(child)
#3.增加一個新權限, 我們要新建一個xml的element, 然后按照格式制造一個新的permission, 插入到原manifest里
permission = ET.Element('uses-permission')
permission.set(SPACE + 'name', 'android.permission.INTERNET')
root.insert(-1, permission) #為了方便插入都最后了
處理activity
因為activity不是manifest的一級子屬性, 而是application的子屬性
#1.先獲取application目錄
application = root.find('application')
#2.遍歷所有activity, 打印name
for item in application.iter('activity'):
print(item.attrib.get(SPACE + 'name'))
#3.增加一個新的activity
activity = ET.Element('activity')
activity.set(SPACE + 'name', "com.test.MainActivity")
activity.set(SPACE + 'configChanges', "keyboardHidden|orientation|screenSize")
application.insert(-1, activity)
處理meta和service
meta和service因為跟acitity是同級的, 所以處理方法一樣, 我就不贅述了
總結
其實如果你搞明白了,manifest的本質是xml, 然后知道如何用python操作xml, 那么這個問題就變得很簡單
參考
總結
以上是生活随笔為你收集整理的android 改python,如何正确的用python修改AndroidManifest.xml(史上最详细教程)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 撒撇是什么?
- 下一篇: 树莓派python编程案例-树莓派Pyt