How android works in mobile

Finally understanding how references work in Android and Java

A few weeks ago I attended Mobiconf, one of the best conferences for Mobile Developers I had the pleasure to attend in Poland. During his eclectic presentation “The best (good) practices”, my friend and colleague Jorge Barroso came up with a statement that made me reflect after hearing it:

If you are an Android developer and you do not use WeakReferences, you have a problem.

On an example of good timing, a couple of months ago I did publish my last book, “Android High Performance”, co-authored with Diego Grancini. One of the most passionate chapters is the one talking about Memory Management in Android. In this chapter, we talk about how the memory works in a mobile device, how memory leaks happen, why this is important and which techniques we can apply to avoid them. Since I did start developing for Android, I have always observed a tendency to involuntarily avoid or give a low priority to everything related with memory leaks and memory management. If the functional criteria are fulfilled, why bothering? We are always in a rush to develop new features, and we would rather present something visual in our next Sprint demo rather than caring about something that nobody will see at a first glance.

Is a nice argument, which irrevocably leads to acquiring technical debt. I would even add that the technical debt has also some effects in the real world that we cannot measure with unit tests: disappointment, friction among fellow developers, low quality software shipped and loss of motivation. The reason why this effects are difficult to measure is because often they happen in the long term. It occurs a little bit like with politicians: if I am only going to be in charge for 8 years, why would I bother about what happens in 12? Except that in Software Development everything moves way faster.

Writing about the decent and proper mindset to adopt in Software Development could require a few volumes, and there are already many books and articles that you can explore. However, explaining briefly the different types of memory references, what do they mean and how can they be applied in Android will be a briefer task, and this is what I want to do in this article.

First of all: what is a reference in Java?

A reference is the direction of an object that is annotated, so you can access it.

Java has by default 4 types of references: strong, soft, weak and phantom. Some people argue that there are just two types of references, strong and weak, and the weak references can present 2 degrees of weakness. We tend to classify everything in life with the taxonomic perseverance of a botanist. Whatever it works better for you, but first you do need to understand them. Then you can figure out your own classification.

What does each type of reference mean?

Strong reference: strong references are the ordinary references in Java. Anytime we create a new object, a strong reference is by default created. For example, when we do:

A new object MyObject is created, and a strong reference to it is stored in object. Easy so far, are you still with me? Well, now more interesting things are coming. This object is strongly reachable — that means, it can be reached through a chain of strong references. That will prevent the Garbage Collector of picking it up and destroy it, which is what we mostly want. But now, let´s see an example where this can play against us.

Take a few minutes and try to spot any approach susceptible of problems.

No worries, take more time if you can´t.

The AsyncTask will be created and executed together with the Activity onCreate() method. But here we have a problem: the inner class needs to be accessing the outside class during its entire lifetime.

Читайте также:  Скриншот не сохраняется android

What happens when the Activity is destroyed? The AsyncTask is holding a reference to the Activity, and the Activity cannot be collected by the GC. This is what we called a memory leak.

Side note: when in my previous lifes I used to conduct interviews with prospective candidates, I used to ask them how could you create a memory leak rather than asking about the theoretical aspect of what a memory leak is. It was always much more fun!

The memory leak actually happens not only when the Activity is destroyed per-se, but as well when it is forcibly destroyed by the system due to a change in the configuration or more memory is needed, etc. If the AsyncTask is complex (i.e., keeps references to Views in the Activity, etc) it could even lead to crashes, since the view references are null.

So how can prevent this problem from ever happening again? Let´s explain the other type of references:

WeakReference: a weak reference is a reference not strong enough to keep the object in memory. If we try to determine if the object is strongly referenced and it happened to be through WeakReferences, the object will be garbage-collected. For terms of understanding, is better to kill the theory and show as a practical example how could we adapt the previous code to use a WeakReference and avoid a memory leak:

Note a main difference now: the Activity within the inner class is now referenced as follows:

What will happen here? When the Activity stops existing, since it is hold through the means of a WeakReference, it can be collected. Therefore no memory leaks will happen.

Side note: now that you hopefully understand what WeakReferences are a little bit better, you will find useful the class WeakHashMap. It works exactly as a HashMap, except that the keys (key, not values) are referred to using WeakReferences. This makes them very useful to implement entities such as caches.

We have mentioned however a couple of references more. Let´s see where they are useful, and how we can benefit of them:

SoftReference: think of a SoftReference as a stronger WeakReference. Whereas a WeakReference will be collected immediately, a SoftReference will beg to the GC to stay in memory unless there is no other option. The Garbage Collector algorithms are really thrilling and something you can dive in for hours and hours without getting tired. But basically, they say “I will always reclaim the WeakReference. If the object is a SoftReference, I will decide what to do based on the ecosystem conditions”. This makes a SoftReference very useful for the implementation of a cache: as long as the memory is plenty, we do not have to worry of manually removing objects. If you want to see an example in action, you can check this example of a cache implemented with SoftReference.

PhantomReference: Ah, PhantomReferences! I think I can count on the fingers of one hand how often I saw them used in a production environment. An Object that has only being referenced through a PhantomReference them can be collected whenever the Garbage Collector wants. No further explanations, no “call me back”. This makes it hard to characterise. Why would we like to use such a thing? Are the other ones not problematic enough? Why did I choose to be a programmer? PhantomReference can be used exactly to detect when an object has been removed from memory. Being fully transparent, I recall two occasions when I had to use a PhantomReference in my entire professional career. So do not get stressed if they are hard to understand now.

Hope this has clear a little bit the idea you previously had about references. As in any matter of learning, you might want to start to be practical and play around with your code and see how can you improve it. A first step would be to see if you are having any memory leak, and see if you can use any of the lessons learned here to get rid of those nasty memory leaks. If you have liked this article or it did help you, feel free to share and/or leave a comment. That is the currency that fuels amateur writers.

Читайте также:  Как писать скрипты для андроид

Thanks to my colleague Sebastian for his input on the article!

Источник

How to Fix Mobile Data Not Working on Android

Cellular data, mobile data, whatever you want to call it, is one of those things that only becomes a life necessity once you acquire your first smartphone. It’s only when you lose connectivity that you realize you don’t know how to get anywhere without Google Maps, don’t have anything to read without Flipboard, and don’t know how to communicate with people through any medium other than WhatsApp.

When mobile data stops working on Android, it’s world-shattering, in other words. Here are some tips on how to get it back.

Also read: How to Create Your Own Android Widget

Reset Your APNs

Access Point Names (APNs) are the means by which your mobile network provider connects your phone to the mobile Internet. It sets your phone up with all the crucial settings, like IP addresses and gateways, to (hopefully) get you connected. However, this process can sometimes go wrong and require a reset. The following shows how to do it.

Go to “Settings -> Network & internet -> Mobile network -> Advanced -> Access Point Names.”

You should see a list of APNs (potentially with only one network on them). Tap the menu icon at the top right, then “Reset to default.”

Set APN Protocol to iPv4/IPv6

This option doesn’t exist in the APN settings of all phones, but some devices (like the OnePlus 3) give you the option of leaving the APN Protocol field blank. If that’s the case in your network’s APN settings, make sure it says IPv4/IPv6 instead. Likewise, with other devices, make sure it says this rather than just one of the two.

Enter Your APN Settings Manually

It’s a sad but not uncommon occurrence for your APN settings to get out of whack after an Android software update, and if a standard reset doesn’t fix the problem, then you may need to enter your APN address manually.

1. Go to your APN list using the method in the previous tip, then tap the “+” icon in the top-right corner.

3. Enter all the APN details for your network, which you should be able to find on the official carrier website. Or you can check out this list of APN settings for US, UK, Indian and other national carriers.

4. Save your new APN settings, then select them from the APN list on your device.

Wipe Cache Partition from Recovery

On your phone, there’s a fair portion of your device’s memory dedicated to the cache – where data for various apps and processes is stored “on the backburner,” activating automatically so that these apps and processes boot up more quickly on your device.

But sometimes, as reported by certain Android users, errors can occur in the cache which can cause crucial processes – in this case your data connection – to stop working. To fix this, you need to clear the system cache partition, which is accessed from your phone’s recovery screen. Getting to your recovery varies slightly between phones, but on a standard stock Android device, do the following:

Switch off your phone, then when switching it back on, hold the Power and Volume Down buttons until the Android droid pops up on your screen.

Use the volume buttons to navigate to “Recovery Mode.” On the next screen, it may “No command.”

If you see this, you need to try holding different combinations of the volume buttons and the power button until you enter recovery (depending on your device).

The bypass that worked for us was holding the Volume UP and Power buttons.

Once you’re in recovery, use the volume buttons on your phone to select “wipe cache partition” or “wipe cache,” then select the option using the power button.

Читайте также:  Удобные планировщики дел для андроид

The process should only take a few seconds. Once it’s done, reboot your phone.

Reset Your Phone’s Network Connection

A simple and powerful fix for data not working on your Android device is to enter an SCRTN (Special Code to Reset the Network). Note that this fix will only work for phones using CDMA networks. In the U.S., these networks are T-Mobile, Verizon and US Cellular.

Assuming you’re with a CDMA network, go to your phone dial pad and enter the following code, depending on your device:

  • Google Pixel, Moto G7: *#*#72786#*#*
  • Nexus 5, Nexus 6, Moto G5: #*#*72786##
  • Other Android phones: ##72786#

Note that phone carriers are slowly trying to phase out CDMA networks, as they seek to move wholly onto the faster, more recent LTE standard, so this particular fix may not exist for much longer.

Also read: How to Fix the Obtaining IP Address Error on Android

Enable the Right Network Mode

Starting with the simplest solution, it’s possible that during an update, or simply in the phone’s default settings, the network mode (3G, 4G, etc.) of your phone is set to one that doesn’t offer optimal coverage.

If you have a 4G phone, for example, you should always make sure 4G is selected in your network modes to catch those sweet 4G rays. Or if your phone isn’t 4G but you’re running on an OS that features it as a network mode (by rooting, for example), your phone may be trying to connect to 4G signals that it’s not capable of.

Changing this is simple. Go to “Settings -> Network & Internet -> Mobile network -> Preferred network type,” then switch to the one that best suits your phone. As my phone is a 4G, I go for 2G/3G/4G Auto so that it always tries to connect to the best signal available.

Also read: How to Fix Android Delayed Notifications Issue

Remove and Re-Insert Your SIM Card

Some will scoff at the very mention of suggestions like “reboot your phone” and “remove and reinsert your SIM card,” but these should always be the first port of call when trying to fix mobile data issues. Another option is to test your phone with another SIM card to see if the issue originates in the phone or the card.

There’s also an extra little trick to rebooting your phone that could help:

  • Before rebooting, turn on Airplane Mode.
  • Wait for 30 seconds, then turn Airplane Mode off.
  • If you still don’t have data, turn airplane mode back on, turn your phone off, wait for a minute, turn your phone back on, turn airplane mode off, wait for 30 seconds, then turn mobile data on.

If this fails, then try the following fixes.

Do You Have a Mobile Data Limit?

Every Android phone lets you set your own mobile data limits and warnings for when you’re about to reach your limit. These aren’t usually switched on by default, but maybe you set a limit previously, have since upgraded your tariff, and have forgotten to update your mobile data limit accordingly. To check this:

Go to “Settings -> Network & Internet -> Mobile network.”

Make sure “Mobile data” is switched on, then tap “Data warning & limit.”

Here you need to make sure that “Set data limit” is switched off, or at least that it isn’t any lower than the limit provided by your network.

There it is: the key to getting you back online just when you thought you’d have to start resorting to paper maps and pigeon mail to communicate with people.

Also read: How to Eliminate the “Unfortunately, App Has Stopped” Messages

Now that you have mobile data working again, why not put it to the test with one of these Internet speed test apps. Alternatively, check out our list of the best Firefox for Android add-ons.

Never Miss Out

Receive updates of our latest tutorials.

Content Manager at Make Tech Easier. Enjoys Android, Windows, and tinkering with retro console emulation to breaking point.

Источник

Оцените статью