Android Activity


An Activity is a single,focused thing that the user can do, according to official android documentations.

The term clearly stems from the verb act which basically means performing an action or interacting with something.

Even though we can have an activity without visual components, most activities get created to host views and widgets by which users can interact with.

Activities can therefore vaguely refer to the whole screen with which the user will interact with.

With this way of thinking here are some of the things we can do to our activity:

No. Action Description
1. Open new activity This then replaces the current activity or screen.
2. Close the current activity So that it's no longer visible to us. Android System will not kill it completely, just put in the background,lest you come back to it again.
3. Rotate the device Say you are watching a video or playing a game from this app and you want to view it in different layout. This process causes the recreation of the activity so as to cater for your layout needs.

Doing things like the above causes android system to raise various life cycle callbacks. These are basically methods that get raised in an event driven manner at various stages in the lifecycle of an activity. For example, creation, pausing, resuming, starting,restarting,stopping etc.

Presentation mechanisms for an Activity

Activities can be presented in various ways in android:

No. Mechanism Description
1. Full Screen Window : Most common way of presenting an activity.With this they cover the full screen.
2. Floating Windows : Activities can be set to as floating windows via a theme with windowIsFloating attribute set.
3. Embedding : Activities can also be embedded inside another activity using ActivityGroup.

However note that embedding is no longer attractive as the ActivityGroup was deprecated with the introduction of Fragments way back in API level 13.Fragments and Fragment Transaction APIs does this in a better, more modular way.If anything fragments are basically subactivities howevr, with their own lifecycle.

Activity class Definition

Let's also see a programmatic description of an activity.

First it belongs to android.app package:

package android.app;

Activity is a class like any other class but also unique in its own way too. It's also public, so it's visible and usable within other packages outside its own.

public class Activity..{}

Being a class makes it also have Object Oriented features that other classes do have like:

  1. Ability to derive from other classes and be derived from.
  2. Ability to implement interfaces.
  3. Ability to have its own methods, fields and inner classes.

In fact the Activity class derives from ContextThemeWrapper class.

public class Activity extends ContextThemeWrapper..{}

The ContextThemeWrapper gives the Activity class the ability to manipulate and modify the theme from what is in the wrapped context.

Furthermore an Activity implements several interfaces:

public class Activity extends ContextThemeWrapper implements LayoutInflater.Factory2 Window.Callback KeyEvent.Callback View.OnCreateContextMenuListener ComponentCallbacks2{}

Activity's Children and GrandChildren

That is activity's direct subclasses and indirect subclasses.

Here are the direct subclasses:

No. Activity Description
1. FragmentActivity The super class used by activities wanting to Fragments and Loader APIs using support library
2. NativeActivity For those who want a convenient activity to be implemented purely in native code.
3. ListActivity An activity specializing in a displaying a list of items bound to a data source.
4. ExpandableListActivity An activity specializing in displaying expandable list of items bound to a data source.
5. AliasActivity Provides alias-like mechanism to an activity. It does this by launching another activity then killing itself.
6. AccountAuthenticatorActivity Super class to create activities that implement AbstractAccountAuthenticator.
7. ActivityGroup Deprecated back in the API 13 after the introduction of Fragments. Before that it was the way to create to create a screen that has multiple embedded activities.

Well those are the activity's children.

Let's now look at the grandchildren/indirect subclasses.

No. Activity Main Parent Description
1. AppCompatActivity FragmentActivity AppCompatActivity is the super clas for activities planning to utilize action bar features.
2. ActionBarActivity AppCompatActivity Deprecated. Before that it was used to provide action bar features to activities. Now that role has gone to AppCompatActivity.
3. TabActivity ActivityGroup Deprecated way back in the API level 13. Before that it was used to create Tabbed Activities.Now Fragments can do that.
4. PreferenceActivity ListActivity The super class to be used for those intending to show a hierarchy of preferences to users.
5. LauncherActivity ListActivity This will display a list of all activities which can be performed for a given intent.

Capabilities Activity class provides its children

We can, and have said that activities represent single focused thing a user can do.

So we know it allows us use and render views and widgets that users can interact with.

However, let's now come and explore more detailed and specific functionalities from a lower level that the Activity class gives to it's children.

1. Context capabilities
  1. Checking various permissions : For example: the checkPermission(String permission, int pid, int uid) will determine whether a particular process and user ID running in the system has the passed permission,checkUriPermission(Uri uri, int pid, int uid, int modeFlags) will determine whether a particular process and user ID running in the system has permission to access the passed Uri etc.
  2. Connect to or create application service : Context can be used to connect to application service or create it if needed.This done via the bindService(Intent service, ServiceConnection conn, int flags) method call. 3.Create other Contexts : For example createConfigurationContext(Configuration overrideConfiguration) will create a new Context object for the current context but with resources adjusted to the passed configuration,createPackageContext(String packageName, int flags) returns a new Context object for the given application name.
  3. List Associated Databases and Files : databaseList() will provide us with a string array with the private databases associated with this Context's application package while fileList() returns a string array with the private files associated with this Context's application package.
  4. Delete Associated Database and File : Context provides us methods: deleteDatabase(String name) to delete the SQLiteDatabase associated with this Context's application's package and deleteFile(String name) to delete the given private file associated with this Context's application package. 6.Getting Application Context : Context's getApplicationContext() will return us the single global Application object of the current process. 7.Getting Application Information : Via the getApplicationInfo() we can get the full application information of the current Context's package.

Quick Activity Examples

1. How to Start an Activity

To start an activity you need an Intent object. Let's create a method that can start for us an activity. This method will take a context object as well as the class name for the target activity, that is the activity we want to open.

    void start(Context c, Class e){
        Intent i = new Intent(,e);
        c.startActivity(i);
        //a.finish();
    }
2. How to Finish/Kill an Activity

To finish an activity we use the finish() method.

    void killIntent(Context c){
        Intent i = new Intent(c,MainActivity.class);
        c.startActivity(i);
        c.finish();
    }
3. How to determine if an activity is in the foreground

This example method can determine for us if an activity is in the Foreground or not. It returns a boolean value based on the result.

    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            returnfalse;  
        } 
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;  
            } 
        } 
        returnfalse;  
    } 

    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    } 

Top Full Android Activity Examples

Let's look at some examples.

Android Activity Examples.

Android ListActivity Tutorial and Examples.

A ListActivity is an activity that displays a list of items by binding to a data source such as an array or Cursor. ListActivity also exposes to us event handlers when the user selects an item.

This is a class that derives from the Activity class. ListActivity is meant to be used when you plan to use a ListView. In fact it does host a ListView object that can be bound to different data sources, typically either an array or a Cursor holding query results.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post