will android restart an activity

will android restart an activity

Search for: will android restart an activity

restart activity

Search Google for: restart activity

Search Android Developers Group for: restart activity

Search Android Beginers Group for: restart activity

Search Google Code for: restart activity

Search Android Issues Database for: restart activity

Read this thread on activity restarts

http://developer.android.com/guide/topics/fundamentals.html

You will need to understand the onSaveInstanceState and onRestoreInstanceState methods. These are useful for

When the system, rather than the user, shuts down an activity to conserve memory, the user may expect to return to the activity and find it in its previous state.

When does android close a foreground activity?

Search for: When does android close a foreground activity?

I understand due to orientation changes or other configuration changes. when else?

http://developer.android.com/reference/android/app/Activity.html

If the configuration of the device (as defined by the Resources.Configuration class) changes, then anything displaying a user interface will need to update to match that configuration. Because Activity is the primary mechanism for interacting with the user, it includes special support for handling configuration changes.

android:configChanges

Search for: android:configChanges

In some special cases, you may want to bypass restarting of your activity based on one or more types of configuration changes. This is done with the android:configChanges attribute in its manifest. For any types of configuration changes you say that you handle there, you will receive a call to your current activity's onConfigurationChanged(Configuration) method instead of being restarted. If a configuration change involves any that you do not handle, however, the activity will still be restarted and onConfigurationChanged(Configuration) will not be called.

onRetainNonConfigurationInstance

Search Google for: onRetainNonConfigurationInstance

Search Android Developers Group for: onRetainNonConfigurationInstance

Search Android Beginers Group for: onRetainNonConfigurationInstance

Search Google Code for: onRetainNonConfigurationInstance

Search Android Issues Database for: onRetainNonConfigurationInstance

A nice article on changing orientaion

from - http://peacemoon.wordpress.com

Faster Screen Orientation Change from Android

Read up on alternate resources

Understand how to load different layouts based on configuration

See alternate resources and how directories are organized for different possible resource settings

First and foremost, you should name all your views in your activity using the android:id attribute. This attribute is important for applications that change with screen orientation, because when Android destroys activities, it saves state only for named views. For example, suppose a user changes orientation in the midst of entering some text into an EditText view. When this happens, if you?ve named the EditText view using an android:id attribute, Android will persist any existing text inside the EditText view, and restore it automatically when the activity is recreated. In contrast, if the view does not have an android:id attribute, the system will not be able to persist the text, so when it recreates the activity, any already-entered text will be lost.

...Quoting from one of the articles above


layout\main.xml
layout-land\main.xml
layout-port\main.xml

Fix orientation in the manifest to one type
In the manfiest file you handle it yourself
specify alternate resources
handle onsaveinstancestate
handle onretainnonconfigurationinstance
provide ids to views

Killi Process with files on SD card

Search Google for: Killi Process with files on SD card

Search Android Developers Group for: Killi Process with files on SD card

Search Android Beginers Group for: Killi Process with files on SD card

Search Google Code for: Killi Process with files on SD card

Search Android Issues Database for: Killi Process with files on SD card

ohhh read this

The activity is restarted but not the process!!!

quote

This means that views have a reference to the entire activity and therefore to anything your activity is holding onto; usually the entire View hierarchy and all its resources. Therefore, if you leak the Context ("leak" meaning you keep a reference to it thus preventing the GC from collecting it), you leak a lot of memory. Leaking an entire activity can be really easy if you're not careful.

When the screen orientation changes the system will, by default, destroy the current activity and create a new one while preserving its state. In doing so, Android will reload the application's UI from the resources. Now imagine you wrote an application with a large bitmap that you don't want to load on every rotation. The easiest way to keep it around and not having to reload it on every rotation is to keep in a static field:

The second solution is to use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().

java weak reference

Search for: java weak reference

http://weblogs.java.net/blog/2006/05/04/understanding-weak-references

when you have a reference to an object and when it is weak, we are willing to let go and accept a null in its place. Pooof it goes from your program. Like a word written with a temporary ink that fades away from view, except for its shell the weak reference standing there like a ghost.

Has a cart load of apples. Clients come and buy half of them. Late in the day when the night falls the remaining apples just melt away, except for those that were sold.

An explanation by Rob Wilson

...The most common use of weak references is indirect - they are used internally by the WeakHashMap class. Like HashMap, WeakHashMap associates key objects with values. However, once the key object becomes inaccessible via stronger references it becomes eligible for garbage collection. When it is freed, the map entry magically disappears. The assumption here is that if you are not using the key anywhere other than in the map you will have no need to look it up, so it should be freed.

Refernce Objects and Garbage Collection

Search for: Refernce Objects and Garbage Collection

WeakHashMap

Search for: WeakHashMap

weakreference API

This can allow to cleanout resources even if deregistration from a registry is feasible

Reference Objects and Garbage Collection - Monica Pawlan

So, weak references allow you to refer to an object without keeping it from being collected. If the garbage collector collects a weakly reachable object, all weak references to it are set to null so the object can no longer be accessed through the weak reference.


public class DisplayImage extends Applet {

        SoftReference sr = null;

        public void init() {
            System.out.println("Initializing");
        }

        public void paint(Graphics g) {
            Image im = (
              sr == null) ? null : (Image)(
              sr.get());
            if (im == null) {
                System.out.println(
                "Fetching image");
                im = getImage(getCodeBase(),
                   "truck1.gif");
                sr = new SoftReference(im);
           }
           System.out.println("Painting");
           g.drawImage(im, 25, 25, this);
           im = null;  
        /* Clear the strong reference to the image */
        }

        public void start() {
            System.out.println("Starting");
        }

        public void stop() {
            System.out.println("Stopping");
        }

}

Soft and weak reference objects are placed in their reference queue some time after they are cleared (their reference field is set to null). Phantom reference objects are placed in their reference queue after they become phantomly reachable, but before their reference field is cleared. This is so a program can perform post-finalization cleanup and clear the phantom reference upon completion of the cleanup.

Weak references work well in applications that need to, for example, associate extra data with an unchangeable object, such as a thread the application did not create. If you make a weak reference to the thread with a reference queue, your program can be notified when the thread is no longer strongly reachable. Upon receiving this notification, the program can perform any required cleanup of the associated data object

Other articles from Ms Pawlan

if the configuration change is one that can be handled by this activity. Also when this is called the activity is NOT restarted.

Here is api for the configuration class

You can put stuff into the bundle in this method. This bundle is then passed to the subsequent invocation oncreate() and also the "onrestoresavedinstancestate()".

From A you go to B. B is working hard. If you hit the back button, you will see A with its previous state. This happens most of the time. However if A is reclaimed before hitting back, then it won't have its state unless it is saved and restored.

Go from A to B and then press back to go back to A. There is no reason to restore state for B as B is being shutdown. (Especially in the same app). So the savestate is not called.

If called, this method will occur before onStop(). There are no guarantees about whether it will occur before or after onPause().

onrestoreinstancestate is called between onstart and onPostcreate

you should read this onsavedinstancestate docs

onRetainNonConfigurationInstance

is called, unlike save and restore, only for configuration changes. called between onstop and ondestroy. You will use method getLastConfigurationInstance() to retrieve the object. It is assumed that a new instance will be immediately created.

android activity stuck in landscape mode

Search Google for: android activity stuck in landscape mode

Search Android Developers Group for: android activity stuck in landscape mode

Search Android Beginers Group for: android activity stuck in landscape mode

Search Google Code for: android activity stuck in landscape mode

Search Android Issues Database for: android activity stuck in landscape mode


07-30 20:08:11.525: INFO/ActivityManager(67): 
Config changed: { 
  scale=1.0 
  imsi=0/0 loc=en_US 
  touch=3 
  keys=2/1/1 
  nav=3/1 
  orien=2 
  layout=18 
  uiMode=17 
  seq=39
}

Why use OnRetainConfigurationInstance()

Search for: Why use OnRetainConfigurationInstance()

Everytime when configuration chagnes, one is guaranteed to see the save and restore instance methods. One could use the bundles in those methods to do this. why do this in the onRetainConfigurationInstance()? Because you have to maintain state anyway because you are going down and up again.

May be because, the two states could be different and there is a level of optimization you could get. For example if you have a lot of state that you need to worry about only if the configuration changes then you dont need to do that in save and restore if the configuration hasnt altered.

Android Architectural Predicates

use android:screenOrientation attribute

android:screenOrientation

Search for: android:screenOrientation

possible values for android:screenOrientation

Example

landscape
portrait
unspecified
user
behind
sensor
...and more

Note: When you declare one of the landscape or portrait values, it is considered a hard requirement for the orientation in which the activity runs. As such, the value you declare enables filtering by services such as Android Market so your application is available only to devices that support the orientation required by your activities. For example, if you declare either "landscape", "reverseLandscape", or "sensorLandscape", then your application will be available only to devices that support landscape orientation. However, you should also explicitly declare that your application requires either portrait or landscape orientation with the <uses-feature> element. For example, <uses-feature android:name="android.hardware.screen.portrait"/>. This is purely a filtering behavior provided by Android Market (and other services that support it) and the platform itself does not control whether your app can be installed when a device supports only certain orientations.

android:configChanges possible values

Examples

mcc
mnc
locale
touchscreen
keyboard
keyboardHidden
navigation
screenLayout
fontScale
uiMode
orientation
screenSize
smallestScreenSize

use Ctrl-f11 or ctrl-f12
or keypad 7 and 9

Couple of articles seem to suggest that if I set the android:screenOrientation to portrait then it will not be restarted and will stay portrait even if the device is rotated.

However on 2.3 when I tested this couple of things happens. The view will stay portrait even if the orientation is landscape.

However it is restarting the activity!! I don't want that

I have used the following settings to get what I wanted.


android:screenOrientation="nosensor"
android:configChanges="orientation|keyboard|keyboardHidden"

Setting the orientation to no sensor seem to stop the device from switching the configuration. The configChanges attribute seem to stop the RESTART of the activity. Ofcourse I have to override the corresponding method in the activity


@Override
public void onConfigurationChanged(Configuration newConfig) {
  super.onConfigurationChanged(newConfig);
  //Nothing to do I am going to ignore it
  Log.d(tag,"I am ignorign the configuration chagne");
}

android screen orientation nosensor

Search for: android screen orientation nosensor

if I just have nosensor will my activity get restarted?

Search for: if I just have nosensor will my activity get restarted?

Int he emulator the orientation flag by itself is not stopping a restart. For example if i press ctrl-f12 the emulator is rotated. This is resulting in a restart. The actual device may not do this by mere rotation if you disable the sensor reaction. However even on the device if you were to explcitly choose a particular orientation (which may be equivalent to ctrl-f12) same things may result.

it is worthwhile testing this behavior on a real device.

but for now I am satisfied to override the configuration change and ignore it as I have done above.

I know there is a call back to pass model objects between view restarts due to configuration changes. These may be in memory objects.

if the data is not large you may want to prefer bundles through restore state callbacks.


//Begining...
onCreate
onStart
onRestoreInstanceState
onResume


//configuration changed
onSaveInstanceState
onPause : partially visible ui
onStop: ui invisible
onRetainNonConfigurationInstance: an local objects you want to remeber
onDestroy

//Back to begining

So by the time onResume happens you restored your instance state

this means your activity is not destroyed. it is merely stopped and restarted. This also means this is not a configuration change. So save and restoreinstance methods may not be called. configurationinstance callback is not called either.

Android activity onPostCreate

Search for: Android activity onPostCreate

Docs on onPostCreate

Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

So it happens prior to onResume...


//Test going back and restart
New activity
Go back
Restart the app from app panel

//Test going back and revisit
Go home
Revisit the app by pressing long on home

//Test going home and restart
Go home again
Restart the app from the app panel

//Test going back and revisit
Go back
Revisit the app by pressing long home

I will tell you the calling sequence. There are some surprises.


//New activity
onCreate
onStart
onResume

//Go back
onPause
onStop
onDestroy

//Restart the app from app panel
onCreate
onStart
onResume

When you press back you would think the activity is not destroyed as you expect to come back to the activity. But that is what is happening on "back". The activity is actually getting destroyed. As you will shortly this doesn't happen on going home.

However the activity is destroyed the process is kept in memory as you can see it by long clicking the hoem button to see the active processes.

Also, not a surprise, notice that the onRestart is not called because the activity is destroyed. so a brand new onCreate is called.


//Go home
onSaveInstanceState: ?? why?
onPause
onStop

//Revisit the app by pressing long on home
onRetart: Notice no oncreate
onStart
onResume: Notice no onRestoreInstancestate

May be the onRestoreInstanceState is not called because I havent' saved anything? is that a result of optimization? Not sure!!!


//Go home again
onSaveInstanceState: ?? why?
onPause
onStop

//Restart the app from the app panelonRetart: 
Notice no oncreate
onStart
onResume: Notice no onRestoreInstancestate

The revisit and restart behavior is identical in this case.


//Go back
onPause
onStop
onDestroy

//Revisit the app by pressing long home
onCreate
onStart
onResume

Notice, no save instance, no non configuration object instance. The activity is destroyed with no indication or opportunity of saving the instance state.

when you go home and come back, the UI state is maintained and the activity is not lost. its local pointers hang around. On back the activity is destroyed. It is as if you are restarting the activity.

However if you have a background task, when the activity starts it may want to recognize it if it is running!!!

if you are going home then UI may be preserved. this means

1. you don't restore state 
2. nor configuration instance is called
3. local pointers are still valid

when you go back,

1. the whole activity is destroyed
2. No opportunity to save/restore instances
3. onNonConfiguration instance not called 
4. stop/destroy called
5. A subsequent start of the activity is a brand new start

onSaveInstance..
onPause
onStop
onRetainNonConf...
onDestroy

//followed by
onCreate
onStart
onRestore
onResume

Create I - Brand new create
Restarted - Restarted with out destroying the UI
Create II - Recreated after a configuration change

Restarted with hints to save/restore state (flip)
Restarted by keeping state intact (home/revisit)
Restarted by keeping no state at all (new start)

New - A brand new activity

New like - A new activity that has left earlier a pending task
   - difficult to distinguish from the first one
   - a back may have indirectly finished the activity
   - only way to know is to indicate that you have a pending item to deal with

Same state - UI is not disturbed
   - ex: home and returning to the activity
   -     or a phone call ends 

Restart with save state hint - typically due to a config change
   - onRestoreInstanceState gets called
   - onRetainNOn... is called before during shutdown

//Dialog is retained

//Order of calls

onSave..
onPause
onStop

onRestart
onStart
onResume

A Back on an activity may or will kill/finish the activity

where as A Back with a dialog on an activity will simply close the dialog

As a dialog shows up on top of an activity i thought the activity will fire off life cycle dialogs. It doesn't. It behaves as if it is another view that is part of the view state...

onRetainNonConfigInstance is deprecated since API 13

Recommendation is to use fragments explicitly and use setRetainInstance

These guarantees are designed so that an activity can use this API to propagate extensive state from the old to new activity instance, from loaded bitmaps, to network connections, to evenly actively running threads. Note that you should not propagate any data that may change based on the configuration, including any data loaded from resources such as strings, layouts, or drawables.

The guarantee of no message handling during the switch to the next activity simplifies use with active objects. For example if your retained state is an AsyncTask you are guaranteed that its call back functions (like onPostExecute(Result)) will not be called from the call here until you execute the next instance's onCreate(Bundle). (Note however that there is of course no such guarantee for doInBackground(Params...) since that is running in a separate thread.)

Retaining fragments is a generalization of this basic need that is illustrated by this method.

If an object holds a pointer to a current activity, that activity can get restarted and the object may have a stale handle of the activity.

An example of this stand alone object could be an async task. Or it might be a large worker object that you dont want to recreate willy nilly when the device is rotated.

This object is really a part and parcel of the activity but you don't want that object to be recreated.

A simple answer (as it turns out a wrong one) is to look for the activity call backs and tell this object the new pointer of the activity.

But how does the activity knows what this object is?

You may say, pass it through a bundle. But the bundle has no API to store object pointers to reestablish that connection.

Try as hard as you may you cannot do this type reconnecting from inside the activity unless the owner of the activity provides a mechanism to reconnect them.

This is precisely the need for onRetainConfigurationInstance()! The OS is saying by calling this method, that the activity is going to restart and the OS is going to remember "ONE" and "ONLY ONE" object reference that is associated with this activity.

This allows you to ask the OS (through the newly minted activity), Hey, where is my object that I told my old activity that he/she is related to

You get that object back if you were to call the getRetainedNonConfigInstance.

This stand alone object is called, now rightfully, the "non configuration instance"! Because it is that portion of the activity that does not depend on a configuration change and wants to get re attached with every instance of the activity.

A better name would have been "THE EXTERNAL OBJECT" that stays around and associated to the activity.

I am guessing here...

There is a drawback to this overloaded method. There is only one object root that can be done this way. what if your activity is inherited from a set of libraries where each library has extended the activity in their own way. what if each library has their own root object to be remembered across activity invocations?

that will be trouble. Only one of them can save theirs unless they cook up their own protocol and agree on a meta-root.

In comes fragments. The OS said, ok, with fragments, you can add as many fragments as you want to an activity. And if you tell them to hang around I will just bring keep them around.

Because fragments are many, now the clients have the ability to store as many roots as you want!!

being a fragment you get one more contract with the activity. Not only that you can retain state, but these objects (fragments) can follow the state of the activity. An added benefit should you want that information to be put to use

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.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

onRetainNonConfigurationInstance and isFinishing

Search for: onRetainNonConfigurationInstance and isFinishing