b2. activity and intent
TRANSCRIPT
PERKYTORIALS
Topic: Activity & Intents
Overview
• Activity• Layout• Event Listener• Explicit Intent• Implicit Intent • Native android Actions• Data transfer between two activities
What is activity?
• An activity is a single, focused thing with which user can interact.• A window to draw its UI
The Activity class takes care of creating a window for you in which you can place your UI with setcontentview(view).
Activity Lifecycle Activities in the system are managed as an activity stack. 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
• onCreate• onStart• onResume• onPause• onStop• onDestroy
Activity Life cycle state
Activity Lifecycle (Cont.)
Activity Lifecycle (Cont.)
OnCreate:
This is the first method to be called when an activity is created. OnCreate is always overridden to perform any startup initializations that may be required by an Activity such as:– Creating views– Initializing variables– Binding static data to lists
@overridepublic void OnCreate(Bundle bundle) { super.OnCreate(bundle); }
• Example
Activity Lifecycle (Cont.)
onStart:
This method is always called by the system after OnCreate is finished. Activities may override this method if they need to perform any specific tasks right before an activity becomes visible such as refreshing current values of views within the activity.
@overridepublic void OnStart() { super.onStart(); }
• Example
Activity Lifecycle (Cont.)
onResume:
The system calls this method when the Activity is ready to start interacting with the user. Activities should override this method to perform tasks such as:– Ramping up frame rates (a common
task in game building)– Starting animations– Listening for GPS updates– Display any relevant alerts or dialogs– Wire up external event handlers
@overridepublic void OnResume() { super.onResume(); }
• Example
Activity Lifecycle (Cont.)
onPause:
This method is called when the system is about to put the activity into the background or when the activity becomes partially obscured. Activities should override this method if they need to:– Commit unsaved changes to persistent
data– Destroy or clean up other objects
consuming resources– Ramp down frame rates and pausing
animations
@overridepublic void OnPause() { super.onPause(); }
• Example
Activity Lifecycle (Cont.)
onStop:
This method is called when the activity is no longer visible to the user. This happens when one of the following occurs:– A new activity is being started and
is covering up this activity.– An existing activity is being brought
to the foreground.– The activity is being destroyed.
@overridepublic void OnStop() { super.onStop(); }
• Example
Activity Lifecycle (Cont.)
onDestroy:
This is the final method that is called on an Activity instance before it’s destroyed and completely removed from memory. In extreme situations Android may kill the application process that is hosting the Activity, which will result in OnDestroy not being invoked
@overridepublic void OnDestroy() { super.onDestroy(); }
• Example
Activity Lifecycle (Cont.)
onRestart:
This method is called after your activity has been stopped, prior to it being started again. A good example of this would be when the user presses the home button while on an activity in the application. When this happensOnPause and then OnStop methods are called, and the Activity is moved to the background but is not destroyed
@overridepublic void OnRestart() { super.onPause() super.onStop() }
• Example
Assessment• Create a new project• In the main activity implements all method that we are described
already ( onCreate, onStart(), onStopetc. )• To observe the result add the below code inside your MainActivity classThis code is for showing
notification. Don’t worry. We will explain this later.
Just write this code.
Assessment• Call the notify method from each method( onCreate, onPause etc) and pass the name of the method
which is calling the notify method.
• Similarly implement others method (onResume, onDestroy)
Assessment• Now run the project to observe the effect of each method.• When each method called a notification will be appeared at the top of your
notification bar in your device.
Event Listener
• What is event listener?
• Why we need this?
• How to use Event listener?
Event Listener
• Events are a useful way to collect data about a user's interaction with interactive components of your app, like button presses or screen touch etc.
• The Android framework maintains an event queue into which events are placed as they occur and then each event is removed from the queue on a first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action as per requirements.
Event Listener• In the figure there is an activity and a button on it.• When user clicked/ press the “Click Me” button an event generated and we toast
a text. • SO it is useful to handle user interaction as well as navigation according to user
interaction
.
After Clicking button
Some types of Event Listener
Event Listeners Registration• Event Registration is the process by which an Event Handler
gets registered with an Event Listener so that the handler is called when the Event Listener fires the event.
• Some way of event listeners registration- 1 Using an Anonymous Inner Class 2 Activity class implements the Listener interface. 3 Using Layout file activity_main.xml to specify event handler directly.
Using an Anonymous Inner Class Create an anonymous implementation of the listener.• Useful if each class is applied to a single control only and you have advantage to
pass arguments to event handler.• In this approach event handler methods can access private data of Activity. No
reference is needed to call to Activity.
Disadvantage• If there are more than one control, you have to cut and paste the code for the
handler and if the code for the handler is long, it makes the code harder to maintain
Assessment • Add a button in xml file
• Initialize it from java file
<Button android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="Click Me"/>
Button clickMe = (Button) findViewById(R.id.button1);
Assessment • Register click event with button
clickMe.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {
//write your code here Toast.makeText(“getApplicationContext()”, ”You clicked a button”,Toast.LENGTH_LONG).show();
}});
Using the Activity Implements Listener Interface
Activity class implements the Listener interface and put the handler method in the main Activity and then call setOnClickListener(this).
This approach is fine if your application has only a single control of that Listener type otherwise have to do further programming to check which control has generated event.
Second you cannot pass arguments to the Listener so, again, works poorly for multiple controls.
Assessment • Implements onClickListener callback
• Implements onClickListener() to MainActivity
<Button android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="match_parent" android:text=“First Button"/>
<Button android:id="@+id/button2" android:layout_height="wrap_content" android:layout_width="match_parent" android:text=“Second Button"/>
Assessment • Implements onClickListener() CallBack which is onCLick()
public void onClick(View v) { if(v.getId() == R.id.button1) { // write your code here return; } if(v.getId() == R.id.button2)
// write your code here return; } }
Using Layout file activity_main.xml Put your event handlers in Activity class without implementing a Listener interface or call to any
listener method.
Rather you will use the layout file (activity_main.xml) to specify the handler method via the android:onClick attribute for click event.
Can be control click events differently for different control by passing different event handler methods.
The event handler method must have a void return type and take a View as an argument.
The method name is arbitrary, and the main class need not implement any particular interface.
This approach does not allow to pass arguments to Listener and for the Android developers it will be difficult to know which method is the handler for which control until they look into activity_main.xml file.
Assessment • Used android:onClick attribute to specify a callback function
<Button android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="match_parent" android:text=“First Button“android:onClick=“method1” />
<Button android:id="@+id/button2" android:layout_height="wrap_content" android:layout_width="match_parent" android:text=“Second Button“android:onClick=“method2” />
android:onClick
Assessment • Implements onClickListener() CallBack which is onCLick()
public void method1(View v) {// write your handler code herereturn; }
//--- Implement the event handler for the second button. public void method2(View v) {// write your handler code herereturn; }
Intent and Intent Filter • Intent is an object carrying an intent ie. message from one component
to another component with-in the application or outside the application
• The intents can communicate messages among any of the three core components of an application - activities, services, and broadcast receivers.
• For example, via the startActivity() method you can define that the intent should be used to start an activity.
• An intent can contain data via a Bundle. This data can be used by the receiving component.
Intent and Intent Filter • Separate mechanisms for delivering intents to each type of
component
Intent (Cont..)
• An Intent object is a bundle of information which is used by the component that receives the intent plus information used by the Android system. An Intent object can contain the following components based on what it is communicating or going to perform:
* ACTION * DATA * CATEGORY * EXTRAS * FLAGS * COMPONENT NAME
Intent: ACTION• Mandatory part of the Intent object and is a string naming the action to be
performed.• . The Intent class defines a number of action constants corresponding to
different intents• The action in an Intent object can be set by the setAction() method and read by
getAction().
Intent: DATA• The URI of the data to be acted on and the MIME type of that
data.
• For example, if the action field is ACTION_EDIT, the data field would contain the URI of the document to be displayed for editing.
• The setData() method specifies data only as a URI, setType() specifies it only as a MIME type, and setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and the type by getType().
Intent: CATEGORY• The category is an optional part of Intent object
• It's a string containing additional information about the kind of component that should handle the intent
• The addCategory() method places a category in an Intent object, removeCategory() deletes a category previously added, and getCategories() gets the set of all categories currently in the object.
• Later we will use categories to choose appropriate acivity
coressponding to an Intent.
Intent: Extras• This will be in key-value pairs for additional information that
should be delivered to the component handling the intent.
• The extras can be set and read using the putExtras() and getExtras() methods respectively
Flag• These flags are optional part of Intent object and instruct the Android
system how to launch an activity, and how to treat it after it's launched etc.
Intent: Component Name• Optional field is an android ComponentName object
representing either Activity, Service or BroadcastReceiver class.
• If it is set, the Intent object is delivered to an instance of the designated class otherwise Android uses other information in the Intent object to locate a suitable target.
• The component name is set by setComponent(), setClass(), or setClassName() and read by getComponent().
Types of Intent• There are following two types of intents supported by
Android till version 4.1
Intent : Explicit Intent• These intents designate the target component by its name and they are typically
used for application-internal messages - such as an activity starting a subordinate service or launching a sister activity.
•Example
Intent : Explicit Intent• For example if we want to start a new Activity and want to pass some value then the
below code will do that.
• First we are defining the new Activity then putting the value in Extra and finally starting the activity using startActivity() method. To get this value in TargetActivity like this
Intent intent = new Intent(this, TargetActivity.class); intent.putExtra("Key1", "ABC"); // putting value to extraintent.putExtra("Key2", "123"); // Starts TargetActivity startActivity(intent);
Bundle extras = getIntent().getExtras();String inputString1 = extras.getString(“Key1"); String inputString2 = extras.getString(“Key2");
Intent : Implicit Intent• These intents do not name a target and the field for the component name is left
blank. Implicit intents are often used to activate components in other applications.Example
Intent : Implicit Intent• For example if we want to open a url in a browser than it will be implicit intent and we
will not mentioned which activity will be responsible for this action• Implicit Intent by specifying a URI
• Here we didn’t specify the activity that will be responsible to open the url of facebook. So Android system will handle this action.
• If multiple activity is responsible to handle this action then a dialog will show to the user for the selection of appropriate activity.
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com")); // Starts Implicit Activity startActivity(i);
Assessment• Open a new android project• Take two button in xml file<Button
android:id="@+id/implicit" android:layout_height="wrap_content" android:layout_width="match_parent" android:text=“Implicit Intent“/>
<Button android:id="@+id/explicit" android:layout_height="wrap_content" android:layout_width="match_parent" android:text=“Explicit Intent“/>
Assessment (Cont..)• Initialize button in java• Add listener to the button • Open another activity named it SecondActivity.• One important thing is if you want to call an Explicit Intent
then first it needs to register in AndroidmManifest.xml file.
• Create a layout for the SecondActivity and set it .
<activity android:name=“.SecondActiity”> </activity>
Assessment (Cont..)• Button initialization may look like this
Button buttonImplicit = (Button) findViewById(R.id.implicit); Button buttonExplicit = (Button) findViewById(R.id.explicit);
buttonImplicit.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //write your Implicit Intent code here }});
buttonExplicit.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //write your Explicit Intent code here }});
Assessment (Cont..)• Inside onClick of buttonImplicit we want to open a url so the
code may look like this
• Inside onClick of buttonExplicit we want to start our SecondActivity so the code may look like this
Intent implicitIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.google.com")); startActivity(implicitIntent);
Intent explicitIntent = new Intent(MainActivity.this,SecondActivity.class) startActivity(explicitIntent);
Assessment (Cont..)• Run the project. Don’t forget to add the SecondActivity in
manifest file what we have shown previous• Press the two button to observe the result of explicit intent
and implicit intent• If everything is ok then Mission Complete
Intent Filter• To pinpoint the set of Activities, Services, and Broadcast
receivers that can handle the Intent with help of specified set of action, categories, data scheme associated with an Intent.
• Use <intent-filter> element in the manifest file to list down actions, categories and data types associated with any activity, service, or broadcast receiver.
• Lets modify our previous project to understand the purpose of Intent Filter.
Assessment: Intent Filter• Add another button in your activity_main.xml file and name it
buttonFilter (its your choice)• Add listener two this button like previous two button. • Add below code inside the onClick method of buttonFilter
• Here we are set to launch an activity to handle www.google.com• Now we want that our SecondActivity will handle this for that
we need to add intent filter for SecondActivity in manifest file
Intent i = new Intent("com.ict.intentdemo.LAUNCH", Uri.parse("http://www.google.com")); startActivity(i);
Assessment: Intent Filter• Here we add intent filter in manifest file.• Here we set an action LAUNCH and category DEFAULT.• Add data http . So when user press a button it comes to SecondActivity if inside the uri it
must be a value “http”
• So android choose our SecondActivity to handle this intent• If you write https in the uri field of MainActivity then it will create an exception because it
can not be filtered
<activity android:name="com.ict.intentdemo.SecondActivity" android:label="@string/app_name"> <intent-filter> <action android:name="com.ict.intentdemo.LAUNCH" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http" /> </intent-filter> </activity>