How to Use Android Activities

Android activities are the building blocks of Android applications, serving as the entry points to your app’s user interface and functionality. Understanding how to use Android activities is crucial for developing Android applications. In this comprehensive guide, we will explore the fundamentals of Android activities, discuss their lifecycle, and provide practical tips on how to effectively use them. Whether you’re a beginner or an experienced developer, this guide will help you grasp the concept of Android activities and make the most of them in your projects.

What are Android Activities?

In the world of Android app development, an activity represents a single screen with a user interface. It is the primary component of an Android application and plays a pivotal role in delivering the app’s user experience. Activities are like windows in a desktop application, providing a UI for users to interact with. Android applications can consist of one or more activities, and these activities work together to provide a seamless user experience.

The Android Activity Lifecycle

To effectively use Android activities, it’s essential to understand their lifecycle. Android activities go through various states, and each state provides developers with opportunities to manage and control the app’s behavior. The key lifecycle methods include:

  1. onCreate(): This method is called when an activity is first created. It’s where you typically set up the initial state of your activity, such as initializing variables and creating the user interface.
  2. onStart(): This method is called when the activity becomes visible to the user but is not yet in the foreground. It is a good place to start components that should be running while the activity is visible but not interacting with the user.
  3. onResume(): This method is called when the activity is about to move into the foreground and become interactive. You should perform tasks that require user interaction, such as starting animations and refreshing data, in this method.
  4. onPause(): This method is called when the activity loses focus but is still visible. It’s an appropriate place to stop animations or other ongoing processes that don’t need to run in the background.
  5. onStop(): This method is called when the activity is no longer visible to the user. It’s where you can release resources or components that are no longer needed.
  6. onDestroy(): This method is called when the activity is being destroyed. It’s your last chance to clean up resources, release memory, and perform any necessary cleanup.

Understanding the activity lifecycle allows you to manage your app’s resources efficiently and provide a seamless user experience.

How to Create and Define an Android Activity

To create an Android activity, you need to define it in the AndroidManifest.xml file. The AndroidManifest.xml file is a crucial configuration file that provides essential information about your app to the Android operating system.

Here’s an example of how you can define an activity in the AndroidManifest.xml file:

xml
<activity android:name=".MyActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

In the code above, we’re defining an activity named MyActivity. This activity will be the main entry point for the app, as indicated by the <intent-filter> section. The <action> and <category> elements specify that this activity is the main launcher activity.

How to Start an Activity

To start a new activity from an existing one, you can use an Intent. An Intent is an abstract description of an operation to be performed, and it can be used to start activities, services, and broadcast receivers. Here’s how you can start a new activity with an Intent:

java
Intent intent = new Intent(this, MyActivity.class);
startActivity(intent);

In this example, MyActivity is the activity you want to start. The Intent is created with the current context (this) and the target activity’s class.

You can also pass data between activities by including extras in the Intent. For example:

java
Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("key", "value");
startActivity(intent);

In MyActivity, you can retrieve this data using the getIntent() method and then extract the extras.

How to Receive Data from Other Activities

Sometimes, you may need to receive data from other activities, which is typically done when an activity is started for a result. For this purpose, you can use the startActivityForResult() method to launch another activity and receive data from it. Here’s how it works:

  1. Start the target activity using startActivityForResult().
  2. In the target activity, set the result data and call setResult() before finishing the activity.
  3. Back in the calling activity, override the onActivityResult() method to handle the result data.

Here’s an example:

In the calling activity:

java
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, REQUEST_CODE);

In the target activity (SecondActivity):

java
// Set the result data and finish the activity
Intent resultIntent = new Intent();
resultIntent.putExtra("result", "Data from SecondActivity");
setResult(RESULT_OK, resultIntent);
finish();

In the calling activity, override onActivityResult():

java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String resultData = data.getStringExtra("result");
// Handle the result data
}
}
}

This allows you to communicate between activities and exchange data seamlessly.

How to Manage Activity State

Managing the state of an Android activity is crucial for providing a smooth user experience. When an activity goes through its lifecycle, it can be destroyed and recreated by the system due to various reasons, such as screen rotations or low memory conditions. To ensure that your app retains its state, you can use techniques like:

  1. Save and Restore State: You can override the onSaveInstanceState() method to save important data when the activity is paused or stopped. Then, in the onCreate() method, you can check for saved data and restore the activity’s state.
  2. ViewModels: ViewModel is a part of Android Architecture Components that allows you to store and manage UI-related data across configuration changes. By using ViewModels, you can separate the UI-related data from the UI controller (activity or fragment) and ensure that it persists across configuration changes.
  3. Persist Data: To persist data, you can use various techniques such as SharedPreferences, databases, or files. SharedPreferences are a simple way to store key-value pairs of primitive data types, while databases offer more robust data storage options for complex data structures.

By implementing these strategies, you can provide a consistent and smooth user experience even when activities are recreated.

How to Navigate Between Activities

In Android, navigation between activities is a common requirement. You can move between activities using different techniques, including explicit and implicit intents.

Explicit Intent: As shown earlier, you can use explicit intents to start a specific activity within your application. This method is suitable for navigating within your app.

Implicit Intent: Implicit intents are used to request functionality from other apps on the device, such as opening a web page in a browser, sending an email, or sharing content. To use implicit intents, you specify the action you want to perform, and the Android system finds the appropriate app to handle the request.

Here’s an example of using an implicit intent to open a web page:

java
Uri webpage = Uri.parse("https://www.example.com");
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}

In this example, the ACTION_VIEW action is used to open a web page. The Android system will find an app capable of handling this action, such as a web browser.

How to Handle User Input and Events

User input and events are fundamental to the functionality of an Android app. Activities respond to user interactions by handling events like button clicks, text input, and more. Here’s how you can handle user input in Android activities:

  1. Button Clicks: To respond to button clicks, you can set an OnClickListener on the button view. When the button is clicked, the onClick() method of the listener is executed, allowing you to perform the desired action.
java
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Handle the button click
}
});
  1. Text Input: Handling text input is common in Android forms. You can use EditText widgets to capture user input. You can then retrieve the entered text and perform actions based on it.
java
EditText editText = findViewById(R.id.editText);
String userInput = editText.getText().toString();
// Process the user input
  1. Menu Items: Android apps often have menus for navigation or actions. You can define menus in XML and handle item selections in the onOptionsItemSelected() method of your activity.
java
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_id:
// Handle the menu item click
return true;
default:
return super.onOptionsItemSelected(item);
}
}

These are just a few examples of how to handle user input and events in Android activities. Depending on your app’s requirements, you can customize the event handling logic to suit your needs.

How to Use Fragments with Activities

Fragments are modular, reusable components that can be combined to create more flexible and responsive user interfaces. They can be used within activities to build complex and multi-pane layouts, providing a better user experience, especially on larger screens or tablets.

To use fragments with activities, follow these steps:

  1. Create a Fragment: Create a fragment class that defines the UI and behavior of the fragment. Fragments have their lifecycle and can be dynamically added or replaced within an activity.
  2. Add a Fragment to an Activity: To add a fragment to an activity, you need to use a FragmentTransaction. This transaction manages the interaction between the activity and the fragment.

Here’s a basic example of how to add a fragment to an activity:

java
MyFragment myFragment = new MyFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, myFragment);
transaction.addToBackStack(null);
transaction.commit();

In this example, MyFragment is added to the activity’s layout using a FragmentTransaction.

  1. Communicate Between Fragment and Activity: To facilitate communication between fragments and their parent activities, you can define interfaces in fragments and have the hosting activity implement those interfaces.

Fragments can be a powerful tool for creating flexible and responsive UIs in your Android applications, and they can work seamlessly with activities.

Related FAQ

1. What is the purpose of the AndroidManifest.xml file?

The AndroidManifest.xml file is a crucial configuration file in Android app development. It contains essential information about your app, including the app’s components (activities, services, broadcast receivers), permissions, and more. It also declares the main launcher activity and sets up various configurations for your app.

2. How can I pass data from one activity to another in Android?

You can pass data from one activity to another in Android using Intents. You create an intent and include data as extras. In the receiving activity, you retrieve the data from the intent and use it as needed.

3. What is the difference between an explicit intent and an implicit intent?

An explicit intent is used to start a specific component within your app, such as an activity or service. You specify the component’s class name in the intent.

An implicit intent is used to request functionality from other apps on the device. You specify the action you want to perform, and the Android system finds the appropriate app to handle the request.

4. How can I handle screen rotations without losing data in an Android activity?

You can handle screen rotations and prevent data loss by properly managing the activity’s state. This can be done by saving and restoring the activity’s state using methods like onSaveInstanceState() and onRestoreInstanceState(). Alternatively, you can use ViewModels to store UI-related data across configuration changes.

5. What is the Android activity lifecycle, and why is it important?

The Android activity lifecycle represents the various states an activity goes through, from creation to destruction. Understanding the activity lifecycle is essential for managing the behavior of your app, handling resource management, and providing a seamless user experience. By implementing the correct lifecycle methods, you can control the flow of your app and ensure it responds appropriately to user interactions and system events.

In conclusion, Android activities are fundamental components of Android app development, and understanding how to use them effectively is essential for creating successful applications. By grasping the Android activity lifecycle, defining activities in the AndroidManifest.xml file, and implementing various techniques to handle user input and navigation, you can build feature-rich and responsive Android apps that offer a great user experience. Additionally, incorporating fragments into your activities can enhance your app’s flexibility and usability, especially on different device form factors. Mastering these concepts and techniques will set you on the path to becoming a proficient Android app developer.

Scroll to Top