Create custom test folder with android studio - android

So far I have the two default folders:
src/test
src/androidTest
I would like to add a new one to write other tests that will. To do so I've created the folder:
src/deviceIntegrationTest
And added in gradle:
android{
// ...
sourceSets {
deviceIntegrationTest{
java.srcDirs = [
'src/main/java',
'src/deviceIntegrationTest/java',
'src/deviceIntegrationTest/java/'
]
}
}
}
But android studio does not list this folder when I use the Android project view. And I cannot add java class neither..
Is it possible to do want I want ?

try to change your code like that :
sourceSets{
integrationTest {
java {
srcDirs = [
'src/main/java',
'src/iotizeDeviceIntegrationTest/java',
'src/iotizeDeviceIntegrationTest/java/'
]
}
}
}

Related

Android Studio does not show the res directory

I have an Android project checked out in Android Studio (4.0.1). The build.gradle contains the following sourceSets block (snippet shown below). It is meant to prevent certain values resource files from being included in the packaged aar (I only want to include values-en-rUS and values-es-rUS in the aar).
The aar gets packaged correctly and contains only values-en-rUS and values-es-rUS, as expected.
sourceSets {
main {
def resSrc = fileTree(dir: 'src/main/res').matching { exclude { details ->
(!details.file.canonicalPath.matches('.*values-(en|es)-rUS.*')
&& details.file.canonicalPath.matches('.*values-.*'))
} }
...
res.srcDirs = [ resSrc ]
...
}
}
However, Android Studio does not show me the res directory (the entire directory!) anymore in the "Project" sidebar when "Android" is selected, and the Java code files can no longer resolve the ids or layouts (e.g. findViewById(R.id.bottom_sheet_layout) -- they show as red squiggly lines).
How can I make it so that Android Studio continues to show the res directory in this case?
Thanks.
Try this:
sourceSets {
main {
def resSrc = fileTree(dir: 'src/main/res').matching { exclude { details ->
(!details.file.canonicalPath.matches('.*values-(en|es)-rUS.*')
&& details.file.canonicalPath.matches('.*values-.*'))
} }
res.srcDirs = [resSrc, 'src/main/res']
}
}
Note: If two or more resource directories contain the same resource file, an error occurs during resource merging.
For more information: https://developer.android.com/studio/write/add-resources

Gradle: how to specify two sourcesets of library and add dependency in project

I try to specify two different sourcesets of a gradle library and add a sourceset specific dependency in a project.
The idea is to do something like this:
The library build.gradle file:
apply plugin: 'com.android.library'
android {
...
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java {
srcDir 'src'
}
res {
srcDir 'res'
}
}
exclude_fr_it{
manifest.srcFile 'AndroidManifest.xml'
java {
srcDir 'src'
}
res {
srcDir 'res'
exclude 'res/values/values-fr'
exclude 'res/values/values-it'
}
}
}
...
}
...
In the Project A, I want to include the main sourceset:
dependencies {
compile project(':explore_layout')
}
In the Project B, I want to include the build that use sourceset exclude_fr_it.
dependencies {
compile project(':explore_layout') library 'exclude_fr_it'
}
I tried to understand the documentation. But I don't see how this can be done...
Question 1
Doc
Question 2
This is not a direct answer to the sourceSets question. But you may not need to use the sourceSets feature at all.
If you simply want your app to include a subset of the resources in your custom android library, you can accomplish that with a configuration block in your app's build.gradle. (In fact, the library does not need those special configuration blocks for the 'main' and 'exclude_fr_it' sourceSets at all.)
This is possible because of the 'resConfigs' property.
In particular, suppose your library has resource configurations for three languages: 'en', 'fr', and 'it'.
Then, in project A, which includes all of the languages from the library, you simply use this in build.gradle:
dependencies {
compile project(':explore_layout')
}
But, in project B, which you want to exclude the custom library's 'fr' and 'it' resources, you use the 'resConfigs' property within a configuration closure to include only a subset of resources like this:
dependencies {
compile project(':explore_layout') {
android {
defaultConfig {
resConfigs 'en'
}
}
}
}
I have achieved this using distribution to mavenLocal of a specific sources specification. I have a library project that has some java.awt code that I want to omit so I can include the project as dependency to an android project (which doesnt support java.awt)
In your library you will have something like this:
apply plugin: 'java'
apply plugin: 'java-library'
apply plugin: 'maven-publish'
sourceSets {
main {
java {
srcDirs = [ 'src' ]
}
}
// android source set excludes portion of source that
// references java.awt
android {
java {
srcDirs = [ 'src' ]
excludes = ['**/skunkworks/**', '**/awt/**']
}
}
}
// this task compiles sources defined by custom sourceSet 'android'
task androidJar(type: Jar) {
from sourceSets.find {'android'}.output
}
publishing {
publications {
myLibrary(MavenPublication) {
groupId = 'foo.bar'
artifactId = 'mylib-android'
version = '1.0'
artifact androidJar
}
}
}
Then use the tasks->publishing->publishToMavenLocal target to compile the custom jar to your ~/.m2/repository.
Now in the android project I reference like this:
repositories {
mavenLocal()
}
dependencies {
implementation 'foo.bar:mylib-android:1.0'
}

How to extract specific folder contents from jar file using gradle

I am new in gradle and looking a Gradle task to extract some specific folder from dependency(jar file). I have created a nativelib folder under src/main/nativeLib and want to copy all native libraries which are inside of native jar.
Basically this native jar already added in my central repo and it contains native libs(.so files) inside a lib. I have added this native jar as dependencies in my gradle.build and now want to first extract all contents from this jar-->lib folder and place in nativelib and then set a jniLibs like this:
android {
sourceSets
{
main {
jniLibs.srcDirs = ['src/main/nativelib']
}
}
}
gradle dependencies:
dependencies {
compile 'com.hospitality.android:liblinphone-sdk-native:3.2.1'
}
Can someone help me out.
Try using this:
apply plugin: 'java'
apply plugin: 'application'
android {
sourceSets
{
main {
jniLibs.srcDirs = ['src/main/nativelib']
}
}
}
build.dependsOn(copyToLib)
task copyToLib(type: Copy) {
into "$buildDir/output/libs"
from configurations.runtime
}
see if this works and it copies to output/libs.

How to do resource filtering in Android plugin for Gradle?

I have the following in my android app
#MyAndroidApp/assets/app.properties
server=localhost
....
....
when building the app, I would like to change the value of 'server' from localhost to whatever is defined in gradle.properties.
The 'java' plugin allows me to do this
processResources {
def serverHostName = project.hasProperty("serverhost") ? project.property("serverhost") : "localhost"
filter ReplaceTokens, tokens: [
"serverhost": serverHostName
]
}
Similarly, I thought I could override processDebugResources and processReleaseResources in Android but unfortunately its not possible. Is there any other alternative way?
I checked out 'productFlavors' but it requires to define whole new project structure, all I want is to change a single property here.
Since I'm new to the gradle build system probably it is not the best solution, but it worked for me:
defaultConfig {
...
applicationVariants.all { variant ->
def serverHostName = project.hasProperty("serverhost") ? project.property("serverhost") : "localhost"
variant.mergeAssets.doLast {
copy {
from("${projectDir}/src/main/assets") {
include "*.properties"
}
into("${buildDir}/assets/${variant.dirName}")
filter(ReplaceTokens, tokens: [
"serverhost": serverHostName)
])
}
}
}
}

How to replace strings resources with Android Gradle

I made a new app with gradle in Android Studio, and now I need to make about 10 versions with different package names and values in resources. I made custom flavors as in example and want to replace some strings in this custom flavors with custom values. I found example like this:
filter(org.apache.tools.ant.filters.ReplaceTokens, tokens: ['version': '2.2'])
But i don't know where to put it. As i understand i need to put it into separate task, but how to make this task called by IDE?
Also i need to replace few variables inside Java classes and Content Provider's auth, maybe i need to do this by copy files into flavor1 folder and let gradle to merge it, but it seems like wrong solution to store many copies of files with difference in one line... Maybe i need to user some other solution for all this?
Here is build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4.2'
}
}
apply plugin: 'android'
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile project(':JazzyListView')
compile project(':ABS')
compile project(':Volley')
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
versionCode 5
versionName "3.0"
minSdkVersion 8
targetSdkVersion 17
}
sourceSets {
main {
manifest.srcFile 'src/main/AndroidManifest.xml'
java.srcDirs = ['src/main/java']
res.srcDirs = ['src/main/res']
}
}
productFlavors {
flavor1 {
packageName "com.example.flavor1"
}
flavor2 {
packageName "com.example.flavor2"
}
}
}
I had a similar problem. I wanted to add the Jenkins build number to the strings that get merged from strings.xml. Here's my solution as of Android Gradle plugin 0.12.+.
// Insert the build number into strings.xml
android.applicationVariants.all{ variant ->
variant.mergeResources.doLast{
ext.env = System.getenv()
def buildNumber = env.BUILD_NUMBER
if (buildNumber != null) {
File valuesFile = file("${buildDir}/intermediates/res/${variant.dirName}/values/values.xml")
println("Replacing revision number in " + valuesFile)
println("Build number = " + buildNumber)
String content = valuesFile.getText('UTF-8')
content = content.replaceAll(/devBuild/, buildNumber)
valuesFile.write(content, 'UTF-8')
}
}
}
You might want to hook into a different Gradle task depending on what you want to do. Take a look at the tasks that are part of the Android build to figure that out.
http://tools.android.com/tech-docs/new-build-system/user-guide
UPDATE: At some point, the Android Gradle plugin changed the way to iterate through application variants keyword from each to all. My answer has been updated to reflect the change, but try switching to each if this code doesn't print anything to the console.
I was trying to get similar functionality as Maven resource filtering.
This is what I came up with. My solution could use some changes to be more robust (i.e. pulling from a properties file, etc).
My example just shows how to replace a single value, which is all that I needed. The variables follow the ${some.property} convention. This solution also works with product flavors that have their own resource files.
import org.apache.tools.ant.filters.*
...
android.applicationVariants.all{ variant ->
// Perform resource filtering
variant.mergeResources.doLast {
filterResources(variant)
}
}
def filterResources(buildVariant) {
//Setup temp directory to filter the resources
File resFiltered = file("${buildDir}/res/all/filtered/${buildVariant.dirName}")
if(resFiltered.exists()){
resFiltered.delete()
}
//Copy and filter the resources.
copy {
from(buildVariant.processResources.resDir) {
include '**/*.xml'
//Could be improved upon to pull from a properties file, etc.
ant.properties['app.version'] = project.version
filter(ExpandProperties, project: ant.project)
}
from(buildVariant.processResources.resDir) {
exclude '**/*.xml'
}
into resFiltered
}
//Delete all the original resource files
file(buildVariant.processResources.resDir).deleteDir()
//Replace with the filtered ones.
resFiltered.renameTo(file(buildVariant.processResources.resDir))
//Delete the original 'filtered' directory
file( "${buildDir}/res/all/filtered").deleteDir()
}
Example in strings.xml
...
<string name="app_version">${app.version}</string>
...
These links may be helpful:
Using Gradle for building Android applications
Gradle Plugin User Guide
And my filter definition using regex to replace something:
from('res/') {
include '**/*.xml'
filter {
line -> line.replaceAll(/YOUR_REGEX_TO_REPLACE_SOMETHING/, 'REPLACED_RESULT_EXPRESSION')
}
}
into 'build/path/to/your/filtered/resources/'
In your "src" folder, create "flavor1" and "flavor2" folders with the same hierarchy as your "main" folder. If you have strings.xml in your main/res/values, you can do it in flavor1/res/values as well and have the replacement values in there. It may show errors in the IDE but it should still build and run.

Categories

Resources