Sunday, 19 October 2014

Activities in Android

Background

An Activity in Android represents an User Interface that is rendered on a Single screen. It is what an user sees on Android devices and user interacts. Activity as an entity in Android has it's own set of APIs and life cycle. We will see that in this post.

Activity Lifecycle

Each Activity that you write will ultimately extend the class android.app.Activity.

Android Activity lifecycle is as follows -


As per the documentation an activity has essentially four states:

  1. If an activity in the foreground of the screen (at the top of the stack), it is active or running.
  2. If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
  3. If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
  4. If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

Sample Activity

public class HelloWorldMainActivity extends ActionBarActivity {



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_hello_world_main);

    }



    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.hello_world_main, menu);

        return true;

    }



    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar item clicks here. The action bar will

        // automatically handle clicks on the Home/Up button, so long

        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();

        if (id == R.id.action_settings) {

            return true;

        }

        return super.onOptionsItemSelected(item);

    }

}

Declaring the activity in the manifest

        <activity

            android:name=".HelloWorldMainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />



                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

Starting an Activity

Intent intent = new Intent(this, HelloWorldMainActivity.class);

intent.putExtra("Key", "Value");

startActivity(intent);

Terminating an Activity

public class TicTacToe extends Activity implements OnClickListener {



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_tic_tac_toe);

        setVolumeControlStream(AudioManager.STREAM_MUSIC);



        View exitButton = findViewById(R.id.exit_button);

        exitButton.setOnClickListener(this);

    }





    @Override

    public void onClick(View v) {



        switch(v.getId()) {

        case R.id.exit_button:

            finish();

            break;

        }



    }



}

Handling Runtime Changes

Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate()). The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that match the new device configuration.

To properly handle a restart, it is important that your activity restores its previous state through the normal Activity lifecycle, in which Android calls onSaveInstanceState() before it destroys your activity so that you can save data about the application state. You can then restore the state during onCreate() or onRestoreInstanceState().

Note :  Prefer using the onRestoreInstanceState() method than onCreate()  for restoring the instance state. Also the onSaveInstanceState() method is not called back button is pressed.

Handling the Configuration Change Yourself

If your application doesn't need to update resources during a specific configuration change and you have a performance limitation that requires you to avoid the activity restart, then you can declare that your activity handles the configuration change itself, which prevents the system from restarting your activity.
Note: Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.

For example, the following manifest code declares an activity that handles both the screen orientation change and keyboard availability change:

<activity android:name=".HelloWorldMainActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.

Notes  

  • To be of use with Context.startActivity(), all activity classes must have a corresponding <activity> declaration in their package's AndroidManifest.xml.
  • Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.
  • We can call finish() in an Activity to terminate it and return all the resources to OS.
  • When you rotate your Screen on Android device Activity is actually destroyed and recreated. However you can change this behavior by handling such configuration changes in your activity.

Some time back I had create a demo Tic-Tac-Toe Android Application covering most of the basic concepts and if you are new you can give it a glance. Should be pretty easy to understand. I have put it up on the git. Clone it on you local machine, import it in your Eclipse and go through it.

  • https://github.com/aniket91/TicTacToe


Note : Most of the above information is taken up from the documentation pages and combined to add all info about Activities that I find useful from programming point of view. Documentation pages liks are provided in Related links section below.

Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top