Android Activity Best Practice

This article will show you three best practice when use android activity class. These best practice can make your java source code simple and clear.

1. Make Activity Extends A Base Activity.

If your android app need several activities, you had better create a base activity which extends android.support.v7.app.AppCompatActivity. Then make other activity extends the base activity.

This can make some general task code management easily such as log data when activity is created, finish all activity when the android app exit.

BaseActivity.java

package com.dev2qa.example.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.dev2qa.example.util.ActivityManagerUtil;

/**
 * Created by Jerry on 12/11/2017.
 */

public class BaseActivity extends AppCompatActivity {

    private static final String TAG = "BaseActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, this.getClass().toString());
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManagerUtil.finishAllActivity();
    }
}

2. Manage All Activity In A Util Class.

In android app we can type Back menu to quit an activity. But how to quit all activities when you click a single button or type the back menu once or when the main activity exit?

You can create an activity manager util class to do this like below. So you can call below class’s finishAllActivity() method in base activity destroy() method.

ActivityManagerUtil.java

package com.dev2qa.example.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jerry on 12/11/2017.
 */

public class ActivityManagerUtil {

    // This list is used to save all activities.
    private static List<Activity> activityList = new ArrayList<Activity>();

    // Add an activity in activityList.
    public static void addActivity(Activity activity)
    {
        if(activityList==null)
        {
            activityList = new ArrayList<Activity>();
        }

        if(activity!=null) {
            activityList.add(activity);
        }
    }

    // Finish and remove an activity from activityList.
    public static void finishActivity(Activity activity)
    {
        if(activityList!=null)
        {
            if(activity!=null && activityList.contains(activity)) {
                activity.finish();
                activityList.remove(activity);
            }
        }
    }

    // Finish and remove all activity in activityList.
    public static void finishAllActivity()
    {
        if(activityList!=null)
        {
            // First finish all the activity in the list.
            int size = activityList.size();
            for(int i=0;i<size;i++)
            {
                Activity activity = activityList.get(i);
                activity.finish();
            }

            // Then remove all the activity in the list.
            for(int i=0;i<size;i++)
            {
                activityList.remove(i);
            }
        }
    }

    // Print all activity info in current task back stack.
    public static void printCurrentTaskActivityList(Context context, String tagName)
    {
        ActivityManager activityManager = (ActivityManager) context.getSystemService( context.ACTIVITY_SERVICE );

        List<ActivityManager.AppTask> appTaskList = activityManager.getAppTasks();

        if(appTaskList!=null)
        {
            int size = appTaskList.size();
            for(int i=0;i<size;i++)
            {
                ActivityManager.AppTask appTask = appTaskList.get(i);
                ActivityManager.RecentTaskInfo recentTaskInfo = appTask.getTaskInfo();

                int taskId = recentTaskInfo.persistentId;

                int activityNumber = recentTaskInfo.numActivities;

                ComponentName origActivity = recentTaskInfo.origActivity;

                ComponentName baseActivity = recentTaskInfo.baseActivity;

                ComponentName topActivity = recentTaskInfo.topActivity;

                Log.d(tagName, "Task Id : " + taskId);
                Log.d(tagName, "Activity Number : " + activityNumber);

                if(origActivity!=null) {
                    Log.d(tagName, "Original Activity : " + origActivity.toString());
                }

                if(baseActivity!=null) {
                    Log.d(tagName, "Base Activity : " + baseActivity.toString());
                }

                if(topActivity!=null) {
                    Log.d(tagName, "Top Activity : " + topActivity.toString());
                }

                Log.d(tagName, "************************************************");
            }
        }
    }
}

3. Provide Activity Startup Method For Others.

If your activity’s startup need some extra input data, you need put those data in the intent object and then start the activity.

READ :   Android Activity Launch Mode SingleTask SingleInstance Example

But you can encapsulate a startup method for your activity with the input data as the method input parameters. This way can make your activity startup clear and simple.

Start activity example code before encapsulate.

Below code start SecondActivity from FirstActivity

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("userName", "Tom");
intent.putExtra("password", "******");
startActivity(intent);

To make code simple and clear, we can add below method in SecondActivity class.

public static void startActivity(Context context, String userName, String password)
{
    Intent intent = new Intent(context, SecondActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("userName", "Tom");
    intent.putExtra("password", "******");
    context.startActivity(intent);
}

Then we can start SecondActivity in other activity source code like below. Below code is simple and clear to reader.

SecondActivity.startActivity(getApplication(), "Tom", "******");
(Visited 683 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.