Android项目内build.gradle
task runAndroidApplication(type: Exec, dependsOn: ':installDebug') {
//TODO update Activity name below or find a way to get it from AndroidManifest.xml
if (System.properties['os.name'].toLowerCase().contains('windows')) {
// windows
commandLine 'cmd', '/c', 'adb', 'shell', 'am', 'start', '-n', "com.example.androidapptorun.MainActivity"
} else {
// linux
commandLine 'adb', 'shell', 'am', 'start', '-n', "com.example.androidapptorun.MainActivity"
}
}
如何从AndroidManifest获取默认Activity的主Activity值? (如果有几个活动,选择一个的逻辑会使它变长, 处理是在Android工具中进行的)
有没有更好的方法从Android插件然后解析AndroidManifest.xml
?
更新:https://github.com/novoda/gradle-android-command-plugin可能适合某些需求,但我需要无参数版本才能通过http://marketplace.eclipse.org/content/gradle
在Eclipse中快速运行答案 0 :(得分:11)
您可以使用XmlSlurper
课程。
示例:
的AndroidManifest.xml
<manifest package="com.example.your.app">
并在gradle中检索
def manifest = new XmlSlurper().parse(file("AndroidManifest.xml"))
// returns "com.exmaple.your.app"
manifest.@package.text()
答案 1 :(得分:6)
我刚为ADT 20(L),Gradle 1.12和com.android.tools.build:gradle:0.12.2
写了这个。
它适用于口味,构建类型(不要忘记myBuildType.initWith(existingBuildType)
)和applicationIdSuffix
。
将以下内容放在android { ... }
:
applicationVariants.all { variant ->
if (variant.install) {
tasks.create(name: "run${variant.name.capitalize()}", type: Exec, dependsOn: variant.install) {
description "Installs the APK for ${variant.description}, and then runs the main launcher activity."
def getMainActivity = { file ->
new XmlSlurper().parse(file).application.activity.find{ it.'intent-filter'.find{ filter ->
return filter.action .find{it.@name.text() == 'android.intent.action.MAIN'} \
&& filter.category.find{it.@name.text() == 'android.intent.category.LAUNCHER'}
}}.@name
}
doFirst {
def activityClass = getMainActivity(variant.processManifest.manifestOutputFile)
commandLine android.adbExe, 'shell', 'am', 'start', '-n', "${variant.packageName}/${activityClass}"
}
}
}
}
对于图书馆,您需要将applicationVariants
更改为libraryVariants
:请参阅manual。
更新:ADT 20,Gradle 2.1和com.android.tools.build:gradle:0.13.1
:
applicationVariants.all { variant ->
if (variant.install) {
tasks.create(name: "run${variant.name.capitalize()}", type: Exec, dependsOn: variant.install) {
description "Installs the APK for ${variant.description}, and then runs the main launcher activity."
def getMainActivity = { file ->
new XmlSlurper().parse(file).application.activity.find{ it.'intent-filter'.find{ filter ->
return filter.action .find{it.'@android:name'.text() == 'android.intent.action.MAIN' } \
&& filter.category.find{it.'@android:name'.text() == 'android.intent.category.LAUNCHER'}
}}.'@android:name'
}
doFirst {
def activityClass = getMainActivity(variant.outputs.processManifest.manifestOutputFile)
commandLine android.adbExe, 'shell', 'am', 'start', '-n', "${variant.applicationId}/${activityClass}"
// or without the XML hacking: commandLine android.adbExe, 'shell', 'monkey', '-p', variant.applicationId, '1'
}
}
}
}