How to compress Kotlin projects in Android studio - java

I create one android application in android studio and for programming language i used Kotlin.
Now my application finished and i want build my app, but after build app show me 35mb for application size!!!
My drawable folders size has 2mb and not have any larger size file, but why my application size is 35mb ?!!!
For generate test apk version i used Build -> Build bundle/Apk -> Build apk from android studio menu.
But when use java for language this size is 7mb!!!
How can i fix it?

Some random ideas to improve your apk size:
Turn on minification (ProGuard or R8, use the property minifyEnabled), recheck your ProGuard files if you are not excluding too much
Convert your images to webp files, or vectors, which are even better
Add an abiFilter, which excludes ancient ABIs, such as mips
Use Android App Bundles, which splits the apk per language, ABI and screen resolution, essentially reducing the delivered APK size
Check if you have any libraries you don't use anymore
Filter out any unsupported languages with the resConfigs attribute
Android also has a documentation about this, which goes into more detail.

Related

Flutter apps are too big in size

I have good experience in android app development using java. Recently I came to know about flutter. So, I have tried to create a simple android app with flutter based on official tutorial. But surprisingly the debug app size is 25MB and release apk costs more than 7MB. It is really larger when compare with native developed android app.
Is there any way to optimize it?
One way that i use to reduce my app size is to use;
flutter clean
before i run the build command;
flutter build appbundle --target-platform android-arm,android-arm64
When i run the build command without the clean command, i get around 32mb, but if i run the clean command first, i get around 18mb
Flutter team acknowledges it here.
There's an explanation for this here, quoting the same -
In August 2018, we measured the size of a minimal Flutter app (no
Material Components, just a single Center widget, built with flutter
build apk), bundled and compressed as a release APK, to be
approximately 4.7MB.
For this simple app, the core engine is approximately 3.2MB
(compressed), the framework + app code is approximately 840KB
(compressed), the LICENSE file is 55KB (compressed), necessary Java
code (classes.dex) is 57KB (compressed), and there is approximately
533KB of (compressed) ICU data.
Of course, YMMV, and we recommend that you measure your own app, by
running flutter build apk and looking at
build/app/outputs/apk/release/app-release.apk.
Also, the relative differences in apk size would likely be smaller with larger apps. Flutter's overhead size is fixed.
Use following commands to analyze which is taking up most your app's space.
For Android's AppBundle:
flutter build appbundle --target-platform android-arm --analyze-size
flutter build appbundle --target-platform android-arm64 --analyze-size
flutter build appbundle --target-platform android-x64 --analyze-size
For Android's APK:
flutter build apk --target-platform android-arm --analyze-size
flutter build apk --target-platform android-arm64 --analyze-size
flutter build apk --target-platform android-x64 --analyze-size
For iOS:
flutter build ios --analyze-size
For Linux:
flutter build linux --analyze-size
For macOS
flutter build macos --analyze-size
For Windows
flutter build windows --analyze-size
This includes native code, assets, and even a package-level breakdown of compiled Dart code.
DevTools
If you want to see the visual representation of it, use DevTools. For that after running previous command, run:
flutter pub global run devtools --appSizeBase=apk-code-size-analysis_01.json
You'll be then directed to your browser, where you will see something like this:
First check these:
As other answer mentioned remove all unnecessary assets(images, fonts
and files).
If you have too many fonts that will affect apk size heavily and flutter also made a solution for that by creating a package for you to get fonts from google fonts library(awesome package that give you access to so much fonts and flexibility to use anywhere). Get the package here and Read more here.
Remove unnecessary packages/ plugin that doesnt use(Not much affect
though).
Remove unused resources
Minimize resource imported from libraries
Support a limited number of screen densities
Compress PNG and JPEG files
Read this also: Measuring your app's size
Please note these too:
If you build your apk using flutter build apk it will contains both arm-32 and arm-64 apks(Which flutter will show in console when you building apk). If you are building app bundle this is not an issue and its size is much smaller.
To avoid one flat apk containing arm-32 and arm-64, you can build them separately using below two commands:
flutter build apk --target-platform=android-arm
Above will produce arm-32 bit apk. Go to project -> build -> app -> release and rename the apk to this: app-armeabi-v7a-release.apk.
then increment version code in pubspec.yaml, next flutter pub get and do this:
flutter build apk --target-platform=android-arm64
Above will produce arm-64 bit apk. Go to project -> build -> app -> release and rename the apk to this: app-arm64-v8a-release.apk.
Then you can submit two apks separately(lower apk version first).
Since, you have to run two commands by incrementing version code, flutter made it easier by this command (flutter > 1.5.4 I think): flutter build apk --split-per-abi. That command will increment apk version code for the second apk and give you two renamed apks (Please note that this command will produce with higher version code(ex: 3222)).
From doc:
From the command line:
Enter cd <app dir>
(Replace <app dir> with your application’s directory.)
Run `flutter build apk --split-per-abi`
(The flutter build command defaults to `--release`.)
This command results in two APK files:
<app dir>/build/app/outputs/apk/release/app-armeabi-v7a-release.apk
<app dir>/build/app/outputs/apk/release/app-arm64-v8a-release.apk
<app dir>/build/app/outputs/apk/release/app-x86_64-release.apk
Removing the --split-per-abi flag results in a fat APK that contains
your code compiled for all the target ABIs. Such APKs are larger in
size than their split counterparts, causing the user to download
native binaries that are not applicable to their device’s architecture
read more here.
I also heard somewhere that in latest flutter update they have made flutter app size even smaller. There is a added issue for this also: https://github.com/flutter/flutter/issues/16833
Yes ofcourse, the size of the apk or ipa built with flutter will be minimum of ~7mb for a hello world app. This is because, flutter ships a core engine, framework, ICU data, LICENSE file etc with its build output which are mandatory for a flutter app to run.
You can check out the FAQ here to know more about what takes how much size when build.
Hope that helps!
I have used this command to generate Released apk for production stage:
flutter build apk --split-per-abi
the output apk is located in project folder:
[project]/build/app/outputs/apk/release/app-armeabi-v7a-release.apk
in my case the size of apk is reduced to 5.3 MB (after above command execution).
the reason for big size (almost > 50 MB) because they contain everything you might need during a hot restart or restart which prevents building whole system again when you made just a small change in your code .
Release builds are real result of all your code and they are real minified apps without any containers which then you can distribute on google store.
TL;DR: use command flutter build apk --split-per-abi
After running flutter build apk --release, my APK size was 16.2 MB. This APK is called FAT APK which is a single APK that contains binaries for multiple ABIs embedded within it and supports multiple architectures.
With flutter build apk --split-per-abi, dart code obsfucates resulting in 3 APK files, size of my app.APK was reduced to 5.6 MB.
Here are the official docs explaining the same: https://docs.flutter.dev/deployment/android
all this kind of cross-platform app are larger from start
i did work with react-native and hello-world app is about 6 MB
all you can do is make a two release apk ,one for arm cpu and one for x86 cpu in this way you can lower the size about 4 MB but never gonna be small as android
according to google
one way to reduce the size of your APK is to create multiple APKs that contain files for specific screen densities or ABIs.
check here for more info https://developer.android.com/studio/build/configure-apk-splits.html
UPDATE: if my it not fully supported now it ,will be in future for sure, in every phase of flutter development it will be this method work but not too much in beta release , but this method will work better by releasing more version of flutter
Here is Official Android documentation that made my apps go
From ~20mb
To ~9mb
Try the Proguard recommendation
Link: https://developer.android.com/topic/performance/reduce-apk-size
Before and After using ProGuard and more
Add Proguard file with the below code in it
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.** { *; }
-keep class io.flutter.util.** { *; }
-keep class io.flutter.view.** { *; }
-keep class io.flutter.** { *; }
-keep class io.flutter.plugins.** { *; }
Note: If the Proguard file does not exist then need to create at the location
/android/app/proguard-rules.pro
Check this below steps it may help you to reduce app size (only Android), i have reduced my 48mb build to 14mb
Step 1: android/gradle.properties
android.enableR8=true
Step 2: android/app/build.gradle
inside -> buildTypes -> release
minifyEnabled true
shrinkResources true
useProguard true
Step 3:
Run
flutter build apk --target-platform=android-arm
or
flutter build apk --split-per-abi
Some other optimizing tips,
1. Image assets
Upload the images in permanent storage path like AWS or in your website server and use the link to that image in your code.
2. Icons
Its recommended to use from Material Icons or Cupertino Icons class. You can add --tree-shake-icons option to flutter build command, to remove all of the not used icons from the bundle. This will potentially save the size of your app. (use svg format icons)
3. Fonts
If we are using more fonts from local assets similar like images these fonts will also increase app size. The best solution is to use google_fonts plugin. This pluign will dynamically download font when it is used.
4. Dynamic App Delivery
We could build an app bundle if we are uploading to playstore or we could split the apk per abi which splits the apk to x64 and x86 bit code. By using appbundle Google Play’s new app serving model, called Dynamic Delivery, uses your app bundle to generate and serve optimized APKs for each user’s device configuration, so they download only the code and resources they need to run your app.
Refer below links for more understanding,
https://developer.android.com/studio/build/shrink-code
https://developer.android.com/guide/app-bundle
https://www.youtube.com/watch?v=9D63S4ZRBls
I also came across in this very apk condition when debugging, while in releases around 7-8 mb. This however we could see it in much larger apps, where natively speaking, we need to import many libraries, while with Flutter the work is optimized. So if we assume an app that natively should weigh around 30mb with Flutter it should be similar. What can scare you is in the very basic apps. The important thing however is to optimize the images
You could use the apk analyzer in android studio to see what causes the app size to be that large.
In the case of having large and multiple image assets, you might want to use SVGs instead of PNGs.
Where you have to use PNGs or JPGs, you should compress them.
You might also want to use cached_network_image and call the image from some external service like Firebase. This will load the image from the internet on first launch and cache it to your app. You can check out cached_network_image on pub.dev.
For your fonts, you should use google fonts instead of binding the font files to your app. You can check out google fonts on pub.dev.
You should also shrink resources and set minifyEnable to true in your
build.gradle in /android/app.
For uploading to playstore, you should generate and upload an app
bundle instead.
You can follow this read on reducing your flutter app sizes. Some of the recommendations are also applicable to native android development. Reducing flutter app size
For a debug apk below are steps for optimize -
Analyze for apk using Analyze APK from build tool of Android studio or manually by extracting the zip.
In my case the biggest folder was lib which contains 4 different folder named arm64-v8a , armeabi-v7a ,x86,x86_64
So these all four folders are basically different processor architecture of mobile devices.So to figure out your device falls under which category,below are some examples-
ARM: This is a mobile processor architecture first and foremost, and what the majority of phones run now. Qualcomm’s Snapdragon, Samsung’s Exynos, and MediaTek’s mobile chips are all examples of ARM processors. Most modern chips are 64-bit, or ARM64.
x86: This is the architecture specification for Intel chips. As dominant as Intel is in the computer market, these chips are far less common in Android handsets. x86_64 refers to 64-bit Intel chips.*
After finding your desired/required apk ,you can now split your apks based on these processor architecture using the command
flutter build apk --debug --split-per-abi
And finally check the build/app/outputs/apk/debug/app-arm64-v8a-debug.apk(here replace with your choice) folder to get your desired and reduced apk.
There are many possibilities:
First , build your application in release mode by using :
In your terminal :
flutter build --release
or just specify the target :
For Android Apk : flutter build apk --release
For Android App Bundle: flutter build appbundle --release
For IOS : flutter build ios --release
By default, flutter run compiles to debug mode .This explains the
large size of the application . Debug mode (Hot reload , Dart Devtools etc ..) vs Release Mode (Simple Application)
By default flutter build build for release mode . So you can just do flutter build
Using --split-debug-info flag can dramatically reduce code size. For an example of using this flag, see Obfuscating Dart code.
Some of the other things you can do to make your app smaller are:
Remove unused resources
Minimize resource imported from libraries
Compress PNG and JPEG files
Your can learn more about flutter app size here
A basic flutter "Hello World" app will be approximately 10mb in iOS and 4mb in Android. This cannot be smaller because of the runtime and LICENSE etc.
To make your app apk size small (for android):
$ flutter clean
$ flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi
You can obfuscate your code and remove the debug symbols from your binary.
flutter build apk --obfuscate --split-debug-info=/<project-name>/<directory>
Replace "apk" with "ipa" for iOS, and "appbundle" for Android before releasing the application.
For e.g.
flutter build appbundle --obfuscate --split-debug-info=symbols/
This will prevent your code from reverse engineering as well as remove debug symbols which will help in reducing the app size.
I saw around 10% decrease in my app size after doing this but it will vary depending upon your application.
Source: https://flutter.dev/docs/deployment/obfuscate#obfuscating-your-app
My apka build by flutter was of 47mb,
Application app bundle -60mb..
After uploading bundle on play store size is11 to 20 mbenter image description here

Can I edit xml/java codes of my android app on Brackets Editor?

I am new to Android app development. I have a source code and would like to modify some xml/java codes. Can I use the Brackets editor for this? I don't want to use Android studio as it's a bit complicated for me.
If you really want to, you can edit source files in an editor of your choosing and build the app manually via terminal. Actually, this is how it's done on Continuous Integration systems.
Typically Android projects are using Gradle build system, and come with Gradle wrappers. After you are done editing, you can just invoke it to assemble the release APK signed with proper keys as discussed in How to create a release signed apk file using Gradle? thread. Note that it would require you having downloaded Android SDK and configured your paths properly, which would be tricky for a beginner, yet completely automated in a proper IDE.
If you are unlucky, it could be an old Eclipse project, or using some less popular build system, like Ant.
As you are new to Android development, I think you should go the more simple route and just download Android Studio and import your project.

One of the possible reason for slow android studio and RAM consumption [duplicate]

I had installed Android Studio 1.0 RC 2. I have 4GB of RAM installed, but after starting Android Studio and launching Android Emulator, more than 90% of physical memory has been used by only these two. Is there is any way to reduce this memory use? Due to this memory issue, I can't open other applications at the same time.
I'm currently running Android Studio on Windows 8.1 machine with 6 gigs of RAM.
I found that disabling VCS in android studio and using an external program to handle VCS helped a lot. You can disable VCS by going to File->Settings->Plugins and disable the following:
CVS Integration
Git Integration
GitHub
Google Cloud Testing
Google Cloud Tools Core
Google Cloud Tools for Android Studio
hg4idea
Subversion Integration
Mercurial Integration
TestNG-J
In my case, there were two main sources of memory hogging: the IDE and Gradle:
Android Studio (up to 1.5GB)
The IDE's JVM is configured to have a max heap size. You can see this in the lower-right corner of the main interface:
You can reduce this by editing the memory-related settings in the .vmoptions file. For example, I changed my max heap size to 512MB:
-Xmx512m
Unfortunately, I found that lowering this value increases the frequency of Android Studio temporarily freezing, perhaps to do its garbage collection.
Gradle (up to 1.5GB)
Gradle can also use a lot of RAM after developing for a while. Windows just shows it as Java(TM) Platform SE Binary:
You can fix this by changing the Gradle JVM options. You can do this on a per-user basis by editing gradle.properties:
Open the gradle.properties file, creating it if it doesn't exist:
Windows: %USERPROFILE%\.gradle\gradle.properties
Linux/Mac: ~/.gradle/gradle.properties
Update the org.gradle.jvmargs property, creating it if necessary. I set mine to this:
org.gradle.jvmargs=-Xmx256m -XX:MaxPermSize=256m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
I haven't noticed any difference in build performance for my small project with the max heap size set to 256MB (-Xmx256m).
Note that you might need to restart Android Studio so the old Gradle process is killed; otherwise you might end up with both running at the same time.
Emulator
Regarding the emulator taking up a lot of your RAM, your screenshot shows it taking about 800MB. You can choose how much RAM to allocate to the emulator:
Edit the AVD
Press Show Advanced Settings
Reduce the value of RAM
You can speed up your Eclipse or Android Studio work, you just follow these:
Use/open single project at a time
clean your project after running your app in emulator every time
use mobile/external device instead of emulator
don't close emulator after using once, use same emulator for running app each time
Disable VCS by using File->Settings->Plugins and disable the following things :
1.CVS Integration
2.Git Integration
3.GitHub
4.Google Cloud Tools for Android Studio
5.Subversion Integration
I am also using Android Studio with 4-GB installed main memory but following these statements really boost my Android Studio performance.
Android Studio has recently published an official guide for low-memory machines: Guide
If you are running Android Studio on a machine with less than the recommended specifications (see System Requirements), you can customize the IDE to improve performance on your machine, as follows:
Reduce the maximum heap size available to Android Studio: Reduce the maximum heap size for Android Studio to 512Mb.
Update Gradle and the Android plugin for Gradle: Update to the latest versions of Gradle and the Android plugin for Gradle to ensure you are taking advantage of the latest improvements for performance.
Enable Power Save Mode: Enabling Power Save Mode turns off a number of memory- and battery-intensive background operations, including error highlighting and on-the-fly inspections, autopopup code completion, and automatic incremental background compilation. To turn on Power Save Mode, click File > Power Save Mode.
Disable unnecessary lint checks: To change which lint checks Android Studio runs on your code, proceed as follows:
Click File > Settings (on a Mac, Android Studio > Preferences) to open the Settings dialog.In the left pane, expand the Editor section and click Inspections. Click the checkboxes to select or deselect lint checks as appropriate for your project. Click Apply or OK to save your changes.
Debug on a physical device: Debugging on an emulator uses more memory than debugging on a physical device, so you can improve overall performance for Android Studio by debugging on a physical device.
Include only necessary Google Play Services as dependencies: Including Google Play Services as dependencies in your project increases the amount of memory necessary. Only include necessary dependencies to improve memory usage and performance. For more information, see Add Google Play Services to Your Project.
Reduce the maximum heap size available for DEX file compilation: Set the javaMaxHeapSize for DEX file compilation to 200m. For more information, see Improve build times by configuring DEX resources.
Do not enable parallel compilation: Android Studio can compile independent modules in parallel, but if you have a low-memory system you should not turn on this feature. To check this setting, proceed as follows:
Click File > Settings (on a Mac, Android Studio > Preferences) to open the Settings dialog. In the left pane, expand Build, Execution, Deployment and then click Compiler. Ensure that the Compile independent modules in parallel option is unchecked.If you have made a change, click Apply or OK for your change to take effect.
Turn on Offline Mode for Gradle: If you have limited bandwitch, turn on Offline Mode to prevent Gradle from attempting to download missing dependencies during your build. When Offline Mode is on, Gradle will issue a build failure if you are missing any dependencies, instead of attempting to download them. To turn on Offline Mode, proceed as follows:
Click File > Settings (on a Mac, Android Studio > Preferences) to
open the Settings dialog.
In the left pane, expand Build, Execution, Deployment and then click Gradle.
Under Global Gradle settings, check the Offline work checkbox.
Click Apply or OK for your changes to take effect.
I have used all of Sam's recommendations above, but I found that the VM command line options are no longer supported as described. (I received an error when used)
As an alternative, I was able to reduce gradle dramatically by adding the following line to the "gradle.properties" file
org.gradle.jvmargs=-Xms512m -Xmx1024m
As of A.S. ver 1.3, the file is located in the same folder level as "gradle.build".
The above configuration is a "memory stack" of 512 meg, and "memory heap" of 1024 meg.
I tested this on a small project, using settings where both memory sizes were set to 256 meg. It limited the JVM sizes as expected. In all my tests, I restarted A.S. to force the JVM to restart.
Hopefully, this will save others dealing with this issue from getting those "Get yourself a better computer" responses. :-)
To run Android envirorment on low configuration machine.
Close the uncessesory web tabs in browser
For Antivirus users, exclude the build folder which is auto generated
Android studio have 1.2 Gb default heap can decrease to 512 MB
Help > Edit custom VM options
studio.vmoptions
-Xmx512m
Layouts performace will be speed up
For Gradle one of the core component in Android studio Mkae sure
like right now 3.0beta is latest one
Below tips can affect the code quality so please use with cautions:
Studio contain Power safe Mode when turned on it will close background operations that lint , code complelitions and so on.
You can run manually lint check when needed ./gradlew lint
Most of are using Android emulators on average it consume 2 GB RAM so if possible use actual Android device these will reduce your resource load on your computer. Alternatively you can reduce the RAM of the emulator and it will automatically reduce the virtual memory consumption on your computer. you can find this in virtual device configuration and advance setting.
Gradle offline mode is a feature for bandwidth limited users to disable the downloading of build dependencies. It will reduce the background operation that will help to increase the performance of Android studio.
Android studio offers an optimization to compile multiple modules in parallel. On low RAM machines this feature will likely have a negative impact on the performance. You can disable it in the compiler settings dialog.
You can adjust the heap size of the IDE and Gradle daemons from inside the Android Studio.
Read and follow the instructions in the settings screen:
Also, see this page on Android Developers site
I have Android Studio 2.1.1 Bro use genymotion emulator It Faster If Use Android Marshmallow. And My Ram Is 4gb.And Install Plugin for genymotion in Android Studio.You Will see good result in instead of wasting time start android emualtor it will take 5 min.genymotion 10 to 20 second speed and faster so I recommended to you use genymotion.
To reduce the lag i would recommend the follwing steps
my pc specs : 2 gb ram, processor: intel core2 duo
first kill all background process, if you have server or database running you could stop them first with following commands
sudo service apache2 stop
sudo service mysql stop
Then enable power saving mode in android studio by file>powersaving mode
It could disable background process, and then studio appears to go well
Try switching your JVM to eclipse openj9. Its gonna use way less memory. I swapped it and its using 600Mb constantly.
I don't know if it is a solution but Invalidate Cache and Restart solved this problem in my case. I am currently using Android Studio 3.6
I fond this YouTube video from Google where are some tips and tricks for it. The video also includes advantages and disadvantages of suggested changes.
Improving Android Studio Performance on Memory-Constrained Machines
Open below mention path on your system and delete all your avd's (Virtual devices: Emulator)
C:\Users{Username}.android\avd
Note: - Deleting Emulator only from android studio will not delete all the spaces grab by their avd's. So delete all avd's from above given path and then create new emulator, if you needed.

Android Studio: Language Defaults are applied instead of Java scheme

I've downloaded a couple of schemes for Android Studio. However, after applying the scheme the Java scheme is not used even though my files are *.java and Android Studio draws a little (J) on the icon. The "Language defaults" are used instead which don't provide enough highlighting.
How can I force Android Studio to use the Java scheme? The default scheme doesn't have too many colours, so it's hard to differentiate.
Edit: The project was exported from Eclipse and imported to Android Studio.
I just found the solution myself. The src directory wasn't recognized as Sources Root. After I did that the editor magically applied the Java scheme, yay!

Including and Excluding Libs at Run Time

In my new Android app, I'm required to use a library when Android Version in 1.6 and 1.5 and include some other library when the version is more than 1.6.
I know how to get the Android SDK version, but I'm stuck at inclusion of specific library at run time.
Any Help ??
Libraries are included in your APK file. As such you cannot remove libraries from the APK at runtime.
As far as loading classes at runtime is concerned, you can always do that, but the content of the APK (the JARs / classes you include in them is static). You are offcourse free to load particular classes from it based on the API level.
If you're worried about the file-size of your APK, and you want to optimize the APK packaging and tweak your app based on the capabilities of the device of the consumer of your app, you should checkout this link :
http://android-developers.blogspot.com/2011/07/multiple-apk-support-in-android-market.html
It allows you to target different APKs based on device capabilities (ex: API level). That way, you can create 2 APKs with the specific libraries you want to use for a specific API level.

Categories

Resources