Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

PERANGKAT BERGERAK

(MOBILE)


Activity & Intent

K Candra Brata
andra.course@gmail.com
Mobille App Lab 2019-2020
Android Activity
https://developer.android.com/reference/android/app/Activity.html
Activity

An activity is a single, focused thing that the user can do.

Almost all activities interact with the user, so the Activity class takes care
of creating a UI window for you.
Activity
Example
Activity

 Application is Made up with Activities


 An application might consist of just one or more Activities.
 Java class, typically one activity in one java class file
 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

 All activities must Specified in the AndroidManifest.xml


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
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>
2. Define Activity
Java class

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
} Resource is layout in this XML file

Connect activity with layout


3. Declaring Activity
in Android Manifest

 Every Activity has to be declared inside the <application> tag in the


AndroidManifest.xml - otherwise “Activity Not Found” error condition
occurs . . .
Launcher
Activity
Typically, one of the activities is marked as the first one (launcher activity
or main activity) that should be presented to the user when the application
is launched.

An activity can be declared as launcher activity using intent-filter main


action and launcher category declaration in AndroidManifest.xml


<application>
<activity android:name=".MainActivity"
android:icon="@drawable/icon"
android:label= “hello apps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

Launcher Activity
• What happen if you place intent category launcher on both activity?
Activity Stack
 Activities in the system are managed as an activity stack.

 a user will be switching activities while using a mobile device.

 When a new activity is started, it is placed on the top of the stack and
becomes the running activity.

 The previous activity always remains below it in the stack, and will not
come to the foreground again until the new activity exits.
Activity Stack

Managing activities in the system


Activity Stack

Managing activities in the system

After viewing shopping cart, user decides


to add more items, then places order.

OrderActivity
Place order
CartActivity CartActivity
View shopping cart View shopping cart
FoodListActivity FoodListActivity FoodListActivity
Choose food items Choose food items Choose food items
MainActivity MainActivity MainActivity MainActivity
What do you want to do? What do you want to do? What do you want to do? What do you want to do?
Activity State

States Description
Active / The activity is at the top of the Activity Stack.
Running Foreground task visible on the device screen
Paused Activity is still visible but partially obscured, instance is
running but might be killed by the system.
Stopped The activity is currently not visible to the user (in other
words it is totally obscured on the device display by other
activities).
Killed/ The Activity has been terminated by the runtime system in
Destroyed order to free up memory and is no longer present on the
Activity Stack.
Activity State
Activity Life Cycle

 Every Activity has a life cycle.


 Represent the Activity state.
Active and Visible
Lifetimes
Active and Visible
Lifetimes
 onCreate(Bundle savedInstanceState) – The method that is called when the
activity is first created and the ideal location for most initialization tasks to be
performed.

 onRestart() – Called when the activity is about to restart after having previously been
stopped by the runtime system.

 onStart() – Always called immediately after the call to the onCreate() or onRestart()
methods, this method indicates to the activity that it is about to become visible to the
user. This call will be followed by a call to onResume() if the activity moves to the top
of the activity stack, or onStop() in the event that it is pushed down the stack by
another activity.

 onResume() – Indicates that the activity is now at the top of the activity stack and is
the activity with which the user is currently interacting

 onPause() – Indicates that a previous activity is about to become the foreground


activity.

 onStop() – The activity is now no longer visible to the user.

 onDestroy() – The activity is about to be destroyed


Modify Your Activity Java Code....

import android.util.Log;

public class MainActivity extends AppCompatActivity {

private static final String MyActivityTag = "lifecycle";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(MyActivityTag,"OnCreate State");

@Override
protected void onStart() {
super.onStart();
Log.i(MyActivityTag,"OnStart State");
}

@Override
protected void onResume() {
super.onResume();
Log.i(MyActivityTag,"OnResume State");
}

// ......... Continue for another activity States ..........


}
Intent
http://developer.android.com/reference/android/content/Intent.html
Definition
 An Android application could include any number of activities.

 Activities are independent of each other; however they usually


cooperate exchanging data and actions.

 Typically, one of the activities is designated as the first one (main) that
should be presented to the user when the application is launched.

 Moving from one activity to another is accomplished by asking the


current activity to execute an intent.

 Activities interact with each other in an asynchronous mode.


Intent
Intent
Intent
• Intents are invoked using the following options
Intent

Intent dibagi 2 yaitu:


 Implicit intent adalah intent yang memanggil fungsi activity yang
sudah ada di fungsi internal android (Built-in) seperti Dial
Number, Open Browser , Gallery, Music Player dan lainya.

 Explicit Intent yang memanggil Activity lain yang masih dalam 1


project atupun beda project.
Intent

The main arguments of an Intent are


1. Action, The built-in action to be performed, such as
ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, … or user-created-
activity.
2. Data, The primary data to operate on, such as a phone number
to be called (expressed as a Uri).
Intent
Typically an intent is called as follows:
Implicit Intent
Implicit Intent
Examples of action/data pairs are:

ACTION_DIAL , tel:123
Display the phone dialer with the given number filled in.

ACTION_VIEW , http://www.google.com
Show Google page in a browser view. Note how the VIEW action does what is
considered the most reasonable thing for a particular URI.

ACTION_EDIT , content://contacts/people/2
Edit information about the person whose identifier is "2".

ACTION_VIEW , content://contacts/people/2
Used to start an activity to display 2-nd person.

ACTION_VIEW , content://contacts/ people/


Display a list of people, which the user can browse through. Selecting a particular person
to view would result in a new intent
main.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="btn1Click"
android:text="Button 1"></Button>

<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:onClick="btn2Click"
android:text="Button 2"></Button>

<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="btn3Click"
android:text="Button 3"></Button>

</LinearLayout>
MainActivity.Java
public class MainActivity extends AppCompatActivity {

private Button btn1,btn2,btn3;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btn1 = (Button) findViewById(R.id.btn1);


btn2 = (Button) findViewById(R.id.btn2);
btn3 = (Button) findViewById(R.id.btn3);
}

public void btn1Click(View view) {


Intent tlp = new Intent (Intent.ACTION_DIAL, Uri.parse("tel:93675359"));
startActivity(tlp); }

public void btn2Click(View view) {


Intent setting = new Intent( android.provider.Settings.ACTION_SETTINGS);
startActivity(setting);
Toast.makeText(this, "you have Pressed : " + btn2.getText() , Toast.LENGTH_LONG).show();
}

public void btn3Click(View view) {


// DO YOUR METHOD HERE !!
} }
Intent
Secondary Attributes
In addition to the primary action/data attributes, there are a number of
secondary attributes that you can also include with an intent, such as:
1. Category
2. Type
3. Extras

Example: Doing a Google search looking for intent android.


Modify Button 3 Click !!!

Intent search = new Intent (Intent.ACTION_WEB_SEARCH );


search.putExtra(SearchManager.QUERY, "intent android");
startActivity(search);
Implicit Intent
Secondary Attributes

Intent myIntent= new Intent();


myIntent.setType("audio/mp3");
myIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivity(myIntent);
Explicit Intent
Call Another Activity
An activity A can launch another activity B in response to an event.
– The activity A can pass data to B.
– The activity B can send data back to A when it is done.
Explicit Intent
Call Another Activity
– creates a new activity .java class in src/java
– creates a new layout .XML file in res/layouts
– adds information to AndroidManifest.xml about the new activity
(without this information, the app will not allow the activity)
Explicit Intent
Call Another Activity
Every activity has an entry in project's AndroidManifest.xml, added
automatically by Android Studio:
Explicit Intent
Call Another Activity
• What happen if you place intent category launcher on both activity?
Explicit Intent
Call Another Activity

Intent myIntent = new Intent (MainActivity.this, Activity2.class);


startActivity(myIntent);
Explicit Intent
Secondary Attributes
Sending Activity (MainActivity)
Intent intent = new Intent(MainActivity.this, Activity2.class);
// pass your values and retrieve them in the other Activity using keyName
intent.putExtra("keyName", value);
startActivity(intent);

Recieving Activity ( Activity2)

Bundle extras = intent.getExtras();


if(extras != null)
String data = extras.getString("keyName"); // retrieve the data using keyName

OR
// shortest way to recieve data..
String data = getIntent().getExtras().getString("keyName");
// shortest way to recieve data..
String data = getIntent().getStringExtra("keyName");
Explicit Intent
Secondary Attributes

Sending Activity Recieving Activity


Explicit Intent Let’s try to pass “string” and “boolean” data type.
Example In the MainActivity add edittext and checkbox
Explicit Intent
Example
And this is the SecondActivity that will get/receive the data
Explicit Intent
Example

MainActivity
Explicit Intent
Example

SecondActivity
Explicit Intent
Example
Intent
• Starting Activities and Getting Results
• The startActivity(Intent) method is used to start a new activity, which will be
placed at the top of the activity stack.
• Sometimes you want to get a result back from the called sub-activity when it
ends.

For example, you may start an activity that let the user pick a image from
galery; when it ends, it returns the image that was selected.
Intent
• In order to get results back from the called activity we use the method

• startActivityForResult ( Intent, requestCodeID )

• Where the second (requestCodeID) parameter identifies the call.


• The result sent by the sub-activity could be picked up through the
asynchronous method.

• onActivityResult ( requestCodeID, resultCode, Intent )


Intent
• Before an activity exits, it can call setResult(resultCode) to return a
termination signal back to its parent.
• Always supply a result code, which can be the standard results
Activity.RESULT_CANCELED, Activity.RESULT_OK, or any custom values.

• All of this information can be capture back on the parent's


onActivityResult (int requestCodeID, int resultCode, Intent data) along with
the integer identifier it originally supplied.

• If a child activity fails for any reason (such as crashing), the parent activity will
receive a result with the code RESULT_CANCELED.
Intent
MainActivity.Java
public class MainActivity extends AppCompatActivity {

private Button btn1,btn2,btn3;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btn1 = (Button) findViewById(R.id.btn1);


btn2 = (Button) findViewById(R.id.btn2);
btn3 = (Button) findViewById(R.id.btn3);
}

public void btn1Click(View view) {


Intent tlp = new Intent (Intent.ACTION_DIAL, Uri.parse("tel:93675359"));
startActivity(tlp); }

public void btn2Click(View view) {


Intent setting = new Intent( android.provider.Settings.ACTION_SETTINGS);
startActivity(setting);
Toast.makeText(this, "you have Pressed : " + btn2.getText() , Toast.LENGTH_LONG).show();
}

public void btn3Click(View view) {


// DO YOUR METHOD HERE !!
} }
MainActivity.Java
Modify Your Code !!!! Showing Pictures and Video,
Calling a sub-activity, receiving results.
public void btn3Click(View view) {
Intent myIntent= new Intent();
myIntent.setType("video/*, images/*");
myIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(myIntent, 0);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if((requestCode== 0) && (resultCode == Activity.RESULT_OK)) {
String selectedImage= intent.getDataString();
Toast.makeText(this, selectedImage, Toast.LENGTH_LONG).show();

// show a 'nice' screen with the selected image


Intent myAct3 = new Intent(Intent.ACTION_VIEW, Uri.parse(selectedImage));
startActivity(myAct3);
}
Thanks!
JOIN !!

http://bit.do/PB_Tekom

You might also like