You are on page 1of 27

UNIVERSITATEA TEHNICĂ “GH.

ASACHI” DIN IAŞI


FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

Activities & Intents

2021
Activities and Intents
Contents
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

1. What is an Activity?

2. Declaring an activity
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

3. Activity lifecycle

4. Intents

5. Starting a new Activity by using Intents

6. Starting a new App by using Intents

7. Returning a result from an activity

8. Exercises
Activities and Intents
1. What is an Activity?
❖An activity represents a single screen with a user interface. For example, an email
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

application might have one activity that shows a list of new emails, another activity to

compose an email, and another activity for reading emails. If an application has more than
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

one activity, then one of them should be marked as the activity that is presented when the

application is launched.

❖An Activity is a class that extends the AppCompatActivity class and implements the logic of a

screen.

❖Each screen should have an Activity class defined, therefore an application with User

Interface must have at least one Activity defined, for the initial screen.

❖Activities facilities the transition from one Screen to another, but also to other application.

❖A Service, since it runs in background, does not require an Activity to run.


Activities and Intents
1. What is an Activity?
➢ The easiest way to create an Activity is from Android Studio menu File->New-
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

>Activity->Empty Activity.
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

By checking the
“Generate a Layout
File”, a layout xml file
is created and
associated with the
new Activity
Activities and Intents
2. Declaring an activity
An activity is declared in the AndroidManifest.xml file, which is the container of all the
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

components and services in an Android Application.


The activity is added in AndroidManifest.xml as a child of the <application> node.
The main activity for the app must be declared in the manifest with an <intent-filter>
that includes the MAIN action and LAUNCHER.
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

Example:

android::name specifies the name of the Activity class.


Activities and Intents
3. Activity lifecycle
Each Activity can pass through the following states during its lifecycle: Active, Paused,
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

Stopped, Destroyed, depending on the user action.

The transition between these states is marked by the call of one of the following

lifecycle events functions of the Activity class: onCreate(), onStart(), onResume(),


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

onPause(), onStop(), onRestart(), onDestroy() .

In order to handle the above lifecycle events, the corresponding function must be

overridden from the AppCompatActivity class in the derived Activity class.

When a new Activity is created, the first lifecycle event which is called is onCreate().

In the implementation of this event, the User Interface of the Activity shall be created,

by calling setContentView() function with the corresponding layout.


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

3. Activity lifecycle
Activities and Intents
Activities and Intents
3. Activity lifecycle
onCreate()
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

➢ This is the first callback and called when the activity is first created.
➢ Operations typically performed in onCreate() method:
• Inflate widgets and place them on screen (e.g. using layout files with setContentView( ) ).
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

• Getting references to inflated widgets ( using findViewbyId( ) ).


• Setting widget listeners to handle user interaction.

public class MainActivity extends AppCompatActivity {


private Button mSubmitButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mSubmitButton = (Button) findViewById(R.id.submit_button);


}
Activities and Intents
3. Activity lifecycle
onStart()
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

➢ This callback is called when the activity becomes visible to the user. The User
Interface is not yet visible at this point, which allows other preparations to be done.
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

➢ Load persistent application state.

onResume()

➢ is the next event called after onStart(). At this point, the Activity is almost ready to
receive user input.
➢ Called when the activity is visible and is about to start interacting with the user
➢ Start foreground-only activities (e.g. get user location and show it on the map)
Activities and Intents
3. Activity lifecycle
onPause()
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

➢ is the only possible event after on Resume. It is called when the Activity looses focus, for
example when another activity is started, or when Home/Recent buttons are pressed.
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

➢ Use it to commit unsaved changes to persistent data, stop animations, CPU-intensive


processing
➢ Processing in this method should be done quickly, because the next activity will not start
until this method returns
– Alternatively, run a parallel thread from onPause()
Activities and Intents
3. Activity lifecycle
onStop()
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

➢ onResume() and onStop() are the possible two events after OnPause(). If the
Activity returns to focus, then onResume() will be called. If the Activity looses focus
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

completely, then onStop() will be called.


➢ Release resources that are not needed while the activity is not visible.
➢ Perform CPU-heavy shutdown operations.
Activities and Intents
3. Activity lifecycle
onRestart()
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

➢ onRestart() and onDestroy() are the two possible events after onStop(). If the
app will regain the focus, then OnRestart() will be called, followed by OnStart(). If the
Activity is destroyed, for example when the app is closed, then onDestroy() is called.
➢ Called if the activity is becoming visible, after being stopped.
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

➢ Perform special processing needed only after having been stopped.


➢ Will be followed by onStart() and onResume().

onDestroy()
➢ Called when the Activity is about to get destroyed.
– Happens when finish() is called
– Happens when the OS calls it
➢ Use it to release resources such as Threads that are associated with the Activity.
• Note: may not be called if Android kills your application.
Activities and Intents
4. Intents
What is an intent?
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

➢ Intents represents a way to start a new Activity, or another app, and to pass data to it.
➢ An Intent is an object used to request an action from another app component via the
Android system.
➢ Intents serve as a glue between activities
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

– Constructed by a component that wants some work to be done


– Received by an Activity that can perform that work
What can intents do?
➢ Start activities
- A button click starts a new activity for text entry
- Clicking Share opens an app that allows you to post a photo
➢ Start services
- Initiate downloading a file in the background
➢ Deliver broadcasts
- The system informs everybody that the phone is now charging.
Activities and Intents
4. Intents
Explicit and Implicit intents
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

➢ An intent can be defined as being Implicit or Explicit.


➢ An intent is Explicit if it specifies exactly what Activity to be started or with what app
the action shall be performed.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

startActivity(i);

In this example, there are two activities


(FirstActivity, SecondActivity). When you click
on the ‘GO TO OTHER ACTIVITY’ Button in
the FirstActivity, then you move to the
SecondActivity. When you click on the ‘GO
TO HOME ACTIVITY’ button in the
SecondActivity, then you move to the first
activity. This is getting done through Explicit
Intent.
Activities and Intents
4. Intents
Explicit and Implicit intents
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

➢ An intent is Implicit if the user is let to choose the application that will complete the
action.
For example, you may write the following code to view the webpage.
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

Intent intent=new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse(“http://www.javatpoint.com”));
startActivity(intent);

In these images, no component


is specified, instead, an action is
performed i.e. a webpage is
going to be opened. As you type
the name of your desired
webpage and click on the ‘CLICK’
button. Your webpage is opened.
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

4. Intents
Activities and Intents
Activities and Intents
4. Intents
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

Explicit intent Implicit intent

explicit intents are those in which the user Implicit intents do not name a specific
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

has a clear vision and knows exactly which component like explicit intent, instead
activity can handle the requests. declare general action to perform, which
allows a component from another app to
handle.
Explicit intent can do the specific application It specifies the only action to be performed
action which is set by the code like and does not directly specify Android
changing activity, downloading the file in Components.
the background, etc.
Explicit intents are used for communication They are used for communication across
inside the application. Like changing two different applications.
activities inside the application.
Activities and Intents
5. Starting a new Activity by using Intents
An activity can be started with an Intent. This is a case of an explicit Intent. Example:
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

1. Create an intent
Intent intent = new Intent(this, SecondActivity.class);
2. Use the intent to start the activity
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

startActivity(intent);

Data can be passed through Intents to the new Activity, by calling the putExtra
function of an Intent. The first argument is the key name of the passed data, while the
second is the passed data, which can be of different types(String, int, float, etc).
Example:
intent.putExtra(Intent.EXTRA_TEXT, " Text from the main activity");
or
intent.putExtra("My Key", 10.3);
Activities and Intents
5. Starting a new Activity by using Intents
➢ Example of starting a new Activity in the handle function of click on a
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

Button:

public void onButtonClick(View view)


UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

{
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "Text from the main activity");
startActivity(intent);
}
Activities and Intents
5. Starting a new Activity by using Intents
➢ In the started Activity, the Intent can be retrieved with function getIntent() and
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

then the passed data can be retrieved with function getXYZExtra(), where XYZ is the
type of the passed data.
Example of retrieving the passed data when the second Activity is started and to
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

display it in a TextView:
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
Intent i = getIntent();
TextView txtView = findViewById(R.id.textView);
txtView.setText(i.getStringExtra(Intent.EXTRA_TEXT));
}
}
Activities and Intents
6. Starting a new App by using Intents
An App can be started with an Intent from an Activity. This is a case of an implicit intent. An Activity
can start apps and send data to them, by specifying an Action type when creating the Intent. Android
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

will then display the list of Apps that can handle that Action.
❖Examples:
- a web browser is started if the Action type is ACTION_VIEW, the URL starts http://
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

and the set data is a Uri:


Intent intent = new Intent(Intent.ACTION_VIEW);
String url = "www.google.com";
if (!url.startsWith("https://") && !url.startsWith("http://")) {
url = "http://" + url;
}
intent.setData(Uri.parse(url));
startActivity(intent);

❖ Text data is sent to other apps if the Action type is ACTION_SEND action, the type
is “text/plain” and there is a text set with putExtra.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "My message");
intent.setType("text/plain");
Activities and Intents
7. Returning a result from an activity
Often it's needed to receive some data from the called activity when the activity ends.
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

The received data ( the result) is encapsulated in an Intent object.


An activity for which a result is expected shall be started with startActivityForResult()
method, instead of startActivity().
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

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


startActivityForResult(intent,3);//3 is a code chosen for the created Activity. It is used to
identify from which Activity the result was received.
Activities and Intents
7. Returning a result from an activity
The Activity sets the result by passing a result code and an Intent to the setResult()
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

method:
Intent returnIntent = new Intent();
returnIntent.putExtra("REQUEST_RESULT", "This is a text from the closed Activity");
setResult(RESULT_OK, returnIntent);
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

❖ In order to process the result, the method onActivityResult() shall be overridden:


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==3)//the result is received for the expected Activity {
if(resultCode == RESULT_OK) {
System.out.println(data.getStringExtra("REQUEST_RESULT"));
}
}
}
Activities and Intents
8. Exercises
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

1) Understanding Activity Lifecycle:


- Create a new project in Android Studio with an Empty Activity
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

- In the autogenerated TextView, display the list of the Activity lifecycle events
that are called. Print that information also in Console.
- Run the application and observe what events are called when the application
is started, when the Back and Home keys are pressed, when the application is
closed.
Activities and Intents
8. Exercises
2) How to start a new Activity by using Intents
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

- Create a new project in Android Studio with an Empty Activity.


- Delete the autogenerated TextView
- Add a PlainText and a Button. Change the id of the PlainText to
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

inputTextMessage, for example, and remove its default text content. Change the text of
the button to “Send”. Please notice that the Properties of the layout elements can be
changed from both Design view and XML view.
- Add in MainActivity a stub method for the onClick method of the button. Example:
public void onClickSend(View view) {}
- Assign onClickSend to the onClick event of the Send button.
- Add a second EmptyActivity. Change the id of the autogenerated TextView to
textMessage, for example, and remove its default text content.
- Add implementation so that when Send button is clicked, the content of the
entered input in FirstActivity is displayed in the TextView of the SecondActivity.
Activities and Intents
8. Exercises
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

3) How to start a new App from an Activity by using Intents


- Based on the project created in the previous exercise, add another button in
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

MainActivity, which, when it is clicked, will give the possibility to open the
entered text in inputTextMessage in a web browser as URL.
- Add another button in MainActivity, which, when it is clicked, will send the
entered text in inputTextMessage to another application.
Activities and Intents
8. Exercises
FACULTATEA DE ELECTRONICĂ, TELECOMUNICAŢII ŞI TEHNOLOGIA INFORMAŢIEI

4) Returning a result from an activity


- Based on the project created in the previous exercise, print in a TextView in
UNIVERSITATEA TEHNICĂ “GH. ASACHI” DIN IAŞI

the MainActivity a string returned as result from the SecondActivity.

You might also like