SlideShare a Scribd company logo
1 of 119
PEMROGRAMAN
ANDROID
Activities and intents
Riad Sahara, S.SI., M.T.
Universitas Siber Asia Program Studi:
PJJ Informatika S1
Modul
Ke: 03
2.1 Activities and Intents
2
Contents
â—ŹActivities
â—ŹDefining an Activity
â—ŹStarting a new Activity with an Intent
â—ŹPassing data between activities with extras
â—ŹNavigating between activities
3
Activities
(high-level view)
4
What is an Activity?
â—ŹAn Activity is an application component
â—ŹRepresents one window, one hierarchy of views
â—ŹTypically fills the screen, but can be embedded in other Activity or a
appear as floating window
â—ŹJava class, typically one Activity in one file
5
What does an Activity do?
â—ŹRepresents an activity, such as ordering groceries, sending email, or
getting directions
â—ŹHandles user interactions, such as button clicks, text entry, or login
verification
â—ŹCan start other activities in the same or other apps
●Has a life cycle—is created, started, runs, is paused, resumed,
stopped, and destroyed
6
Examples of activities
7
Apps and activities
â—ŹActivities are loosely tied together to make up an app
â—ŹFirst Activity user sees is typically called "main activity"
â—ŹActivities can be organized in parent-child relationships in the
Android manifest to aid navigation
8
Layouts and Activities
â—ŹAn Activity typically has a UI layout
â—ŹLayout is usually defined in one or more XML files
â—ŹActivity "inflates" layout as part of being created
9
Implementing Activities
10
Implement new activities
• Define layout in XML
• Define Activity Java class
â—‹extends AppCompatActivity
• Connect Activity with Layout
â—‹Set content view in onCreate()
• Declare Activity in the Android manifest
11
1. Define layout in XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Let's Shop for Food!" />
</RelativeLayout>
12
2. Define Activity Java class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
13
3. Connect activity with layout
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
14
in this XML file
is layout
Resource
4. Declare activity in Android manifest
<activity android:name=".MainActivity">
15
4. Declare main activity in manifest
MainActivity needs to include intent-filter to start from
launcher
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
16
Intents
17
What is an intent?
An Intent is a description of an operation to be performed.
An Intent is an object used to request an action from another app
component via the Android system.
18
App component
Originator
Intent Action
Android
System
What can intents do?
â—ŹStart an Activity
â—‹A button click starts a new Activity for text entry
â—‹Clicking Share opens an app that allows you to post a photo
â—ŹStart an Service
â—‹Initiate downloading a file in the background
â—ŹDeliver Broadcast
â—‹The system informs everybody that the phone is now charging
19
Explicit and implicit intents
Explicit Intent
â—Ź Starts a specific Activity
â—‹ Request tea with milk delivered by Nikita
â—‹ Main activity starts the ViewShoppingCart Activity
Implicit Intent
â—Ź Asks system to find an Activity that can handle this
request
â—‹ Find an open store that sells green tea
â—‹ Clicking Share opens a chooser with a list of apps
20
Starting Activities
21
Start an Activity with an explicit intent
To start a specific Activity, use an explicit Intent
• Create an Intent
â—‹Intent intent = new Intent(this, ActivityName.class);
• Use the Intent to start the Activity
â—‹ startActivity(intent);
22
Start an Activity with implicit intent
To ask Android to find an Activity to handle your request, use an
implicit Intent
• Create an Intent
â—‹Intent intent = new Intent(action, uri);
• Use the Intent to start the Activity
â—‹ startActivity(intent);
23
Implicit Intents - Examples
24
Show a web page
Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = Uri.parse("tel:8005551234");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
How Activities Run
â—Ź All Activity instances are managed by the Android runtime
â—Ź Started by an "Intent", a message to the Android runtime to
run an activity
25
MainActivity
What do you want to do?
FoodListActivity
Choose food items...Next
OrderActivity
Place order
User clicks
launcher icon
Android
System
Intent: Start
app
Start
main
activity
Android
System
Start choose
food activity Android
System
Start finish
order activity
Intent:
Shop
Intent:
order
Sending and Receiving Data
26
Two types of sending data with intents
●Data—one piece of information whose data location can be
represented by an URI
●Extras—one or more pieces of information as a collection of
key-value pairs in a Bundle
27
Sending and retrieving data
In the first (sending) Activity:
• Create the Intent object
• Put data or extras into that Intent
• Start the new Activity with startActivity()
In the second (receiving) Activity:
• Get the Intent object, the Activity was started with
• Retrieve the data or extras from the Intent object
28
Putting a URI as intent data
// A web page URL
intent.setData(
Uri.parse("http://www.google.com"));
// a Sample file URI
intent.setData(
Uri.fromFile(new File("/sdcard/sample.jpg")));
29
Put information into intent extras
â—Ź putExtra(String name, int value)
⇒ intent.putExtra("level", 406);
â—Ź putExtra(String name, String[] value)
⇒ String[] foodList = {"Rice", "Beans",
"Fruit"};
intent.putExtra("food", foodList);
â—Ź putExtras(bundle);
⇒ if lots of data, first create a bundle and pass the bundle.
â—Ź See documentation for all
30
Sending data to an activity with extras
public static final String EXTRA_MESSAGE_KEY =
"com.example.android.twoactivities.extra.MESSAGE";
Intent intent = new Intent(this,
SecondActivity.class);
String message = "Hello Activity!";
intent.putExtra(EXTRA_MESSAGE_KEY, message);
startActivity(intent);
31
Get data from intents
â—Ź getData();
⇒ Uri locationUri = intent.getData();
â—Ź int getIntExtra (String name, int defaultValue)
⇒ int level = intent.getIntExtra("level", 0);
â—Ź Bundle bundle = intent.getExtras();
⇒ Get all the data at once as a bundle.
â—Ź See documentation for all
32
Returning data to the starting activity
• Use startActivityForResult() to start the second Activity
• To return data from the second Activity:
â—Ź Create a new Intent
â—Ź Put the response data in the Intent using putExtra()
â—Ź Set the result to Activity.RESULT_OK
or RESULT_CANCELED, if the user cancelled out
â—Ź call finish() to close the Activity
• Implement onActivityResult() in first Activity
33
startActivityForResult()
startActivityForResult(intent, requestCode);
â—Ź Starts Activity (intent), assigns it identifier
(requestCode)
â—Ź Returns data via Intent extras
â—Ź When done, pop stack, return to previous Activity, and
execute onActivityResult() callback to process returned
data
â—Ź Use requestCode to identify which Activity has
"returned"
34
1. startActivityForResult() Example
public static final int CHOOSE_FOOD_REQUEST = 1;
Intent intent = new Intent(this,
ChooseFoodItemsActivity.class);
startActivityForResult(intent, CHOOSE_FOOD_REQUEST);
35
2. Return data and finish second activity
// Create an intent
Intent replyIntent = new Intent();
// Put the data to return into the extra
replyIntent.putExtra(EXTRA_REPLY, reply);
// Set the activity's result to RESULT_OK
setResult(RESULT_OK, replyIntent);
// Finish the current activity
finish();
36
3. Implement onActivityResult()
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TEXT_REQUEST) { // Identify activity
if (resultCode == RESULT_OK) { // Activity succeeded
String reply =
data.getStringExtra(SecondActivity.EXTRA_REPLY);
// … do something with the data
}}}
37
Navigation
38
Activity stack
â—ŹWhen a new Activity is started, the previous Activity is stopped
and pushed on the Activity back stack
●Last-in-first-out-stack—when the current Activity ends, or the
user presses the Back button, it is popped from the stack and the
previous Activity resumes
39
Activity Stack
40
MainActivity
What do you want to do?
FoodListActivity
Choose food items
CartActivity
View shopping cart
MainActivity
What do you want to do?
FoodListActivity
Choose food items
MainActivity
What do you want to do?
FoodListActivity
Choose food items
CartActivity
View shopping cart
OrderActivity
Place order
MainActivity
What do you want to do?
After viewing
shopping cart, user
decides to add more
items, then places
order.
Two forms of navigation
Temporal or back navigation
â—Źprovided by the device's Back button
â—Źcontrolled by the Android system's back stack
Ancestral or up navigation
â—Źprovided by the Up button in app's action bar
â—Źcontrolled by defining parent-child relationships between activities in
the Android manifest
41
Back navigation
â—Ź Back stack preserves history of recently viewed screens
â—Ź Back stack contains all the Activity instances that have been
launched by the user in reverse order for the current task
â—Ź Each task has its own back stack
â—Ź Switching between tasks activates that task's back stack
42
Up navigation
43
â—ŹGoes to parent of current Activity
â—ŹDefine an Activity parent in Android manifest
â—ŹSet parentActivityName
<activity
android:name=".ShowDinnerActivity"
android:parentActivityName=".MainActivity" >
</activity>
Learn more
44
Learn more
â—ŹAndroid Application Fundamentals
â—ŹStarting Another Activity
â—ŹActivity (API Guide)
â—ŹActivity (API Reference)
â—ŹIntents and Intent Filters (API Guide)
â—ŹIntent (API Reference)
â—ŹNavigation
45
What's Next?
46
â—Ź Concept Chapter: 2.1 Activities and Intents
â—Ź Practical: 2.1 Activities and intents
2.2 Activity lifecycle and state
47
Contents
â—ŹActivity lifecycle
â—ŹActivity lifecycle callbacks
â—ŹActivity instance state
â—ŹSaving and restoring Activity state
48
Activity lifecycle
49
What is the Activity Lifecycle?
50
â—Ź The set of states an Activity can be in during its lifetime,
from when it is created until it is destroyed
More formally:
â—Ź A directed graph of all the states an Activity can be in,
and the callbacks associated with transitioning from
each state to the next one
What is the Activity Lifecycle?
51
Activity states and app visibility
52
â—Ź Created (not visible yet)
â—Ź Started (visible)
â—Ź Resume (visible)
â—Ź Paused(partially invisible)
â—Ź Stopped (hidden)
â—Ź Destroyed (gone from memory)
State changes are triggered by user action, configuration
changes such as device rotation, or system action
Activity lifecycle callbacks
53
Callbacks and when they are called
54
onCreate(Bundle savedInstanceState)—static initialization
onStart()—when Activity (screen) is becoming visible
onRestart()—called if Activity was stopped (calls onStart())
onResume()—start to interact with user
onPause()—about to resume PREVIOUS Activity
onStop()—no longer visible, but still exists and all state info preserved
onDestroy()—final call before Android system destroys Activity
Activity states and callbacks graph
55
Implementing and overriding callbacks
â—ŹOnly onCreate() is required
â—ŹOverride the other callbacks to change default behavior
56
onCreate() –> Created
â—ŹCalled when the Activity is first created, for example when user
taps launcher icon
â—ŹDoes all static setup: create views, bind data to lists, ...
â—ŹOnly called once during an activity's lifetime
â—ŹTakes a Bundle with Activity's previously frozen state, if there was
one
â—ŹCreated state is always followed by onStart()
57
onCreate(Bundle savedInstanceState)
58
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
}
onStart() –> Started
59
â—Ź Called when the Activity is becoming visible to user
â—Ź Can be called more than once during lifecycle
â—Ź Followed by onResume() if the activity comes to the
foreground, or onStop() if it becomes hidden
onStart()
60
@Override
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
onRestart() –> Started
61
â—Ź Called after Activity has been stopped, immediately before
it is started again
â—Ź Transient state
â—Ź Always followed by onStart()
onRestart()
62
@Override
protected void onRestart() {
super.onRestart();
// The activity is between stopped and started.
}
onResume() –> Resumed/Running
63
â—Ź Called when Activity will start interacting with user
â—Ź Activity has moved to top of the Activity stack
â—Ź Starts accepting user input
â—Ź Running state
â—Ź Always followed by onPause()
onResume()
64
@Override
protected void onResume() {
super.onResume();
// The activity has become visible
// it is now "resumed"
}
onPause() –> Paused
65
â—Ź Called when system is about to resume a previous Activity
â—Ź The Activity is partly visible but user is leaving the Activity
â—Ź Typically used to commit unsaved changes to persistent data, stop
animations and anything that consumes resources
â—Ź Implementations must be fast because the next Activity is not
resumed until this method returns
â—Ź Followed by either onResume() if the Activity returns back to the front,
or onStop() if it becomes invisible to the user
onPause()
66
@Override
protected void onPause() {
super.onPause();
// Another activity is taking focus
// this activity is about to be "paused"
}
onStop() –> Stopped
67
â—Ź Called when the Activity is no longer visible to the user
â—Ź New Activity is being started, an existing one is brought
in front of this one, or this one is being destroyed
â—Ź Operations that were too heavy-weight for onPause()
â—Ź Followed by either onRestart() if Activity is coming back
to interact with user, or onDestroy() if Activity is going
away
onStop()
68
@Override
protected void onStop() {
super.onStop();
// The activity is no longer visible
// it is now "stopped"
}
onDestroy() –> Destroyed
69
â—Ź Final call before Activity is destroyed
â—Ź User navigates back to previous Activity, or configuration
changes
â—Ź Activity is finishing or system is destroying it to save space
â—Ź Call isFinishing() method to check
â—Ź System may destroy Activity without calling this, so use
onPause() or onStop() to save data or state
onDestroy()
70
@Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}
Activity instance state
71
When does config change?
Configuration changes invalidate the current layout or other resources
in your activity when the user:
â—ŹRotates the device
â—ŹChooses different system language, so locale changes
â—ŹEnters multi-window mode (from Android 7)
72
What happens on config change?
On configuration change, Android:
1. Shuts down Activity
by calling:
73
2. Starts Activity over again
by calling:
â—Ź onPause()
â—Ź onStop()
â—Ź onDestroy()
â—Ź onCreate()
â—Ź onStart()
â—Ź onResume()
Activity instance state
74
â—Ź State information is created while the Activity is running,
such as a counter, user text, animation progression
â—Ź State is lost when device is rotated, language changes,
back-button is pressed, or the system clears memory
Saving and restoring Activity state
75
What the system saves
76
â—Ź System saves only:
â—‹ State of views with unique ID (android:id) such as
text entered into EditText
â—‹ Intent that started activity and data in its extras
â—Ź You are responsible for saving other activity and user
progress data
Saving instance state
77
Implement onSaveInstanceState() in your Activity
â—Ź Called by Android runtime when there is a possibility the
Activity may be destroyed
â—Ź Saves data only for this instance of the Activity during
current session
onSaveInstanceState(Bundle outState)
78
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Add information for saving HelloToast counter
// to the to the outState bundle
outState.putString("count",
String.valueOf(mShowCount.getText()));
}
Restoring instance state
Two ways to retrieve the saved Bundle
â—Źin onCreate(Bundle mySavedState)
Preferred, to ensure that your user interface, including any saved
state, is back up and running as quickly as possible
â—ŹImplement callback (called after onStart())
onRestoreInstanceState(Bundle mySavedState)
79
Restoring in onCreate()
80
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShowCount = findViewById(R.id.show_count);
if (savedInstanceState != null) {
String count = savedInstanceState.getString("count");
if (mShowCount != null)
mShowCount.setText(count);
}
}
onRestoreInstanceState(Bundle state)
81
@Override
public void onRestoreInstanceState (Bundle mySavedState) {
super.onRestoreInstanceState(mySavedState);
if (mySavedState != null) {
String count = mySavedState.getString("count");
if (count != null)
mShowCount.setText(count);
}
}
Instance state and app restart
82
When you stop and restart a new app session, the Activity instance
states are lost and your activities will revert to their default
appearance
If you need to save user data between app sessions, use shared
preferences or a database.
Learn more
â—ŹActivities (API Guide)
â—ŹActivity (API Reference)
â—ŹManaging the Activity Lifecycle
â—ŹPausing and Resuming an Activity
â—ŹStopping and Restarting an Activity
â—ŹRecreating an Activity
â—ŹHandling Runtime Changes
â—ŹBundle
83
What's Next?
84
â—Ź Concept Chapter: 2.2 Activity lifecycle and state
â—Ź Practical: 2.2 Activity lifecycle and state
2.3 Implicit Intents
85
Contents
●Intent—recap
â—ŹImplicit Intent overview
â—ŹSending an implicit Intent
â—ŹReceiving an implicit Intent
86
Recap: Intent
87
What is an Intent?
An Intent is:
â—ŹDescription of an operation to be performed
â—ŹMessaging object used to request an action from another app
component via the Android system.
88
App component
Originator
Intent Action
Android
System
What can an Intent do?
An Intent can be used to:
â—Źstart an Activity
â—Źstart a Service
â—Źdeliver a Broadcast
Services and Broadcasts are covered in other lessons
89
Explicit vs. implicit Intent
Explicit Intent — Starts an Activity of a specific class
Implicit Intent — Asks system to find an Activity class with a registered
handler that can handle this request
90
Implicit Intent overview
91
What you do with an implicit Intent
â—ŹStart an Activity in another app by describing an action you intend to
perform, such as "share an article", "view a map", or "take a picture"
â—ŹSpecify an action and optionally provide data with which to perform
the action
â—ŹDon't specify the target Activity class, just the intended action
92
What system does with implicit Intent
â—ŹAndroid runtime matches the implicit intent request with registered
intent handlers
â—ŹIf there are multiple matches, an App Chooser will open to let the
user decide
93
How does implicit Intent work?
• The Android Runtime keeps a list of registered Apps
• Apps have to register via AndroidManifest.xml
• Runtime receives the request and looks for matches
• Android runtime uses Intent filters for matching
• If more than one match, shows a list of possible matches and lets the
user choose one
• Android runtime starts the requested activity
94
App Chooser
95
When the Android runtime finds
multiple registered activities that can
handle an implicit Intent, it displays an
App Chooser to allow the user to
select the handler
Sending an implicit Intent
96
Sending an implicit Intent
97
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);
User has pressed Call button — start Activity that can
make a call (no data is passed in or returned)
1. Start the Activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
Avoid exceptions and crashes
98
Before starting an implicit Activity, use the package manager
to check that there is a package with an Activity that matches
the given criteria.
Intent myIntent = new Intent(Intent.ACTION_CALL_BUTTON);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
Sending an implicit Intent with data URI
99
1. Create an Intent for action
Intent intent = new Intent(Intent.ACTION_DIAL);
1. Provide data as a URI
intent.setData(Uri.parse("tel:8005551234"));
1. Start the Activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
Providing the data as URI
100
Create an URI from a string using Uri.parse(String uri)
â—Ź Uri.parse("tel:8005551234")
â—Ź Uri.parse("geo:0,0?q=brooklyn%20bridge%2C%20brooklyn%2C%20ny")
â—Ź Uri.parse("http://www.android.com");
Uri documentation
Implicit Intent examples
101
Show a web page
Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
Dial a phone number
Uri uri = Uri.parse("tel:8005551234");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
Sending an implicit Intent with extras
102
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
1. Put extras
String query = edittext.getText().toString();
intent.putExtra(SearchManager.QUERY, query));
1. Start the Activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
Category
103
Additional information about the kind of component to
handle the intent.
â—Ź CATEGORY_OPENABLE
Only allow URIs of files that are openable
â—Ź CATEGORY_BROWSABLE
Only an Activity that can start a web browser to display
data referenced by the URI
Sending an implicit Intent with type and category
104
1. Create an Intent for an action
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
1. Set mime type and category for additional information
intent.setType("application/pdf"); // set MIME type
intent.addCategory(Intent.CATEGORY_OPENABLE);
continued on next slide...
Sending an implicit Intent with type and category
105
3. Start the Activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(myIntent,ACTIVITY_REQUEST_CREATE_FILE);
}
4. Process returned content URI in onActivityResult()
Common actions for an implicit Intent
Common actions include:
â—ŹACTION_SET_ALARM
â—ŹACTION_IMAGE_CAPTURE
â—ŹACTION_CREATE_DOCUMENT
â—ŹACTION_SENDTO
â—Źand many more
106
Apps that handle common actions
107
Common actions are usually handled by installed apps (both
system apps and other apps), such as:
â—Ź Alarm Clock, Calendar, Camera, Contacts
â—Ź Email, File Storage, Maps, Music/Video
â—Ź Notes, Phone, Search, Settings
â—Ź Text Messaging and Web Browsing
âž” List of common
actions for an
implicit intent
âž” List of all
available actions
Receiving an Implicit Intent
108
Register your app to receive an Intent
â—ŹDeclare one or more Intent filters for the Activity in
AndroidManifest.xml
â—ŹFilter announces ability of Activity to accept an implicit Intent
â—ŹFilter puts conditions on the Intent that the Activity accepts
109
Intent filter in AndroidManifest.xml
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category
android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
110
Intent filters: action and category
111
● action — Match one or more action constants
○ android.intent.action.VIEW — matches any Intent with ACTION_VIEW
○ android.intent.action.SEND — matches any Intent with ACTION_SEND
● category — additional information (list of categories)
○ android.intent.category.BROWSABLE—can be started by web browser
○ android.intent.category.LAUNCHER—Show activity as launcher icon
Intent filters: data
112
● data — Filter on data URIs, MIME type
○ android:scheme="https"—require URIs to be https protocol
○ android:host="developer.android.com"—only accept an Intent from
specified hosts
○ android:mimeType="text/plain"—limit the acceptable types of documents
An Activity can have multiple filters
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
...
</intent-filter>
<intent-filter>
<action
android:name="android.intent.action.SEND_MULTIPLE"/>
...
</intent-filter>
</activity> 113
An Activity can have several filters
A filter can have multiple actions & data
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<action
android:name="android.intent.action.SEND_MULTIPLE"/>
<category
android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
<data android:mimeType="video/*"/>
</intent-filter> 114
Learn more
115
Learn more
â—ŹIntent class documentation
â—ŹUri documentation
â—ŹList of common apps that respond to implicit intents
â—ŹList of available actions
â—ŹList of categories
â—ŹIntent Filters
116
What's Next?
117
â—Ź Concept Chapter: 2.3 Implicit Intents
â—Ź Practical: 2.3 Implicit Intents
Referensi
1. Google, D. (2021, 09 24). Dasar-Dasar Developer Android. Retrieved from Google Developers:
https://developers.google.com/training/courses/android-fundamentals?hl=id
TERIMA KASIH

More Related Content

Similar to PEMROGRAMAN ANDROID Activities and intents

Intents are Awesome
Intents are AwesomeIntents are Awesome
Intents are AwesomeIsrael Camacho
 
Android Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intentsAndroid Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intentsDenis Minja
 
Android development - Activities, Views & Intents
Android development - Activities, Views & IntentsAndroid development - Activities, Views & Intents
Android development - Activities, Views & IntentsLope Emano
 
08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)Oum Saokosal
 
Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAnuchit Chalothorn
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptxMugiiiReee
 
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)TECOS
 
Android intents in android application-chapter7
Android intents in android application-chapter7Android intents in android application-chapter7
Android intents in android application-chapter7Dr. Ramkumar Lakshminarayanan
 
android_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last semandroid_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last semaswinbiju1652
 
Day 4: Android: Getting Active through Activities
Day 4: Android: Getting Active through ActivitiesDay 4: Android: Getting Active through Activities
Day 4: Android: Getting Active through ActivitiesAhsanul Karim
 
Android activity intents
Android activity intentsAndroid activity intents
Android activity intentsperpetrotech
 
Android activity intentsq
Android activity intentsqAndroid activity intentsq
Android activity intentsqperpetrotech
 
Android webinar class_3
Android webinar class_3Android webinar class_3
Android webinar class_3Edureka!
 
Android development session 2 - intent and activity
Android development   session 2 - intent and activityAndroid development   session 2 - intent and activity
Android development session 2 - intent and activityFarabi Technology Middle East
 
Android Application managing activites.pptx
Android Application managing activites.pptxAndroid Application managing activites.pptx
Android Application managing activites.pptxPoornima E.G.
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intentPERKYTORIALS
 

Similar to PEMROGRAMAN ANDROID Activities and intents (20)

Intents are Awesome
Intents are AwesomeIntents are Awesome
Intents are Awesome
 
Android Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intentsAndroid Bootcamp Tanzania:intents
Android Bootcamp Tanzania:intents
 
Android development - Activities, Views & Intents
Android development - Activities, Views & IntentsAndroid development - Activities, Views & Intents
Android development - Activities, Views & Intents
 
08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)08.1. Android How to Use Intent (explicit)
08.1. Android How to Use Intent (explicit)
 
Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; Share
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
 
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)
 
Android intents in android application-chapter7
Android intents in android application-chapter7Android intents in android application-chapter7
Android intents in android application-chapter7
 
Android - Android Intent Types
Android - Android Intent TypesAndroid - Android Intent Types
Android - Android Intent Types
 
android_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last semandroid_mod_3.useful for bca students for their last sem
android_mod_3.useful for bca students for their last sem
 
Day 4: Android: Getting Active through Activities
Day 4: Android: Getting Active through ActivitiesDay 4: Android: Getting Active through Activities
Day 4: Android: Getting Active through Activities
 
Android activity intents
Android activity intentsAndroid activity intents
Android activity intents
 
Android activity intentsq
Android activity intentsqAndroid activity intentsq
Android activity intentsq
 
Android webinar class_3
Android webinar class_3Android webinar class_3
Android webinar class_3
 
Introduction toandroid
Introduction toandroidIntroduction toandroid
Introduction toandroid
 
Android development session 2 - intent and activity
Android development   session 2 - intent and activityAndroid development   session 2 - intent and activity
Android development session 2 - intent and activity
 
Android Application managing activites.pptx
Android Application managing activites.pptxAndroid Application managing activites.pptx
Android Application managing activites.pptx
 
unit3.pptx
unit3.pptxunit3.pptx
unit3.pptx
 
DAY2.pptx
DAY2.pptxDAY2.pptx
DAY2.pptx
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 đź’ž Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 đź’ž Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 đź’ž Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 đź’ž Full Nigh...Pooja Nehwal
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Recently uploaded (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 đź’ž Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 đź’ž Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 đź’ž Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 đź’ž Full Nigh...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

PEMROGRAMAN ANDROID Activities and intents

  • 1. PEMROGRAMAN ANDROID Activities and intents Riad Sahara, S.SI., M.T. Universitas Siber Asia Program Studi: PJJ Informatika S1 Modul Ke: 03
  • 2. 2.1 Activities and Intents 2
  • 3. Contents â—ŹActivities â—ŹDefining an Activity â—ŹStarting a new Activity with an Intent â—ŹPassing data between activities with extras â—ŹNavigating between activities 3
  • 5. What is an Activity? â—ŹAn Activity is an application component â—ŹRepresents one window, one hierarchy of views â—ŹTypically fills the screen, but can be embedded in other Activity or a appear as floating window â—ŹJava class, typically one Activity in one file 5
  • 6. What does an Activity do? â—ŹRepresents an activity, such as ordering groceries, sending email, or getting directions â—ŹHandles user interactions, such as button clicks, text entry, or login verification â—ŹCan start other activities in the same or other apps â—ŹHas a life cycle—is created, started, runs, is paused, resumed, stopped, and destroyed 6
  • 8. Apps and activities â—ŹActivities are loosely tied together to make up an app â—ŹFirst Activity user sees is typically called "main activity" â—ŹActivities can be organized in parent-child relationships in the Android manifest to aid navigation 8
  • 9. Layouts and Activities â—ŹAn Activity typically has a UI layout â—ŹLayout is usually defined in one or more XML files â—ŹActivity "inflates" layout as part of being created 9
  • 11. Implement new activities • Define layout in XML • Define Activity Java class â—‹extends AppCompatActivity • Connect Activity with Layout â—‹Set content view in onCreate() • Declare Activity in the Android manifest 11
  • 12. 1. Define layout in XML <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Let's Shop for Food!" /> </RelativeLayout> 12
  • 13. 2. Define Activity Java class public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } } 13
  • 14. 3. Connect activity with layout public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } 14 in this XML file is layout Resource
  • 15. 4. Declare activity in Android manifest <activity android:name=".MainActivity"> 15
  • 16. 4. Declare main activity in manifest MainActivity needs to include intent-filter to start from launcher <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> 16
  • 18. What is an intent? An Intent is a description of an operation to be performed. An Intent is an object used to request an action from another app component via the Android system. 18 App component Originator Intent Action Android System
  • 19. What can intents do? â—ŹStart an Activity â—‹A button click starts a new Activity for text entry â—‹Clicking Share opens an app that allows you to post a photo â—ŹStart an Service â—‹Initiate downloading a file in the background â—ŹDeliver Broadcast â—‹The system informs everybody that the phone is now charging 19
  • 20. Explicit and implicit intents Explicit Intent â—Ź Starts a specific Activity â—‹ Request tea with milk delivered by Nikita â—‹ Main activity starts the ViewShoppingCart Activity Implicit Intent â—Ź Asks system to find an Activity that can handle this request â—‹ Find an open store that sells green tea â—‹ Clicking Share opens a chooser with a list of apps 20
  • 22. Start an Activity with an explicit intent To start a specific Activity, use an explicit Intent • Create an Intent â—‹Intent intent = new Intent(this, ActivityName.class); • Use the Intent to start the Activity â—‹ startActivity(intent); 22
  • 23. Start an Activity with implicit intent To ask Android to find an Activity to handle your request, use an implicit Intent • Create an Intent â—‹Intent intent = new Intent(action, uri); • Use the Intent to start the Activity â—‹ startActivity(intent); 23
  • 24. Implicit Intents - Examples 24 Show a web page Uri uri = Uri.parse("http://www.google.com"); Intent it = new Intent(Intent.ACTION_VIEW,uri); startActivity(it); Dial a phone number Uri uri = Uri.parse("tel:8005551234"); Intent it = new Intent(Intent.ACTION_DIAL, uri); startActivity(it);
  • 25. How Activities Run â—Ź All Activity instances are managed by the Android runtime â—Ź Started by an "Intent", a message to the Android runtime to run an activity 25 MainActivity What do you want to do? FoodListActivity Choose food items...Next OrderActivity Place order User clicks launcher icon Android System Intent: Start app Start main activity Android System Start choose food activity Android System Start finish order activity Intent: Shop Intent: order
  • 27. Two types of sending data with intents â—ŹData—one piece of information whose data location can be represented by an URI â—ŹExtras—one or more pieces of information as a collection of key-value pairs in a Bundle 27
  • 28. Sending and retrieving data In the first (sending) Activity: • Create the Intent object • Put data or extras into that Intent • Start the new Activity with startActivity() In the second (receiving) Activity: • Get the Intent object, the Activity was started with • Retrieve the data or extras from the Intent object 28
  • 29. Putting a URI as intent data // A web page URL intent.setData( Uri.parse("http://www.google.com")); // a Sample file URI intent.setData( Uri.fromFile(new File("/sdcard/sample.jpg"))); 29
  • 30. Put information into intent extras â—Ź putExtra(String name, int value) ⇒ intent.putExtra("level", 406); â—Ź putExtra(String name, String[] value) ⇒ String[] foodList = {"Rice", "Beans", "Fruit"}; intent.putExtra("food", foodList); â—Ź putExtras(bundle); ⇒ if lots of data, first create a bundle and pass the bundle. â—Ź See documentation for all 30
  • 31. Sending data to an activity with extras public static final String EXTRA_MESSAGE_KEY = "com.example.android.twoactivities.extra.MESSAGE"; Intent intent = new Intent(this, SecondActivity.class); String message = "Hello Activity!"; intent.putExtra(EXTRA_MESSAGE_KEY, message); startActivity(intent); 31
  • 32. Get data from intents â—Ź getData(); ⇒ Uri locationUri = intent.getData(); â—Ź int getIntExtra (String name, int defaultValue) ⇒ int level = intent.getIntExtra("level", 0); â—Ź Bundle bundle = intent.getExtras(); ⇒ Get all the data at once as a bundle. â—Ź See documentation for all 32
  • 33. Returning data to the starting activity • Use startActivityForResult() to start the second Activity • To return data from the second Activity: â—Ź Create a new Intent â—Ź Put the response data in the Intent using putExtra() â—Ź Set the result to Activity.RESULT_OK or RESULT_CANCELED, if the user cancelled out â—Ź call finish() to close the Activity • Implement onActivityResult() in first Activity 33
  • 34. startActivityForResult() startActivityForResult(intent, requestCode); â—Ź Starts Activity (intent), assigns it identifier (requestCode) â—Ź Returns data via Intent extras â—Ź When done, pop stack, return to previous Activity, and execute onActivityResult() callback to process returned data â—Ź Use requestCode to identify which Activity has "returned" 34
  • 35. 1. startActivityForResult() Example public static final int CHOOSE_FOOD_REQUEST = 1; Intent intent = new Intent(this, ChooseFoodItemsActivity.class); startActivityForResult(intent, CHOOSE_FOOD_REQUEST); 35
  • 36. 2. Return data and finish second activity // Create an intent Intent replyIntent = new Intent(); // Put the data to return into the extra replyIntent.putExtra(EXTRA_REPLY, reply); // Set the activity's result to RESULT_OK setResult(RESULT_OK, replyIntent); // Finish the current activity finish(); 36
  • 37. 3. Implement onActivityResult() public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == TEXT_REQUEST) { // Identify activity if (resultCode == RESULT_OK) { // Activity succeeded String reply = data.getStringExtra(SecondActivity.EXTRA_REPLY); // … do something with the data }}} 37
  • 39. Activity stack â—ŹWhen a new Activity is started, the previous Activity is stopped and pushed on the Activity back stack â—ŹLast-in-first-out-stack—when the current Activity ends, or the user presses the Back button, it is popped from the stack and the previous Activity resumes 39
  • 40. Activity Stack 40 MainActivity What do you want to do? FoodListActivity Choose food items CartActivity View shopping cart MainActivity What do you want to do? FoodListActivity Choose food items MainActivity What do you want to do? FoodListActivity Choose food items CartActivity View shopping cart OrderActivity Place order MainActivity What do you want to do? After viewing shopping cart, user decides to add more items, then places order.
  • 41. Two forms of navigation Temporal or back navigation â—Źprovided by the device's Back button â—Źcontrolled by the Android system's back stack Ancestral or up navigation â—Źprovided by the Up button in app's action bar â—Źcontrolled by defining parent-child relationships between activities in the Android manifest 41
  • 42. Back navigation â—Ź Back stack preserves history of recently viewed screens â—Ź Back stack contains all the Activity instances that have been launched by the user in reverse order for the current task â—Ź Each task has its own back stack â—Ź Switching between tasks activates that task's back stack 42
  • 43. Up navigation 43 â—ŹGoes to parent of current Activity â—ŹDefine an Activity parent in Android manifest â—ŹSet parentActivityName <activity android:name=".ShowDinnerActivity" android:parentActivityName=".MainActivity" > </activity>
  • 45. Learn more â—ŹAndroid Application Fundamentals â—ŹStarting Another Activity â—ŹActivity (API Guide) â—ŹActivity (API Reference) â—ŹIntents and Intent Filters (API Guide) â—ŹIntent (API Reference) â—ŹNavigation 45
  • 46. What's Next? 46 â—Ź Concept Chapter: 2.1 Activities and Intents â—Ź Practical: 2.1 Activities and intents
  • 47. 2.2 Activity lifecycle and state 47
  • 48. Contents â—ŹActivity lifecycle â—ŹActivity lifecycle callbacks â—ŹActivity instance state â—ŹSaving and restoring Activity state 48
  • 50. What is the Activity Lifecycle? 50 â—Ź The set of states an Activity can be in during its lifetime, from when it is created until it is destroyed More formally: â—Ź A directed graph of all the states an Activity can be in, and the callbacks associated with transitioning from each state to the next one
  • 51. What is the Activity Lifecycle? 51
  • 52. Activity states and app visibility 52 â—Ź Created (not visible yet) â—Ź Started (visible) â—Ź Resume (visible) â—Ź Paused(partially invisible) â—Ź Stopped (hidden) â—Ź Destroyed (gone from memory) State changes are triggered by user action, configuration changes such as device rotation, or system action
  • 54. Callbacks and when they are called 54 onCreate(Bundle savedInstanceState)—static initialization onStart()—when Activity (screen) is becoming visible onRestart()—called if Activity was stopped (calls onStart()) onResume()—start to interact with user onPause()—about to resume PREVIOUS Activity onStop()—no longer visible, but still exists and all state info preserved onDestroy()—final call before Android system destroys Activity
  • 55. Activity states and callbacks graph 55
  • 56. Implementing and overriding callbacks â—ŹOnly onCreate() is required â—ŹOverride the other callbacks to change default behavior 56
  • 57. onCreate() –> Created â—ŹCalled when the Activity is first created, for example when user taps launcher icon â—ŹDoes all static setup: create views, bind data to lists, ... â—ŹOnly called once during an activity's lifetime â—ŹTakes a Bundle with Activity's previously frozen state, if there was one â—ŹCreated state is always followed by onStart() 57
  • 58. onCreate(Bundle savedInstanceState) 58 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The activity is being created. }
  • 59. onStart() –> Started 59 â—Ź Called when the Activity is becoming visible to user â—Ź Can be called more than once during lifecycle â—Ź Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden
  • 60. onStart() 60 @Override protected void onStart() { super.onStart(); // The activity is about to become visible. }
  • 61. onRestart() –> Started 61 â—Ź Called after Activity has been stopped, immediately before it is started again â—Ź Transient state â—Ź Always followed by onStart()
  • 62. onRestart() 62 @Override protected void onRestart() { super.onRestart(); // The activity is between stopped and started. }
  • 63. onResume() –> Resumed/Running 63 â—Ź Called when Activity will start interacting with user â—Ź Activity has moved to top of the Activity stack â—Ź Starts accepting user input â—Ź Running state â—Ź Always followed by onPause()
  • 64. onResume() 64 @Override protected void onResume() { super.onResume(); // The activity has become visible // it is now "resumed" }
  • 65. onPause() –> Paused 65 â—Ź Called when system is about to resume a previous Activity â—Ź The Activity is partly visible but user is leaving the Activity â—Ź Typically used to commit unsaved changes to persistent data, stop animations and anything that consumes resources â—Ź Implementations must be fast because the next Activity is not resumed until this method returns â—Ź Followed by either onResume() if the Activity returns back to the front, or onStop() if it becomes invisible to the user
  • 66. onPause() 66 @Override protected void onPause() { super.onPause(); // Another activity is taking focus // this activity is about to be "paused" }
  • 67. onStop() –> Stopped 67 â—Ź Called when the Activity is no longer visible to the user â—Ź New Activity is being started, an existing one is brought in front of this one, or this one is being destroyed â—Ź Operations that were too heavy-weight for onPause() â—Ź Followed by either onRestart() if Activity is coming back to interact with user, or onDestroy() if Activity is going away
  • 68. onStop() 68 @Override protected void onStop() { super.onStop(); // The activity is no longer visible // it is now "stopped" }
  • 69. onDestroy() –> Destroyed 69 â—Ź Final call before Activity is destroyed â—Ź User navigates back to previous Activity, or configuration changes â—Ź Activity is finishing or system is destroying it to save space â—Ź Call isFinishing() method to check â—Ź System may destroy Activity without calling this, so use onPause() or onStop() to save data or state
  • 70. onDestroy() 70 @Override protected void onDestroy() { super.onDestroy(); // The activity is about to be destroyed. }
  • 72. When does config change? Configuration changes invalidate the current layout or other resources in your activity when the user: â—ŹRotates the device â—ŹChooses different system language, so locale changes â—ŹEnters multi-window mode (from Android 7) 72
  • 73. What happens on config change? On configuration change, Android: 1. Shuts down Activity by calling: 73 2. Starts Activity over again by calling: â—Ź onPause() â—Ź onStop() â—Ź onDestroy() â—Ź onCreate() â—Ź onStart() â—Ź onResume()
  • 74. Activity instance state 74 â—Ź State information is created while the Activity is running, such as a counter, user text, animation progression â—Ź State is lost when device is rotated, language changes, back-button is pressed, or the system clears memory
  • 75. Saving and restoring Activity state 75
  • 76. What the system saves 76 â—Ź System saves only: â—‹ State of views with unique ID (android:id) such as text entered into EditText â—‹ Intent that started activity and data in its extras â—Ź You are responsible for saving other activity and user progress data
  • 77. Saving instance state 77 Implement onSaveInstanceState() in your Activity â—Ź Called by Android runtime when there is a possibility the Activity may be destroyed â—Ź Saves data only for this instance of the Activity during current session
  • 78. onSaveInstanceState(Bundle outState) 78 @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Add information for saving HelloToast counter // to the to the outState bundle outState.putString("count", String.valueOf(mShowCount.getText())); }
  • 79. Restoring instance state Two ways to retrieve the saved Bundle â—Źin onCreate(Bundle mySavedState) Preferred, to ensure that your user interface, including any saved state, is back up and running as quickly as possible â—ŹImplement callback (called after onStart()) onRestoreInstanceState(Bundle mySavedState) 79
  • 80. Restoring in onCreate() 80 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mShowCount = findViewById(R.id.show_count); if (savedInstanceState != null) { String count = savedInstanceState.getString("count"); if (mShowCount != null) mShowCount.setText(count); } }
  • 81. onRestoreInstanceState(Bundle state) 81 @Override public void onRestoreInstanceState (Bundle mySavedState) { super.onRestoreInstanceState(mySavedState); if (mySavedState != null) { String count = mySavedState.getString("count"); if (count != null) mShowCount.setText(count); } }
  • 82. Instance state and app restart 82 When you stop and restart a new app session, the Activity instance states are lost and your activities will revert to their default appearance If you need to save user data between app sessions, use shared preferences or a database.
  • 83. Learn more â—ŹActivities (API Guide) â—ŹActivity (API Reference) â—ŹManaging the Activity Lifecycle â—ŹPausing and Resuming an Activity â—ŹStopping and Restarting an Activity â—ŹRecreating an Activity â—ŹHandling Runtime Changes â—ŹBundle 83
  • 84. What's Next? 84 â—Ź Concept Chapter: 2.2 Activity lifecycle and state â—Ź Practical: 2.2 Activity lifecycle and state
  • 86. Contents â—ŹIntent—recap â—ŹImplicit Intent overview â—ŹSending an implicit Intent â—ŹReceiving an implicit Intent 86
  • 88. What is an Intent? An Intent is: â—ŹDescription of an operation to be performed â—ŹMessaging object used to request an action from another app component via the Android system. 88 App component Originator Intent Action Android System
  • 89. What can an Intent do? An Intent can be used to: â—Źstart an Activity â—Źstart a Service â—Źdeliver a Broadcast Services and Broadcasts are covered in other lessons 89
  • 90. Explicit vs. implicit Intent Explicit Intent — Starts an Activity of a specific class Implicit Intent — Asks system to find an Activity class with a registered handler that can handle this request 90
  • 92. What you do with an implicit Intent â—ŹStart an Activity in another app by describing an action you intend to perform, such as "share an article", "view a map", or "take a picture" â—ŹSpecify an action and optionally provide data with which to perform the action â—ŹDon't specify the target Activity class, just the intended action 92
  • 93. What system does with implicit Intent â—ŹAndroid runtime matches the implicit intent request with registered intent handlers â—ŹIf there are multiple matches, an App Chooser will open to let the user decide 93
  • 94. How does implicit Intent work? • The Android Runtime keeps a list of registered Apps • Apps have to register via AndroidManifest.xml • Runtime receives the request and looks for matches • Android runtime uses Intent filters for matching • If more than one match, shows a list of possible matches and lets the user choose one • Android runtime starts the requested activity 94
  • 95. App Chooser 95 When the Android runtime finds multiple registered activities that can handle an implicit Intent, it displays an App Chooser to allow the user to select the handler
  • 96. Sending an implicit Intent 96
  • 97. Sending an implicit Intent 97 1. Create an Intent for an action Intent intent = new Intent(Intent.ACTION_CALL_BUTTON); User has pressed Call button — start Activity that can make a call (no data is passed in or returned) 1. Start the Activity if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); }
  • 98. Avoid exceptions and crashes 98 Before starting an implicit Activity, use the package manager to check that there is a package with an Activity that matches the given criteria. Intent myIntent = new Intent(Intent.ACTION_CALL_BUTTON); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); }
  • 99. Sending an implicit Intent with data URI 99 1. Create an Intent for action Intent intent = new Intent(Intent.ACTION_DIAL); 1. Provide data as a URI intent.setData(Uri.parse("tel:8005551234")); 1. Start the Activity if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); }
  • 100. Providing the data as URI 100 Create an URI from a string using Uri.parse(String uri) â—Ź Uri.parse("tel:8005551234") â—Ź Uri.parse("geo:0,0?q=brooklyn%20bridge%2C%20brooklyn%2C%20ny") â—Ź Uri.parse("http://www.android.com"); Uri documentation
  • 101. Implicit Intent examples 101 Show a web page Uri uri = Uri.parse("http://www.google.com"); Intent it = new Intent(Intent.ACTION_VIEW,uri); startActivity(it); Dial a phone number Uri uri = Uri.parse("tel:8005551234"); Intent it = new Intent(Intent.ACTION_DIAL, uri); startActivity(it);
  • 102. Sending an implicit Intent with extras 102 1. Create an Intent for an action Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); 1. Put extras String query = edittext.getText().toString(); intent.putExtra(SearchManager.QUERY, query)); 1. Start the Activity if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); }
  • 103. Category 103 Additional information about the kind of component to handle the intent. â—Ź CATEGORY_OPENABLE Only allow URIs of files that are openable â—Ź CATEGORY_BROWSABLE Only an Activity that can start a web browser to display data referenced by the URI
  • 104. Sending an implicit Intent with type and category 104 1. Create an Intent for an action Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); 1. Set mime type and category for additional information intent.setType("application/pdf"); // set MIME type intent.addCategory(Intent.CATEGORY_OPENABLE); continued on next slide...
  • 105. Sending an implicit Intent with type and category 105 3. Start the Activity if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(myIntent,ACTIVITY_REQUEST_CREATE_FILE); } 4. Process returned content URI in onActivityResult()
  • 106. Common actions for an implicit Intent Common actions include: â—ŹACTION_SET_ALARM â—ŹACTION_IMAGE_CAPTURE â—ŹACTION_CREATE_DOCUMENT â—ŹACTION_SENDTO â—Źand many more 106
  • 107. Apps that handle common actions 107 Common actions are usually handled by installed apps (both system apps and other apps), such as: â—Ź Alarm Clock, Calendar, Camera, Contacts â—Ź Email, File Storage, Maps, Music/Video â—Ź Notes, Phone, Search, Settings â—Ź Text Messaging and Web Browsing âž” List of common actions for an implicit intent âž” List of all available actions
  • 108. Receiving an Implicit Intent 108
  • 109. Register your app to receive an Intent â—ŹDeclare one or more Intent filters for the Activity in AndroidManifest.xml â—ŹFilter announces ability of Activity to accept an implicit Intent â—ŹFilter puts conditions on the Intent that the Activity accepts 109
  • 110. Intent filter in AndroidManifest.xml <activity android:name="ShareActivity"> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> </intent-filter> </activity> 110
  • 111. Intent filters: action and category 111 â—Ź action — Match one or more action constants â—‹ android.intent.action.VIEW — matches any Intent with ACTION_VIEW â—‹ android.intent.action.SEND — matches any Intent with ACTION_SEND â—Ź category — additional information (list of categories) â—‹ android.intent.category.BROWSABLE—can be started by web browser â—‹ android.intent.category.LAUNCHER—Show activity as launcher icon
  • 112. Intent filters: data 112 â—Ź data — Filter on data URIs, MIME type â—‹ android:scheme="https"—require URIs to be https protocol â—‹ android:host="developer.android.com"—only accept an Intent from specified hosts â—‹ android:mimeType="text/plain"—limit the acceptable types of documents
  • 113. An Activity can have multiple filters <activity android:name="ShareActivity"> <intent-filter> <action android:name="android.intent.action.SEND"/> ... </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND_MULTIPLE"/> ... </intent-filter> </activity> 113 An Activity can have several filters
  • 114. A filter can have multiple actions & data <intent-filter> <action android:name="android.intent.action.SEND"/> <action android:name="android.intent.action.SEND_MULTIPLE"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="image/*"/> <data android:mimeType="video/*"/> </intent-filter> 114
  • 116. Learn more â—ŹIntent class documentation â—ŹUri documentation â—ŹList of common apps that respond to implicit intents â—ŹList of available actions â—ŹList of categories â—ŹIntent Filters 116
  • 117. What's Next? 117 â—Ź Concept Chapter: 2.3 Implicit Intents â—Ź Practical: 2.3 Implicit Intents
  • 118. Referensi 1. Google, D. (2021, 09 24). Dasar-Dasar Developer Android. Retrieved from Google Developers: https://developers.google.com/training/courses/android-fundamentals?hl=id

Editor's Notes

  1. Up is left
  2. Up is left