I'm getting frustrated with having to load the same support libraries over and over again each time I start a new project. Is there to make sure they're always loaded when starting Android Studio?
Thanks.
[Edit] I just found a library from jack wharton doing what you are looking for. Check SDK Manager Plugin : https://github.com/JakeWharton/sdk-manager-plugin
It exists for some libraries. You have to check on building your projects with Graddle in Android-Studio :
Tips for Graddle
App generator with included libraries
Graddle Test project that loads it automatically (for example only)
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.13.+'
}
}
// Manifest version information!
def versionMajor = 1
def versionMinor = 0
def versionPatch = 0
def versionBuild = 0
apply plugin: 'com.android.application'
repositories {
jcenter()
}
dependencies {
compile 'com.android.support:support-v4:20.+'
compile 'com.android.support:support-annotations:20.+'
compile fileTree(dir: 'libs', include: ['*.jar'])
}
def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
def buildTime = new Date().format("yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"))
android {
compileSdkVersion 20
buildToolsVersion "19.1.0"
defaultConfig {
minSdkVersion 15
targetSdkVersion 20
versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild
versionName "${versionMajor}.${versionMinor}.${versionPatch}"
buildConfigField "String", "GIT_SHA", "\"${gitSha}\""
buildConfigField "String", "BUILD_TIME", "\"${buildTime}\""
}
signingConfigs {
release {
storeFile file(storeFilePath)
storePassword keystorePassword
keyAlias storeKeyAlias
keyPassword aliasKeyPassword
}
}
buildTypes {
debug {
applicationIdSuffix '.dev'
versionNameSuffix '-dev'
}
release {
signingConfig signingConfigs.release
}
}
lintOptions {
abortOnError false
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
You can set Android Studio to work offline if have loaded the supported libraries once;
Open Setting menu and search Gradle as keywords check on the Offline work :
Do remember to uncheck the checkbox if you have changed the your dependency in build.gradle
Related
I've followed the Detox guide for Android here to install on my react-native project - https://github.com/wix/Detox/blob/master/docs/Introduction.Android.md. But after running react-native run-android to build the app. I get the following error evaluating project :detox:
1: Task failed with an exception.
-----------
* Where:
Build file 'C:\Users\brian\Documents\Projects\react-native-prototyping\node_modules\detox\android\detox\build.gradle' line: 2
* What went wrong:
A problem occurred evaluating project ':detox'.
> Could not initialize class org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSetKt
I've looked in their issue tracker but didn't see a related issue. Looking at similar issues around Kotlin it seems it could be a conflict between my kotlin and gradle version. But I'm not sure how to determine the correct versions to use. I also did a ./gradlew clean in the android folder to no avail.
Question:
How can you resolve 'Could not initialize class ..sources.DefaultKotlinSourceSetKt' error?
Some details of my gradle and package setup are as follows:
"devDependencies": {
"detox": "^16.5.0",
},
root build.gradle:
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 18
compileSdkVersion = 28
targetSdkVersion = 28
kotlinVersion = '1.3.0'
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:3.5.2")
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
app/build.gradle:
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.testapp"
minSdkVersion rootProject.ext.minSdkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
// detox automated tests config
// This will later be used to control the test apk build type
testBuildType System.getProperty('testBuildType', 'debug')
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
release {
storeFile file(System.getenv("KEYSTORE") ?: "keystore.jks")
storePassword System.getenv("KEYSTORE_PASSWORD")
keyAlias System.getenv("KEY_ALIAS")
keyPassword System.getenv("KEY_PASSWORD")
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.release
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
// Detox-specific additions to pro-guard
proguardFile "${rootProject.projectDir}/../node_modules/detox/android/detox/proguard-rules-app.pro"
}
}
packagingOptions {
pickFirst "lib/armeabi-v7a/libc++_shared.so"
pickFirst "lib/arm64-v8a/libc++_shared.so"
pickFirst "lib/x86/libc++_shared.so"
pickFirst "lib/x86_64/libc++_shared.so"
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
androidTestImplementation(project(path: ":detox"))
}
Turns out I had to change my kotlin version in build.gradle to match my gradle version - buildscript. See - https://github.com/wix/Detox/blob/master/examples/demo-react-native/android/build.gradle
{
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 18
compileSdkVersion = 28
targetSdkVersion = 28
kotlinVersion = '1.3.41'
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:3.5.2")
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
This answer helped me. I needed to update my version of Kotlin.
Tools -> Kotlin -> Configure Kotlin Plugin Updates -> Check for updates now
Once it was updated I changed the version in build.gradle (project) to match the newly updated version. i.e.
buildscript {
ext {
kotlin_version = '1.3.72'
...
}
}
I have 2 questions regarding this issue.
if in laravel/web we have .env file to set environment to "development" or production and automatically connect to different database. how about in android/kotlin/android studio?
and how to make my application request to my localhost (127.0.2.1) on PC if it's in "development" environment and request to real url API if it's in "production" environment. FYI, I dont use emulator. I use my phone to test my application.
Yes this is possible in your Android application as well. You just have to modify your build.gradle file to manage your BuildConfig based on your dev, test or production environment.
Here's a sample build.gradle file from one of my project.
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
def keystorePropertiesFile = rootProject.file("../Path_To_KeyStore/keystore.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
def appPropertiesFile = rootProject.file("app-settings.properties")
def appProperties = new Properties()
appProperties.load(new FileInputStream(appPropertiesFile))
android {
compileSdkVersion 27
buildToolsVersion "27.0.3"
signingConfigs {
MyAppSigningConfig {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
defaultConfig {
applicationId "com.example.myapp"
minSdkVersion 21
targetSdkVersion 27
versionCode appProperties['app.version.code'] as int
versionName appProperties['app.version.name']
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
def buildVariant = getBuildVariant()
def environmentPath
if ((buildVariant == "Release")) {
environmentPath = appProperties["env.path.live"]
} else if ((buildVariant == "Debug")) {
environmentPath = appProperties["env.path.test"]
} else {
environmentPath = appProperties["env.path.live"]
}
def envPropertiesFile = rootProject.file(environmentPath)
def envProperties = new Properties()
envProperties.load(new FileInputStream(envPropertiesFile))
println("buildVariant = $buildVariant")
for (String key : envProperties.keySet()) {
buildConfigField "String", key.replaceAll("\\.", "_").toUpperCase(), envProperties[key]
}
}
buildTypes {
debug {
applicationIdSuffix ".debug"
manifestPlaceholders = [appName: "#string/app_name_debug_test"]
}
release {
manifestPlaceholders = [appName: "#string/app_name"]
signingConfig signingConfigs.MyAppSigningConfig
minifyEnabled false
multiDexEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
def getBuildVariant() {
for (TaskExecutionRequest t : gradle.getStartParameter().getTaskRequests()) {
for (String command : t.args) {
if (command.matches(":app:generate(.*)Sources")) {
return command.replaceAll(":app:generate(.*)Sources", "\$1")
} else if (command.matches(":app:assemble(.*)")) {
return command.replaceAll(":app:assemble(.*)", "\$1")
}
}
}
return "Release"
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:recyclerview-v7:27.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
I have two different build variants here. One is for release and the other is for debug. And I have three properties file in the application directory. These are as follows.
The app-settings.properties file looks like this.
app.version.code=1
app.version.name=0.0.1
env.path.live=live-env.properties
env.path.test=test-env.properties
The test-env.properties looks like
base.url.auth="http://localhost:8888/auth/"
base.url.communication="http://localhost:8000/communication/"
base.url.site="http://localhost:8000/"
api.key.auth="demo_key"
And the live-env.properties is like
base.url.auth="http://auth.yourapp.com/auth/"
base.url.communication="http://yourapp.com/communication/"
base.url.site="http://yourapp.com/"
api.key.auth="live_key1223ssHHddSSYYY"
So once the build.gradle and the application properties are setup, you need to sync with gradle to generate the BuildConfig.java file. You will see the file is generated automatically with the values found from your properties file.
From anywhere in your code, you might access the environment variables like the following.
const val BASE_URL = BuildConfig.BASE_URL_SITE
const val BASE_URL_AUTH = BuildConfig.BASE_URL_AUTH
Get the desired application build from the left side menu of build variants in Android Studio.
One of my colleague named Sajid Shahriar helped me to understand the setup for different build variants. Hence, I am sharing this with you. Hope that helps.
Add inside inside app level build.gradle file
android {
flavorDimensions "full"
productFlavors {
production {
versionCode 17
versionName "1.1.0"
dimension "full"
}
develop {
applicationId "dev.kadepay.app"
versionCode 17
versionName "1.1.0"
dimension "full"
}
}
if set up different package name
Add this line
applicationId "dev.kadepay.app"
and after sync build check build variants
The following build.gradle code for my main or launcher module is not updating the versionCode to 2. When I try to update the apk in Google Play the website tells me the apk uploaded is still version 1. Anyone knows what the problem is? I did download and modify some existing code, so I'm not aware of all the build scripts. I'm not looking to auto increment the version code. At line 24 I code versionCode 2.
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
repositories {
maven { url 'https://maven.fabric.io/public' }
}
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
//Keep old ITEC package name as application Id for Play Store compatibility
// applicationId 'at.aau.itec.android.mediaplayerdemo'
// applicationId "com.gregmarsh.AndroidVideoCapture.VideoMetronome"
applicationId "com.gregmarsh.AndroidVideoCapture.WCSDanceOnTimePro"
minSdkVersion 16
targetSdkVersion 22
versionCode 2
versionName '1.1'
// versionCode 3
// versionName "1.2"
// //applicationId "com.exercise.com.exercise.AndroidVideoCapture.AndroidVideoCapture"
// applicationId "com.gregmarsh.AndroidVideoCapture.VideoMetronome"
// minSdkVersion 16
// targetSdkVersion 22
// // versionCode 1 Name "1.0" 10/28/2015 Initial release
// // versionCode 2 Name "1.1" 1/4/2016 Recorded video listed in gallery
// // versionCode 3 Name "1.2" 4/3/2016 Flash & beat sync adjusted, recording stops on phone call.
// versionCode 3
// versionName "1.2"
buildConfigField "boolean", "CRASHLYTICS_CONFIGURED", "${isChrashlyticsConfigured()}"
}
signingConfigs {
debug // configured in signingconfig.gradle
release // configured in signingconfig.gradle
}
buildTypes {
debug {
applicationIdSuffix ".debug"
versionNameSuffix "-debug"
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
if (variant.name == android.buildTypes.release.name) {
def file = output.outputFile
def fileName = file.name.replace(".apk", "-" + defaultConfig.versionCode + "-" + defaultConfig.versionName + ".apk")
output.outputFile = new File(file.parent, fileName)
}
}
}
lintOptions {
// Lint fix for Okio: https://github.com/square/okio/issues/58
warning 'InvalidPackage'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':MediaPlayer')
compile project(':MediaPlayer-DASH')
compile('com.crashlytics.sdk.android:crashlytics:2.5.6#aar') {
transitive = true;
}
compile 'com.android.support:appcompat-v7:22.2.1'
}
ext.isLibrary = false
apply from: "../gitversioning.gradle"
apply from: "signingconfig.gradle"
if (isChrashlyticsConfigured()) {
apply plugin: 'io.fabric'
}
def isChrashlyticsConfigured() {
return file("fabric.properties").exists()
}
I am trying to launch my android application in debug mode, but everytime I check BuildConfig.DEBUG it says it is false. Even further, a buildconfigField defined in my buildtypes does not even show up in BuildConfig.
Here is my gradle file:
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.22.0'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
repositories {
maven {
url 'https://maven.fabric.io/public'
}
}
def versionMajor = 1
def versionMinor = 2
def versionPatch = 41
def versionBuild = 0 // bump for dogfood builds, public betas, etc.
android {
compileOptions.encoding = 'ISO-8859-1'
compileSdkVersion 21
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.name"
minSdkVersion 17
targetSdkVersion 21
buildConfigField 'Boolean', 'enableCrashlytics', 'false'
multiDexEnabled true
versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild
versionName "${versionMajor}.${versionMinor}.${versionPatch}.${versionBuild}"
}
signingConfigs {
release {
// release stuff
}
}
buildTypes {
android {
release {
debuggable false
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
buildConfigField 'Boolean', 'enableCrashlytics', 'true'
}
debug {
buildConfigField 'Boolean', 'enableCrashlytics', 'false'
debuggable true
minifyEnabled false
applicationIdSuffix ".debug"
}
}
}
sourceSets {
main {
res.srcDirs = ['src/main/res', 'src/main/res/xml']
}
}
dexOptions {
incremental true
javaMaxHeapSize "2048M"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
lintOptions {
checkReleaseBuilds false
abortOnError false
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.1.1'
// ... some other libs
compile('com.crashlytics.sdk.android:crashlytics:2.6.6#aar') {
transitive = true;
}
}
So in Android Studio I chooseBuild Variant "debug" for my app, but when I hit a breakpoint in the application and check the values of BuildConfig, the filed enableCrashlytics cant be resolved and the value of BuildConfig.BUILD_TYPE is "release".
What am I doing wrong?
This may happen if the code is in a library, there are multiple BuildConfig classes in a project, one per module, and only the main app one will be updated as expected.
If you want to have a proper BuildConfig.BUILD_TYPE across the app, you'd need to have debug/release build types on all your modules' gradle files, and trickle down the selected build-type from the main gradle file to the dependencies.
I want to create smth like this in my project, but i'm new to gradle, so i don't know a lot of things it can do.
Here is project structure in explorer
gradle.build from app module
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.7'
}
}
// Manifest version information!
def versionMajor = 1
def versionMinor = 0
def versionPatch = 0
def versionBuild = 0 // bump for dogfood builds, public betas, etc.
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
repositories {
mavenCentral()
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}
def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
def date = new Date()
def buildTime = date.format("dd.MM.yy", TimeZone.getTimeZone("UTC"))
def buildTimeInternal = date.format("yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"))
android {
compileSdkVersion rootProject.compileSdkVersion
buildToolsVersion rootProject.buildToolsVersion
defaultConfig {
minSdkVersion rootProject.minSdkVersion
targetSdkVersion rootProject.targetSdkVersion
versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild
versionName "${versionMajor}.${versionMinor}.${versionPatch}"
buildConfigField "String", "GIT_SHA", "\"${gitSha}\""
buildConfigField "String", "BUILD_TIME", "\"${buildTimeInternal}\""
testApplicationId "ru.ltst.u2020mvp.tests"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
signingConfigs {
debug {
storeFile file("../distribution/debug.keystore")
storePassword "android"
keyAlias "androiddebugkey"
keyPassword "android"
}
release {
storeFile file("../distribution/debug.keystore")
storePassword "android"
keyAlias "androiddebugkey"
keyPassword "android"
}
}
buildTypes {
debug {
applicationIdSuffix '.dev'
versionNameSuffix '-dev'
debuggable true
signingConfig signingConfigs.debug
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), file('proguard-project.txt')
signingConfig signingConfigs.release
}
}
productFlavors {
internal {
applicationId 'ru.ltst.u2020mvp.internal'
}
production {
applicationId 'ru.ltst.u2020mvp'
}
}
lintOptions {
textReport true
textOutput 'stdout'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
packagingOptions {
exclude 'LICENSE.txt'
}
}
// TODO remove eventually: http://b.android.com/162285
configurations {
internalDebugCompile
}
dependencies {
compile 'com.android.support:support-v4:23.0.1'
compile 'com.android.support:support-annotations:23.0.1'
compile "com.android.support:appcompat-v7:23.0.1"
compile 'com.android.support:recyclerview-v7:23.0.1'
compile 'com.android.support:cardview-v7:23.0.1'
compile 'com.google.dagger:dagger:2.0.1'
apt 'com.google.dagger:dagger-compiler:2.0'
provided 'org.glassfish:javax.annotation:10.0-b28'
compile 'com.squareup.okhttp:okhttp:2.3.0'
compile 'com.squareup.picasso:picasso:2.5.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
internalDebugCompile 'com.squareup.retrofit:retrofit-mock:1.9.0'
compile 'com.jakewharton:butterknife:6.1.0'
compile 'com.jakewharton.timber:timber:2.7.1'
internalDebugCompile 'com.jakewharton.madge:madge:1.1.1'
internalDebugCompile 'com.jakewharton.scalpel:scalpel:1.1.1'
compile 'io.reactivex:rxjava:1.0.8'
compile 'io.reactivex:rxandroid:0.24.0'
internalCompile 'com.mattprecious.telescope:telescope:1.4.0#aar'
// Espresso 2 Dependencies
androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
androidTestCompile ('com.android.support.test.espresso:espresso-contrib:2.0') {
exclude module: 'support-annotations'
}
}
// change apk name
android.applicationVariants.all { variant ->
for (output in variant.outputs) {
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
def fileName = "u2020-mvp-${output.name}-${buildTime}.apk"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
// print build finish time
gradle.buildFinished { buildResult ->
def buildFinishDate = new Date()
def formattedDate = buildFinishDate.format('yyyy-MM-dd HH:mm:ss')
println "Build finished: ${formattedDate}"
}
Can someone explain to me how it works?
When i change build Variant the java content is changed. (e.g it was main, internal,internalDebug for internalDebug variant and then it became main,internal,internalRelease for internalRelease build variants).
The reason I'm asking is that i don't see any "internalRelease" word in gradle file, so i don't understand the logic of how the build variants were created and how it defines what modules to show for different build variants
debug for test without signature and release for publish with signature;click the left-top robot ,and turn android to project , u will understand;