Tuesday, 19 May 2015

Android activity life cycle - what are all these methods for?


What is the life cycle of an Android activity? Why are so many similar sounding methods (onCreate()onStart()onResume()) called during initialization, and so many others (onPause()onStop()onDestroy()) called at the end?
When are these methods called, and how should they be used properly?
shareedit
9 
Why this question has been upvoted so many times? Why it has not been closed? –  Alex May 26 '13 at 19:29
14 
Why close a question with a lot of upvotes? Stackoverflow has a bad habit of that. –  Richard Jun 11 '14 at 20:16
2 
This is a wiki-style question and I feel it should be allowed on the site. –  Mateen Ulhaq Nov 29 '14 at 22:00
   
How to go directly from onResume() to onPause() in an activity? –  The Hunter Apr 9 at 16:57

6 Answers

up vote345down voteaccepted
See it in Activity Lifecycle (at Android Developers).
Enter image description here
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
Called after your activity has been stopped, prior to it being started again. Always followed by onStart()
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
When the Activity first time loads the events are called as below:
onCreate()
onStart()
onResume()
When you click on Phone button the Activity goes to the background and the below events are called:
onPause()
onStop()
Exit the phone dialer and the below events will be called:
onRestart()
onStart()
onResume()
When you click the back button OR try to finish() the activity the events are called as below:
onPause()
onStop()
onDestroy()

The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:
These states can be broken into three main groups as follows:
Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.
Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.
Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.
Sample activity to understand the life cycle*
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
    String tag = "LifeCycleEvents";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Log.d(tag, "In the onCreate() event");
    }
    public void onStart()
    {
       super.onStart();
       Log.d(tag, "In the onStart() event");
    }
    public void onRestart()
    {
       super.onRestart();
       Log.d(tag, "In the onRestart() event");
    }
    public void onResume()
    {
       super.onResume();
       Log.d(tag, "In the onResume() event");
    }
    public void onPause()
    {
       super.onPause();
       Log.d(tag, "In the onPause() event");
    }
    public void onStop()
    {
       super.onStop();
       Log.d(tag, "In the onStop() event");
    }
    public void onDestroy()
    {
       super.onDestroy();
       Log.d(tag, "In the onDestroy() event");
    }
}
shareedit
   
@Taqub Ahmad Thank you for the explanation.Now i got it :) –  Nav Dec 15 '11 at 15:05
   
So if I understood it correctly onStop() is always called after onPause() ? –  Titouan de Bailleul Oct 31 '12 at 16:19
3 
NOT always, "onStop(): Called when you are no longer visible to the user" –  Yaqub Ahmad Nov 26 '12 at 8:22
   
Is there anything by any chance that gets called before onCreate? –  Aaron Russell Sep 23 '13 at 3:31
1 
Yes there is - the default constructor (that's the one with no parameters). But it has only very limited use for very basic initialization purposes. Usually you should not use it unless you really know what you are doing. And even then you should think twice if there's a better way of doing things. –  Mjoellnir Feb 28 at 7:45
The entire confusion is caused since Google chose non-intuivitive names instead of something as follows:
onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change] 
The Activity Diagram can be interpreted as:
enter image description here
shareedit
   
Depends. Unless it solves confusion, a long name ain't hurt. Eg: onRoutePresentationDisplayChanged() is very much a function from inside Android SDK –  Nilesh Pawar Apr 29 '13 at 18:45
   
If we had to type these method names often, the ones from the SDK present a good balance between length and being descriptive enough. However, IDEs have shortcuts to override these things and we don't really need to be calling them around, so longer descriptive names as these would have worked just nicely. This is more of a problem to beginners though. –  Daniel Jul 27 '13 at 10:46
3 
I personally don't find your names extremely more intuitive, plus with Fragments, it doesn't really correlate. – Martín Marconcini Aug 2 '13 at 21:44
2 
Upvoted. More helpful than the official documentation –  ronnieaka Mar 3 '14 at 5:41 
1 
+1 good job, thank you! –  necromancer Aug 5 '14 at 3:45

Application Skeleton to support multiple screen

http://stackoverflow.com/questions/12242111/application-skeleton-to-support-multiple-screen


As we know Android coming with various device which having different Features, Resolution and Screen-size so while developing an Application which support multiple(small and big) screen there is an obstacle of size and layout.
This leads to different combinations of screen sizes, resolutions and DPIs and creates quite a challenge when designing and developing for Android devices. While some other Manufacturer(non Android) have different resolutions and DPI, they share the same screen size and the resolutions follow the same aspect ratio. Therefore, an image can be created to fit the non Android devices.
My question is that is there a proper flow or architecture that one should follow to meet the requirement?
enter image description here
Remember we do have Tablets of different Size and Resolution.
I'm aware that Android Developer contains this information but my view is from implementation.
From my knowledge what I understood is that for designing Android graphics even Programmer must know the designing concept.
shareedit
13 
Are you Guys sure this question isn't constructive? –  hotveryspicy Sep 3 '12 at 5:03
6 
I think it is very constructive. Would like to know the reasons of the down votes. –  Lazy Ninja Sep 3 '12 at 5:13
11 
@MKJParekh take MicroMax Funbook gsmarena.com/micromax_funbook_p300-4701.php 7", 480X800, Ldpi (133 dpi) can you tell me in which category(drawble-large or Ldpi or if Android v3.0 sw-480) it will fall? –  hotveryspicy Sep 3 '12 at 6:55 
1 
@AZ_ :) We used this res structure in res folder drawable drawable-hdpi drawable-hdpi-v11 drawable-hdpi-v9 drawable-large drawable-large-hdpi drawable-ldpi drawable-mdpi drawable-mdpi-v11 drawable-small drawable-xhdpi drawable-xhdpi-v11 drawable-xxhdpi drawable-xxhdpi-v11 layout layout-small layout-sw530dp layout-sw720dp layout-xlarge values values-sw530dp values-sw720dp values-v14 values-xlarge and used well defined dimensions in xml from values folder. FYKI our application supports more than 5k types of devices. –  MKJParekh Aug 28 '14 at 8:52 
1 
@MKJParekh bro I have also used the same but I didn't use v9. Still haven't got any complaint from customer :) read this very informative opensignal.com/reports/2014/android-fragmentation –  AZ_ Aug 28 '14 at 9:58

2 Answers

up vote117down voteaccepted
Finally created a structure which handle layouts and icon for multiple screen.
Android generalises device displays into categories based on two parameters:
  • Screen size, the physical size of the display (measured diagonally)
  • Screen density, the physical pixel density of the display (in pixels-per-inch, or ppi)`
To determine screen size & density quickly, please install "What's my Size" app for Android.
Screen size
Android defines four generalised screen sizes:

 Qualifier           Size

 small               ~3 inches (approx) 
 normal              ~4 inches (approx) 
 large               Exceeds 4 inches    
 xlarge              Exceeds 7 inches  
  • Most phones are classified as small or normal (roughly 3 to 4 inches diagonally). But now, there are many phones with large screen such as Galaxy S4, HTC One, Xperia Z
  • A small tablet like the Samsung Galaxy Tab is classified as large (larger than 4 inches)
  • Extra-large applies to large devices, for example large tablets
Android defines four generalised screen densities:

 Qualifier         Description         Nominal value

 ldpi              low density          120 ppi
 mdpi              medium density       160 ppi
 hdpi              high density         240 ppi
 xhdpi             extra high density   320 ppi
Typically:
  • screen size has most impact on your app layouts
  • screen density has most impact on your image and graphic resources
It is listed here the percentage difference of device screen
  • Ldpi- 75%
  • Mdpi- 100% (base according to Android developer site)
  • Hdpi- 150%
  • XHdpi- 200%
enter image description here
But as we know now most of device coming with 480X800 so I'm consider this as based device, so our new calculation will like this
  • Ldpi- 50%
  • Mdpi- 66.67%
  • Hdpi- 100%
  • XHdpi- 133.33%
which means that first icon and design will be created for 480X800 only and then for rest ones(i.e. Ldpi, Mdpi, Xhdpi).
There are images which are common for all layout and must uniform in color and shape(no complex shape, no curve) so for this kind of image we are creating 9patch which to be put in “drawable(no-suffix)” folder. To create 9Patch image you can either use DrawNinePatch orBetterNinePatch
Now just rename your images based on Android's standards and complete your application with hdpi and then just take drawable-hdpi folder and Open Adode Photoshop(recommended) create Action of multiple size(just change the size according to percentage ratio) once Action created for all size then just do Batch Automate and give source(drawable-hdpi) and destination(drawable-ldpi, drawable-mdpi, drawable-xdpi).
The reason I insist you to use Photoshop because it will resize automatically your image with Actions and one more plus point is that you need not to rename the file(it will assign same name as original one).
once you completed with creation of all images, refresh your project and test it.
Sometimes there may be possibility that the layout which support screen(xhdpi, hdpi, mdpi) may be get cut in small screen(ldpi) so for handling this just create separate Layout folder(layout-small) for it and add ScrollView(mostly). Thats it.
Tablet Tablets are categorized into two size.
  1. 7"(1024X(600-48(navigation bar))) = 1024X552 (drawable-large)
  2. 10"(1280X(800-48(navigation bar))) = 1280X752 (drawable-xlarge)
In this we need to create image for both the screen and just put them accordingly
So all in all we will have this folder in our application to support multiple screen.
drawable
drawable-ldpi
drawable-mdpi
drawable-hdpi
drawable-xhdpi
drawable-large
drawable-xlarge
will be more qualifier combination with Screen size and Screen density
drawable-large-ldpi
drawable-large-mdpi
drawable-large-hdpi
drawable-large-xhdpi
more qualifier with Screen density and Version
drawable-ldpi-v11
drawable-mdpi-v11
drawable-hdpi-v11
drawable-xhdpi-v11
and more qualifier with Screen size and Version
drawable-large-v11
drawable-xlarge-v11
and more qualifier with Smallest width concept(SW)
 drawable-sw???dp
Further more in Android V3.0 Honeycomb they introduced new concept of SW(smallest width)in which device are categorized into screen width, so if we are creating a folder named drawable-sw360dp then the device with 720dp(either width or height) will use resource from the this folder.
for example to find the Samsung Galaxy S3 dp to suffix to drawable-sw?dp
With reference of DP Calculation, If you want to support your layout or drawable to S3 then the calculation says
px= Device's width = 720
dpi= Device's density= 320
formula given
    px = dp * (dpi / 160)
interchanging formula because we have px's value
    dp = px / (dpi / 160)
now putting value,
     dp= 720 / (320/160);
     dp=360. 
so drawable-sw360dp will do the job
Get you Device configuaration from GsmArena Sameway you can also create folder according to Device's Android API version i.e. drawable-hdpi-v11` so the device which is having API11 and it is Hdpi then it will use this resources.
Additional Tips:
  • Use relative layouts, dp, sp, and mm
    dp units - device independent pixels normalised to 1 physical pixel on a 160 ppi screen i.e. medium density. Scaled at runtime. Use for screen element dimensions
    sp units - scaled pixels, specified as floating point values, based on dp units but additionally scaled for the user's font-size preference setting. Scaled at runtime. Use for font sizes
    you should always use RelativeLayout for layouts; AbsoluteLayout is deprecated and should not be used.
  • Use appropriate image formats - PNG versus JPEG
    Android "prefers" PNG for bitmap image files, "accepts" JPEG, and "discourages" GIF.
    However, PNG and JPEG are not equivalents. They have different quality trade offs, and PNG is not always best:
    JPEG can offer up to 50% file-size reductions over PNG, which is significant if your app is image-intensive
    A higher quality "lossy" JPEG may look better than a highly compressed "lossless" PNG, for the same file size
  • Add labels to your images and graphics for debugging
  • Use the supports-screens element
  • Configure your emulators with real device values
    Conventionally, desktop systems display at 72ppi (Mac), or 96ppi (Windows, Linux). Compared with mobile, desktop displays are always low density.
    Always configure your Android emulators to mimic real device values, and always set them to scale to emulate device density.
    In Eclipse, it's easy to create multiple emulators (from the Eclipse menu bar, select Window > AVD Manager > New) configured with values for real devices:
    Name the emulator for the real device it's emulating Specify Resolution, don't use Built-in generic sizes Set the device density to match the real device (in the Hardware pane set Abstracted LCD Property to the real density, always an integer value)
    When you launch the device, always select Scale display to real size, and type in the real screen dimension in inches.
    If you don't set the device density, the emulator defaults to low density, and always loads ldpi-specific resources. Resolution (pixel dimensions) will be correct, but your density-dependent image resources will not display as intended.
    Of course, nothing you do will reproduce higher density image quality on a lower density desktop display.
Here is the Data collected during a 7-day period ending on October 1, 2012. To see the latest statistic about Android platform version, go to here
Based on Screen Size
enter image description here
Based on Screen Density
enter image description here
shareedit
2 
For samsung galaxy tab 7" we have to keep images under drawable-large-hdpi otherwise image will get stretched or shrinked. –  rajpara Sep 4 '12 at 7:08 
   
@rajpara there are lot of combination and permutation, we will include all such cases later on. – hotveryspicy Sep 4 '12 at 7:10
5 
+1 Great work man!! –  Dharmendra Jan 21 '13 at 6:42
1 
see @AlexBonel, ya I do agree with you, but my main motto is to make aware how things can be done when it comes to Multi-screen support. One can modify/manipulate this flow/concept because the above is for making clear the initial problem. Additionally I too do modification based on application design. Your post giving me sense that you understood the concept. Hope you got my point. –  hotveryspicy Mar 19 '13 at 13:37 
1