App development

Android Reminiscence Profiler: Getting Began [FREE]

The Android Reminiscence Profiler is a instrument which helps you perceive the reminiscence utilization of your app. Each Android developer ought to perceive reminiscence administration. Reminiscence pitfalls trigger lots of the crashes and efficiency points in Android apps.

On this tutorial you’ll learn to monitor reminiscence allocation and create heap dumps utilizing the Android Reminiscence Profiler.

Be aware: This tutorial assumes you could have earlier expertise growing for Android in Kotlin. In case you’re unfamiliar with the language, take a look at this tutorial. In case you’re starting with Android, take a look at a few of our Getting Began and different Android tutorials.

Android Profiler

Android Profiler, which replaces Android Monitor instruments, is included in Android Studio three.zero and later. It measures a number of efficiency elements of an app in real-time like:

Battery
Community
CPU
Reminiscence

On this tutorial you’ll concentrate on reminiscence evaluation.

Android Reminiscence Administration

The Android digital machine retains monitor of every reminiscence allocation within the heap. The heap is a piece of reminiscence the place the system allocates Java/Kotlin objects.

There’s a course of for reclaiming unused reminiscence often known as rubbish assortment. It has the next targets:

Discover objects that no person wants.
Reclaim the reminiscence utilized by these objects and return it to the heap.

You don’t typically request a rubbish assortment. As an alternative, the system has a working set of standards to find out when to carry out one.

To allow a multi-task surroundings, Android places a restrict on the heap measurement for every app. This measurement will range relying on how a lot accessible RAM the system has. When the heap capability is full and the system tries to allocate extra reminiscence, you might get an OutOfMemoryError.

Rubbish Assortment Roots

Suppose you could have the next objects in reminiscence:

The highest white objects are known as GC Roots. No different object within the heap references them.

To simplify issues, you possibly can consider obj9 as an exercise retaining different objects: obj10, obj11 and obj12.

Suppose you’re in that exercise and press again, ending it. The system will clear the reference from obj7 to obj9:

gc roots obj7 clears reference

When the system triggers the Rubbish Collector, it’ll begin from the GC roots. It’ll notice that obj9 and the remainder of the objects retained by it, obj10, obj11 and obj12, aren’t reachable and can accumulate them.

Why You Ought to Profile Your App Reminiscence

The system has to pause your app’s code to let the Rubbish Collector do its job. Normally, this course of is imperceivable.

However different occasions you’ll discover your app is sluggish and skipping frames. This occurs when your app allocates reminiscence sooner than the system can accumulate it.

While you leak reminiscence it may’t be launched again to the heap. This forces pointless rubbish assortment occasions and slows the remainder of the system. Ultimately, the system could kill your app course of to reclaim the reminiscence.

To keep away from these issues, you need to profile your app reminiscence.

Getting Began

To get began with this tutorial, click on the Obtain Supplies button on the prime or backside of the tutorial to obtain the starter undertaking.

All through this tutorial you’ll work with TripLog app. TripLog lets the consumer write notes about what they’re doing and feeling throughout a visit.

Open Android Studio three.four.1 or later, click on File ▸ New ▸ Import Venture. Choose the top-level undertaking folder for the starter undertaking you downloaded.

Alternatively, you possibly can choose Open an present Android Studio undertaking from the Welcome display screen. Once more, select the top-level undertaking folder for the starter undertaking you downloaded.

Construct and run TripLog to develop into accustomed to it:

trip log app main screen

trip log app detail screen

The TripLog undertaking incorporates the next most important recordsdata:

MainActivity.kt incorporates the principle display screen. It’ll present all of the logs right here.

DetailActivity.kt permits the consumer to create or view a log.

MainApplication.kt offers dependencies for the actions: a repository and formatters.

TripLog.kt represents the information of a log.

Repository.kt saves and retrieves logs.

DateFormatter.kt codecs the information to indicate within the screens.

Utilizing the Android Profiler

Open the Android Profiler:

android profiler button

You may as well open it by going to View ‣ Software Home windows ‣ Profiler.

Be aware: Alternatively, you possibly can construct and immediately profile the app by going to Run ‣ Profile ‘app’ or urgent the Profile button within the Navigation Bar.

It is best to see the present session:

android memory profiler

In case you don’t see the session listed, press the + button and choose the app.

android memory profiler add session

Be aware: In case you’re utilizing a tool or emulator working Android 7.1 or decrease, you’ll see a message stating, Superior profiling is unavailable for the chosen course of. To allow it, go to Run ‣ Edit Configurations and choose your app within the left pane. Then go to the Profiling tab. Lastly, verify Allow superior profiling.
Apply, construct and run your app once more.

Now, click on the Reminiscence part:

android memory profiler memory

On the prime, you’ll see the present exercise. On this case it’s the MainActivity.

Within the app, press the + button so as to add a brand new log and verify the profiler:

android memory profiler detail activity

It now exhibits the DetailActivity is the present exercise and a small pink dot. The profiler exhibits these dots every time you contact the display screen. Later, you’ll additionally see different icons, similar to again or keyboard, whenever you press them in your system or emulator.

Under that, you possibly can see the reminiscence depend of your app, segmented into a number of classes:

Java: Reminiscence from objects that Java/Kotlin has allotted.

Native: Allotted reminiscence from C/C++ code objects.

Graphics: Reminiscence to show pixels to the display screen.

Stack: Reminiscence utilized by each native and Java stacks in your app. When your app invokes a technique, a block is created within the stack reminiscence to carry native primitive values and references to different objects on this methodology.

Code: Reminiscence used for code and assets similar to dex bytecode, .so libraries and fonts.

Others: Reminiscence that the system doesn’t know how one can categorize.

Allotted: The variety of Java/Kotlin objects your app has allotted.

Be aware: In case you’re working a tool or emulator with Android 7.1 or decrease, this allocation depend begins solely on the time the Reminiscence Profiler related to your working app. It doesn’t depend any objects allotted earlier than you began profiling.

Allocation Monitoring

You’ll now see how one can analyze when TripLog objects are created in reminiscence.

Enter one thing into the What are you doing? subject. Press the verify button on the highest proper nook to reserve it.

Within the Reminiscence Profiler, in case you’re working a tool with Android eight.zero or larger, drag within the timeline to pick out the area between the DetailActivity and the MainActivity.

android profiler allocation tracking

Be aware: In case you’re working a tool with a decrease model, earlier than creating the log you’ll must click on on Document reminiscence allocations. Then add the log and press Cease recording.

Under the timeline, the profiler shows the Dwell Allocation outcomes:

android memory profiler allocation list

This exhibits the next for every class:

Allocations: Variety of objects allotted in this time period.

Deallocations: Amount of deallocations in this time period.

Whole Depend: Variety of objects nonetheless allotted of this class.

Shallow Measurement: Whole bytes of reminiscence used for the objects of this class.

Filter by TripLog, matching case, and also you’ll see the next:

android memory profiler triplog filter

Whilst you most likely didn’t anticipate it, there are two allocations of TripLog:

android memory profiler triplog alloc

To seek out out why, click on on every row of the Occasion View to see extra details about every allocation:

android memory profiler triplog first alloc

android memory profiler triplog second alloc

Within the Allocation Name Stack, one TripLog occasion was allotted within the onOptionsItemSelected() methodology. This was known as whenever you pressed the verify button on the highest proper nook.

The opposite one was created in onActivityResult() of MainActivity because of the unparcel.

Within the app, delete the log by urgent the trash button on the highest proper nook of the principle display screen.

Within the Reminiscence Profiler, scroll the timeline till the second you pressed the button. Carry out an allocation monitoring by dragging the timeline in to see if the TripLog situations have been deallocated whenever you pressed that button.

Be aware: In case you’re utilizing Android 7.1 or decrease, first click on on Document reminiscence allocations. Then delete the log and press Cease recording.

android memory profiler trash no deallocs

There have been no deallocations! Are you confused?

confused

It is because the Rubbish Collector didn’t move but. Subsequently there aren’t any deallocations.

To drive a rubbish assortment, press the next button two occasions:

android memory profiler force gc

Carry out an allocation monitoring by dragging the timeline in to see that the situations have been lastly deallocated.

android memory profiler deallocs

happy

Heap Dump

You may as well analyze the present state of the reminiscence by performing a heap dump.

You’ll simulate you could have one 100 logs. There’s a hidden button to take action. Open the activity_main.xml and alter the visibility of the button with buttonAddMultipleLogs id to seen.

Go to Run ‣ Profile ‘app’ and press the Add 100 logs button. After a couple of seconds, you’ll discover the logs have been added to the checklist.

Now, within the Reminiscence Profiler press the Dump Java heap button:

android memory profiler dump heap

Under the timeline you’ll see the heap dump:

android memory profiler dump result

This exhibits the next for every class:

Allocations: Amount of allocations.

Native Measurement: Whole bytes of native reminiscence.

Shallow Measurement: Whole bytes of Java reminiscence.

Retained Measurement: Whole bytes being retained on account of all situations of this class.

Order by Retained Measurement to see that there have been precisely 100 ConstraintLayout objects allotted. Proceed including logs and capturing heap dumps. You’ll see that this quantity will increase by precisely the variety of logs you add.

Which means the app is creating one ConstraintLayout per TripLog. Open the MainActivity.kt and verify the refreshLogs() methodology.

personal enjoyable refreshLogs()
layoutContainer.removeAllViews()
repository.getLogs().forEach tripLog ->
val baby = inflateLogViewItem(tripLog)
layoutContainer.addView(baby)

personal enjoyable inflateLogViewItem(tripLog: TripLog): View?
return layoutInflater.inflate(R.structure.view_log_item, null, false).apply
textViewLog.textual content = tripLog.log
textViewDate.textual content = dateFormatter.format(tripLog.date)
textViewLocation.textual content = coordinatesFormatter.format(tripLog.coordinates)
setOnClickListener
showDetailLog(tripLog)

By studying this code you possibly can verify that the app is inflating one view per log. In case you open the view_log_item.xml you’ll see it’s a ConstrainLayout.

This isn’t good as a result of it’s not recycling the views. That might ultimately create an OutOfMemoryError and generate a crash in your app. The answer is to refactor the app utilizing RecyclerView.

Open the activity_main.xml and change the ScrollView with the next:

Open the MainActivity.kt file, delete the refreshLogs() and inflateLogViewItem() strategies. Paste the next:

personal enjoyable refreshLogs()

Let the MainActivity implement the next listener:

class MainActivity : BaseActivity(), TripLogAdapter.Listener {

And likewise change the next:

personal enjoyable showDetailLog(tripLog: TripLog) {

To this:

override enjoyable showDetailLog(tripLog: TripLog) {

This received’t compile but. So, create a brand new class known as TripLogAdapter.kt with the next content material:

class TripLogAdapter(context: Context,
personal val logs: Record,
personal val dateFormatter: DateFormatter,
personal val coordinatesFormatter: CoordinatesFormatter
) : RecyclerView.Adapter()

var listener: Listener? = null

override enjoyable onCreateViewHolder(mum or dad: ViewGroup, viewType: Int)
: TripLogViewHolder
val inflater = LayoutInflater.from(mum or dad.context)
val itemView = inflater.inflate(R.structure.view_log_item, mum or dad, false)
return TripLogViewHolder(itemView)

override enjoyable getItemCount() = logs.measurement

override enjoyable onBindViewHolder(holder: TripLogViewHolder, place: Int)
val tripLog = logs[position]
holder.bind(tripLog)

inside class TripLogViewHolder(itemView: View)
: RecyclerView.ViewHolder(itemView)
personal val textViewLog = itemView.textViewLog
personal val textViewDate = itemView.textViewDate
personal val textViewLocation = itemView.textViewLocation

enjoyable bind(tripLog: TripLog)
textViewLog.textual content = tripLog.log
textViewDate.textual content = dateFormatter.format(tripLog.date)
textViewLocation.textual content = coordinatesFormatter.format(tripLog.coordinates)
itemView.setOnClickListener
listener?.showDetailLog(tripLog)

interface Listener

Profile the app once more and see that now it creates fewer ConstraintLayout objects as a result of it’s recycling the views.

Frequent Rubbish Assortment

Rubbish Assortment, additionally known as reminiscence churn, occurs when the app allocates but additionally has to deallocate objects in a brief time frame.

For instance, it may occur in case you allocate heavy objects in loops. Inside every iteration, the app has to not solely allocate an enormous object, but additionally deallocate it from the earlier iteration so it doesn’t run out of reminiscence.

The consumer will discover stuttering within the app due to frequent rubbish assortment. This results in a poor consumer expertise.

To see this in motion, add a toggle button when writing your log in order that the consumer can even describe her or his temper. So, open the activity_detail.xml and add the next above the EditText:

Open the DetailActivity.kt file and add the next to the showNewLog() methodology:

toggleButtonMood.isEnabled = true

Add this to the showLog() methodology:

toggleButtonMood.isChecked = log.happyMood
toggleButtonMood.isEnabled = false

Lastly, replace the creation of the TripLog within the newLog() methodology:

val log = TripLog(editTextLog.textual content.toString(), Date(), null,
toggleButtonMood.isChecked)

Don’t overlook to replace the TripLog.kt:

information class TripLog(val log: String, val date: Date, val coordinates: Coordinates?, val happyMood: Boolean = true) : Parcelable

Now, to see the temper of every log in the principle display screen it’s worthwhile to replace the TripLogAdapter class. So open it and replace the TripLogViewHolder(itemView: View) inside class with this:

inside class TripLogViewHolder(itemView: View)
: RecyclerView.ViewHolder(itemView) {

personal val imageView = itemView.imageView

enjoyable bind(tripLog: TripLog) {
val happyBitmap = BitmapFactory.decodeResource(itemView.context.assets,
R.drawable.bg_basic_happy_big)
val sadBitmap = BitmapFactory.decodeResource(itemView.context.assets,
R.drawable.bg_basic_sad_big)
imageView.setImageBitmap(if (tripLog.happyMood) happyBitmap else sadBitmap)

Construct and run the app. Add 100 logs and attempt to scroll:

angry

This may be the face your customers make after they encounter such gradual efficiency! So, you’d higher see what’s taking place and repair it earlier than transport the app.

Open the Android Profiler which can begin monitoring mechanically or add the present session manually as defined earlier than.

One of many first belongings you’ll discover is the Whole reminiscence is larger than earlier than. Additionally, attempt to scroll within the app and also you’ll see one thing just like this:

android memory profiler frequent gc

As you possibly can see, the system triggers the rubbish collector ceaselessly. You may as well verify this by performing some allocation monitoring within the timeline. You’ll see the amount of objects being allotted are virtually the identical as these being deallocated.

This clearly isn’t good. Frequent rubbish collections is inflicting unhealthy efficiency.

Now, carry out a heap dump and also you’ll see one thing like this:

android memory profiler frequent gc heap dump

Right here you could find a clue. There are some Bitmap objects retaining quite a lot of reminiscence.

So, do some allocation monitoring once more when the logs are created. Filter by Bitmap. You’ll be able to click on on one among them to see the place they’re being created:

android memory profiler frequent gc bitmap alloc

Double click on the bind methodology within the Allocation Name Stack and also you’ll go to the supply code:

enjoyable bind(tripLog: TripLog) {
val happyBitmap = BitmapFactory.decodeResource(itemView.context.assets,
R.drawable.bg_basic_happy_big)
val sadBitmap = BitmapFactory.decodeResource(itemView.context.assets,
R.drawable.bg_basic_sad_big)
imageView.setImageBitmap(if (tripLog.happyMood) happyBitmap else sadBitmap)

Evidently these traces are inflicting the issue. The app is unnecessarily decoding R.drawable.bg_basic_happy_big and R.drawable.bg_basic_sad_big every time you bind a log.

So, take away these traces and modify the TripLogAdapter.kt as follows:

class TripLogAdapter(context: Context,
personal val logs: Record,
personal val dateFormatter: DateFormatter,
personal val coordinatesFormatter: CoordinatesFormatter
) : RecyclerView.Adapter() {

personal val happyBitmap = BitmapFactory.decodeResource(
context.assets,
R.drawable.bg_basic_happy_big)

personal val sadBitmap = BitmapFactory.decodeResource(
context.assets,
R.drawable.bg_basic_sad_big)

Right here, you’re decoding the drawables solely as soon as as a substitute of doing it on every bind. There aren’t any extra frequent rubbish collections since you correctly allotted reminiscence for the Bitmap objects.

Construct and run the app once more, you’ll see the efficiency was enhanced!

celebrate

Problem

All through the tutorial you’ve used an in reminiscence repository to get and save the logs. Subsequently the logs are at all times deleted between periods of the app.

Open the MainApplication.kt and also you’ll see a commented line to make use of a SharedPreferences repository implementation that completely saves the logs. Uncomment this line and remark or delete the one you’ve been utilizing.

Construct and profile the app to see it’s creating many TripLog situations. For instance, after including 5 logs you’ll see the app truly allotted eleven situations. As a problem, attempt to refactor SharedPreferencesRepositoryImpl to reduce the amount of allocations.

You’ll find the finished problem in the identical obtain from the Obtain supplies button discovered on the prime or backside of this tutorial.

The place To Go From Right here?

You’ll be able to obtain the finished undertaking utilizing the Obtain supplies button on the prime or backside of the tutorial.

Congratulations! You now know how one can:

Use the Android Profiler to investigate reminiscence.
Use Heap Dumps to establish which courses allocate massive quantities of reminiscence.
Carry out Allocation Monitoring over time to know when the app allocates or deallocates objects and likewise to know the place in your code the allocation is going on.

If you wish to study extra in regards to the topic, please verify the next references:

I hope you loved this introduction to Android Reminiscence Profiler tutorial. You probably have any questions, feedback or superior modifications to this undertaking app please be part of the discussion board dialogue and remark under!

asubhan
wordpress autoblog
amazon autoblog
affiliate autoblog
wordpress web site
web site improvement

Related posts

What’s new with Quick Pair

admin

Glide Tutorial for Android: Getting Began [FREE]

admin

Nexon will increase day 60 retention and monetization with pre-registration rewards

admin

Leave a Comment