How to add service in a library in android? - android-studio

I have a project with service which scans the Bluetooth devices in the range and when i get the signal it will broadcast the device details.
I want to create a library of that service so anyone can import my library and use it.
How can i do this ?

I got the solution
First make changes in the build.gradle
do the changes as show bellow
apply plugin: 'com.android.library'
android {
compileSdkVersion 22
buildToolsVersion "23.0.1"
defaultConfig {
minSdkVersion 19
targetSdkVersion 22
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:22.2.1'
}
task deleteOldJar(type: Delete){
delete 'release/customlib.jar'
}
task exportJar(type: Copy) {
from('/build/intermediates/bundles/release/')
into('/release/')
include('classes.jar')
//rename the file name as u want
rename('classes.jar','myLibrary.jar')
}
exportJar.dependsOn(deleteOldJar,build)
sync the project then click on the right menu bar gradle option u will
-MyLibrary
-:app/Task/Other/exportJar
here you will see exportJar double click on it will create a jar file after the build successful u can check the jar file at location /app/release/MyLibrary.jar

Your question is not very clear. For building a library, you must have source code for it. Once you have the library, a system service would attach that library with itself either at boot time or event-based. You need to be clear what you need to do. You can not add a service in a library rather it's the opposite.

Related

keep getting an error when I open android studio

I recently installed Android Studio and when ever I start a new Project no matter what I keep getting this error :
Could not GET 'https://jcenter.bintray.com/com/android/tools/build/gradle/4.2.0-beta03/gradle-4.2.0-beta03.pom'. Received status code 403 from server: Forbidden
Disable Gradle 'offline mode' and sync project.
and offline mode doesn't work either . I really ran out of ideas . if anyone can help me please do. thanks.
this is my build gradle :
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
and this is build.gradle :
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.0-beta03"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
and when I'm clicking on Offline mode this error appears :
A problem occurred configuring root project 'My Application'.
> Could not resolve all artifacts for configuration ':classpath'.
> Could not resolve com.android.tools.build:gradle:4.2.0-beta03.
Required by:
project :
> No cached version of com.android.tools.build:gradle:4.2.0-beta03 available for offline mode.
> No cached version of com.android.tools.build:gradle:4.2.0-beta03 available for offline mode.
Possible solution:
- Disable offline mode and rerun the build
The always working and best solution is to delete the full application with the sdk's if you have any projects take a backup of them and reinstall android studio. That's the most easiest way.
Try to disable gradle offline mode. You can find how to here: How to disable gradle 'offline mode' in android studio?. Then wait for gradle files to sync after restart.
Jcenter is no longer available.
You must replace all jcenter()s in you build.gradle with mavenCentral().
Also check your Internet connection(VPN) and proxies because it seems you have problems with your connection.

Kotlin compiler build error Recompile with -jvm-target 1.8

I am dealing with the same error described in the following questions, but all the solutions proposed didn't solve my problem.
Why kotlin gradle plugin cannot build with 1.8 target?
Android Studio throws build error in Kotlin project which calls static method in java interface
Intellij refuses to set the Kotlin target jvm to 1.8?
In my case there is a small difference. I am using Android Studio 3.5 and I recently upgraded the Kotlin version to 1.3.61 Initially I got the usual error message:
calls to static methods in Java interfaces are prohibited in JVM target 1.6. Recompile with '-jvm-target 1.8'
I changed File -> Settings -> Kotlin Compiler -> Target JVM Version and after this change it compiled without errors, but later when I tried to to deploy on the emulator the build failed again. So, when it builds the app it works, when it does the full build to deploy it fails, but in theory they are using the same configuration. When I click on settings within the gradle window, whatever the node is selected it opens the same window of the main settings. What can be the difference?
I checked all possible settings and configurations, I checked also the project structure and the build/run/debug templates, but I couldn't find other places where I could set the property.
I tried to set in the gradle build the JvmTarget, but with this Kotlin version the property does no longer exist. I thought about a download issue and I added mavenCentral to the repositories, but nothing changed. If something changed recently this page does not seem to be up to date:
https://kotlinlang.org/docs/reference/using-gradle.html
What else could I try? Why only the full build fails?
UPDATE:
For the moment I worked around the issue by adding non static methods, but it will cost in term of performance. So I hope a solution will pop out sooner or later. In the meanwhile I am adding the build file, although I don't think it will add a lot to the description of the issue:
//Originally the plugins were declared with the syntax "apply plugin ...."
//Changing to this form did not change the result
plugins {
id('com.android.application')
id('org.jetbrains.kotlin.android')
id('org.jetbrains.kotlin.android.extensions')
}
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId ..........
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
// Commented out because the property JvmTarget is not found with Kotlin 1.3.61
// compileReleaseKotlin {
// JvmTarget='1.8'
// }
// compileDebugKotlin {
// JvmTarget='1.8'
// }
lintOptions {
abortOnError false
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//I tried also JDK 7
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.core:core-ktx:1.0.2'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
//Follow other dependencies which are irrelevant
// ...
}
Update
Recent versions of Kotlin plugin allow you to put kotlinOptions inside the android block. Tested this with Kotlin 1.4.20 and Gradle 6.7.
android {
// ...
kotlinOptions {
jvmTarget = "1.8"
}
}
Original answer
Place this outside of the android block in your build.gradle file:
Gradle
compileKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
Gradle KTS
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
jvmTarget = "1.8"
}
}
Note the small j in jvmTarget and absence of variant names - this will apply to all build variants.
Make sure you are setting jvmTarget correctly:
For source, it would be:
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
For test, it would be:
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}

Why isn't .aab file added -free-release or -pro-release.apk suffix automatically when I use the same build.gradle in Android Studio?

I use the following build.gradle to generate .apk files, the result will be MagnifyingGlass-V1.01-free-release.apk for free edition and MagnifyingGlass-V1.01-pro-release.apk for pro edition. -free-release or -pro-release is added to filename as suffix automatically by Android Studio 3.4.2.
I try to use the same build.gradle to generate .aab files, I find the result is MagnifyingGlass-V1.01 for free and MagnifyingGlass-V1.01 for pro, there are same, why? -free-release or -pro-release isn't added to filename as suffix automatically by Android Studio 3.4.2.
Added content:
I generated different edition .apk and .aab using Android Studio just like Image 1.
build.gradle
android {
compileSdkVersion 28
flavorDimensions "default"
defaultConfig {
applicationId "info.dodata.magnifyingglass"
minSdkVersion 21
targetSdkVersion 28
versionCode 2
versionName "1.02"
archivesBaseName = "MagnifyingGlass-V" + versionName
}
productFlavors {
free {
applicationId "info.dodata.magnifyingglass"
}
pro {
applicationId "info.dodata.magnifyingglass.pro"
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "boolean", "IsDebugMode", "false"
}
debug {
buildConfigField "boolean", "IsDebugMode", "true"
}
}
}
Image 1
This is because the name of the bundle is being rigidly applied (there might be a relevant ticket available on the issue-tracker).
Once left a workaround here: How to change the generated filename for App Bundles with Gradle?
This approach can also be used to finalize these flavors, based upon their final task's name. Another optimization would be, to use the Apache Ant integration on the generated bundle. For some reason (unknown to me), Gradle does not support move (rename) operations out-of-the-box.
This configuration appears pretty useless (and there might be other configurations missing):
buildConfigField "boolean", "IsDebugMode", "true"
because in Java that is known as BuildConfig.DEBUG; better replace that with configuration applicationIdSuffix ".debug" - and also add the corresponding applicationIdSuffix ".release" (which rather sounds alike the intended outcome); for example:
buildTypes {
release {
applicationIdSuffix ".release"
...
}
debug {
applicationIdSuffix ".debug"
...
}
}
This is now available in gradle version 3.5.2 where the product flavor suffix is applied automatically.

Android Studio 2.3.3 stuck on Gradle Build Running

Using android studio 2.3.3 I've stuck on Gradle Build Running.
I don't have any idea and loss my mind to figure it out what happened with my project. Recently we want to compile Zoom Login Application Sample and following carefully from this link.
Here are Android Studio Version :
Android Studio 2.3.3
Build #AI-162.4069837, built on June 6, 2017
JRE: 1.8.0_31-b13 x86
JVM: Java HotSpot(TM) Server VM by Oracle Corporation
On event log, Grade seems working hard to finish this task
Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies]
I've tried to
Set Global Gradle Setting to Offline Work by followed this solution
Isn't using google play service like this solution suggest.
Not using proxy
Add org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 and org.gradle.parallel=true on gradle.properties project
On C:\Users\<username>\.gradle\gradle.properties add this line org.gradle.daemon=true and org.gradle.parallel=true
Every solution I tried but no one work well. This is silly and ridiculous, the build phase cannot be completed even I leave that for one night.
Here is project build.gradle :
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.facialnetwork.com/maven2'
credentials {
username '***'
password '***'
}
authentication {
basic(BasicAuthentication)
}
}
// Reference local .aar file if it doesn't exist in maven
flatDir{ dirs '../../../' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
and here module build.gradle
buildscript {
}
apply plugin: 'com.android.application'
android {
if (project.hasProperty("zoom_keystore")) {
signingConfigs {
release {
storeFile file(zoom_keystore)
storePassword zoom_keystore_password
keyAlias zoom_key_alias
keyPassword zoom_key_password
}
}
}
compileSdkVersion 25
buildToolsVersion '25.0.3'
defaultConfig {
applicationId "com.facetec.zoom.sampleapp"
minSdkVersion 18
targetSdkVersion 25
versionCode 1
versionName "1.0"
buildConfigField("String", "ZOOM_APP_TOKEN", System.getProperty("zoom_app_token", "\"\""))
resConfigs "en"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
if (signingConfigs.hasProperty('release')) {
signingConfig signingConfigs.release
}
}
debug {
debuggable true
jniDebuggable true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
dependencies {
compile 'com.android.support:appcompat-v7:25.+'
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.facetec:zoom-authentication:5.1.1#aar'
compile project(':zoom-authentication-5.1.1')
}
after trying to build from gradlew command line gradlew -d assembleDebug,
I got this log, maybe can help identify my problem :
09:08:19.942 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock
acquired.
09:08:19.942 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Relea
sing lock on daemon addresses registry.
> Building 62% > :app:compileDebugJavaWithJavac
Its stuck on task :app:compileDebugJavaWithJavac
I've tried to delete caches on C:\Users\<username>\.gradle\caches and still hang on :app:compileDebugJavaWithJavac process
I cannot figure it out. Any Idea? What I miss out?
Thanks.
This works for me:
CTRL + SHIFT + ESC -> Process -> Kill java.exe -> Rebuild
I also face this problem.
and i m really tired because i continuously 3 days find this solution.
then i show in gradle console. in which it show error: C:\Users\khimsuriya\AppData\Local\Android\sdk\build-tools\29.0.3-> "aapt" does not start.
so i change "build tool version" to 26.0.3 and the error was finished.
so you try change "build tool version" in your build.gradle(app level). it continue still you find perfect "strong textbuild tool version"
it is 100% work.
My number .9725414329

Android Studio, Gradle: How to automatically publish release.apk to svn repository?

In Maven, a release process works without problems. Since I was forced to use Android Studio with Gradle, I want to achieve the same behaviour as I had with Eclipse and Maven. I found some quite good Maven-like release plugin (https://github.com/researchgate/gradle-release), it almost works as expected, but it does not upload the release apk, although it correctly creates the apk in /app/build/outputs/apk and a tag with the source code on my SVN repository. The release folder is still empty. I'm not even sure if this plugin can do that, because it's not very well documented but I guess I need to tell this plugin what to upload and where to find it. There is only a afterReleaseBuild.dependsOn uploadArchives. What does this mean, that I have to override this uploadArchives method or whatever this means in Gradle? It seems to be something built-in because Gradle build does not complain if I write this in my script and run gradlew release. Obviously the plugin already knows the repository and can connect via ssh, otherwise it could not create the tag, but it seems that it does not know what to upload, the release folders stays empty.
Meanwhile I tried to solve that with a lot of other Gradle attempts, e.g. with the Maven plugin, but then I run into SSH cert problems without a solution, whereby even if it works, it wouldn't be a good solution, because I don't want to create pom.xml files or so on, it would have been just a workaround.
The target is that the release process should automatically create a folder in the svn repository's releases folder which is named like the current version (as it already works in tags folder, e.g. 1.0.0) and copy the released apk into it which was already renamed to myapp-app-1.0.0-release.apk by Gradle, since this is the name of the package in the local output folder.
Here is my current gradle script which can generate the release apk in the output folder but does not upload it to svn:
apply plugin: 'com.android.application'
apply plugin: 'net.researchgate.release'
def keystorePropertiesFile = rootProject.file("/home/myuser/.android/keystore.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
android {
lintOptions {
//TODO remove this or set to true
abortOnError false
}
signingConfigs {
myapp_release_config {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
compileSdkVersion 24
buildToolsVersion "24.0.1"
packagingOptions {
exclude 'META-INF/ASL2.0'
}
defaultConfig {
applicationId "com.mydomain.myapp"
minSdkVersion 9
targetSdkVersion 24
versionCode 1
versionName '1.0.0'
archivesBaseName = "myapp-app-$versionName"
}
buildTypes {
debug {
debuggable true
zipAlignEnabled false
}
release {
minifyEnabled true
proguardFiles 'proguard-rules.pro'
signingConfig signingConfigs.myapp_release_config
afterReleaseBuild.dependsOn uploadArchives
}
}
}
release {
failOnUnversionedFiles = false
svn {
username = 'myuser'
password = 'mypassword'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.mydomain.myapp:model:1.0'
//support-v4
compile 'com.android.support:support-core-utils:24.2.0'
compile 'com.android.support:support-fragment:24.2.0'
//compile 'com.android.support:multidex:1.0.0'
//support-design
compile 'com.android.support:design:24.2.0'
//support-v7
compile 'com.android.support:appcompat-v7:24.2.0'
//FlowLayout
compile 'com.wefika:flowlayout:0.4.1'
compile 'javax.validation:validation-api:1.1.0.Final'
compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
testCompile 'junit:junit:4.12'
testCompile 'org.hamcrest:hamcrest-all:1.3'
}
You can add a task to your build.gradle
This is a sample task and bash script for publishing:
task publishit (type: Exec) {
commandLine './publish.sh', android.defaultConfig.versionName
}
assembleRelease.finalizedBy(publishit)
and put publish.sh in your app path (and make it executable)
#!/bin/bash
### Settings
svn_path='/path/to/repo/'
svn_user='user'
svn_password='password'
app_prefix='myapp-app-'
app_suffix='-release.apk'
release_name='app-release.apk'
dir='/'
current_path=`pwd`
release_path=$current_path$dir$release_name
code_name=$1
app_path=$svn_path$code_name$dir$app_prefix$code_name$app_suffix
cd $svn_path
mkdir $code_name
cp $release_path $app_path
# check and fix these:
svn add $code_name
svn update
svn commit -m "new version" --username $svn_user --password $svn_passwd > publish_log
You can do it with gradle syntax, for more info read here

Resources