0% found this document useful (0 votes)
64 views69 pages

Mobile Application Development Activities, Services, Broadcast, Etc

An activity represents a single screen in an Android application that provides a user interface. Activities are represented by a subclass of the Activity class. Each activity is given a window to draw its UI and is represented by both XML layout files and Java code files. Multiple activities can be created and arranged in a stack, with intents used to start one activity from another. The activity lifecycle involves methods like onCreate, onStart, onResume, onPause, onStop and onDestroy that control when the activity is visible and interacting with the user.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views69 pages

Mobile Application Development Activities, Services, Broadcast, Etc

An activity represents a single screen in an Android application that provides a user interface. Activities are represented by a subclass of the Activity class. Each activity is given a window to draw its UI and is represented by both XML layout files and Java code files. Multiple activities can be created and arranged in a stack, with intents used to start one activity from another. The activity lifecycle involves methods like onCreate, onStart, onResume, onPause, onStop and onDestroy that control when the activity is visible and interacting with the user.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

ACTIVITIES

ACTIVITY
 Activity represents a single screen with a user interface (UI) of an application and it acts as an entry point
for users to interact with an app.

 The android apps will contain multiple screens and each screen of our application will be an extension of
activity class. By using activities, we can place all our android application UI components in a single
screen.

 Each activity is given a window in which to draw its user interface.

 An activity in android is a specific combination of XML files and JAVA files. It is basically a container
that contains the design as well as coding .

 The Activity must register in AndroidManifest.xml file


 The main activity is presented to the user when launching an application, each activity can then start
other activities in order to perform different actions.

 Android activities are started or activated with an intent. Intents are asynchronous messages that you
can use in your activity to request an action from another activity. Intents are used to start one activity
from another and to pass data between activities.

 Activities are subclasses of the Activity class, or one of its subclasses. When you create a new project
in Android Studio, your activities are, by default, subclasses of the AppCompatActivity class. The
AppCompatActivity class is a subclass of Activity that lets you to use up-to-date Android app features
such as the action bar and material design, while still enabling your app to be compatible with devices
running older versions of Android.
ACTIVITY LIFE CYCLE
 onCreate() — the activity is first created.  This method is called when the user clicks on your app’s icon,

which causes this method to create the activity. This method is required for every activity, as it sets the

layout. The onCreate() method takes in a Bundle as a parameter. This Bundle will be used by the activity to

reinstate itself back to the previous state using the data stored in the Bundle.

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_register);

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

}
 onResume() — the activity starts interacting with the user

 onPause() — the current activity is being paused and the previous activity is being resumed

 onStart() — the activity becomes visible to the user


@Override
protected void onStart() {
super.onStart();
}
Note: the above can also be used for onResume,onPause,onDestory,onPause,onStart
@Override
protected void onResume() {
super.onStart();
}
 onStop: The activity is no longer visible to the user. This can happen because it is being destroyed or is
going to background so that another activity takes its place at the top of the stack and is visible to the
user.

 onDestroy() The activity is destroyed by the system, it is called because the activity is terminating
(someone called finish ()), or because the system is temporarily destroying this activity instance to
save space.

 onRestart: Called when an activity that was stopped in the background is returning to the foreground
because the activity that was visible above it is being destroyed or called. It always runs when an
activity is in the STOP state.
TASKS
 A task is the sequence of activities the user follows to accomplish an objective, regardless of which
applications the activities belong to

 All activities in a task are arranged in a stack

*If one activity starts another, the new activity is pushed on the stack and it becomes the running activity

*When the user presses the BACK key, the current activity is popped from the stack and the previous one
resumes
DIFFERENCE BETWEEN ACTIVITIES AND TASKS
S.NO ACTIVITIES TASKS
1 A concrete class in the API More of a notion than a concrete API entity.

2 An encapsulation of a particular operation. A collection of related activities

3 They run in the process of the APK which installed Capable of spanning multiple processes
them.

4 Optionally associated with a window(UI) Associated with their own UI history stack.

5 An execution content What users on other platform knows as applications.


HOW TO CREATE A NEW ACTIVITY

In order to implement an activity in your app, do the following:

• Create an activity Java class.

• Implement a user interface for that activity.

• Declare that new activity\ register in the app manifest(manifest.xml file)

Below is an illustration of steps to create an activity

 To create an activity in Android, right click ‘app’ under the project tab of your app, then
click New > Activity > Empty Activity\Blank Activity. It doesn’t have to be an empty activity but it is

the simplest type of activity to start with if you’re just getting started with Android app development .
 Name your activity in a manner that clearly distinguishes its purpose from the other parts of your app.
For this example, the activity name will be Main2Activity

 Note:

In order to launch the activity use the below approach:

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

startActivity(intent);
PICTORIAL
REPRESATATION ON
HOW TO CREATE AN
ACTIVITY
Basic guidelines on the activity concept
 The  Main2Activity is a java file and the activity_main2 has the xml file which works on the layout

 The above procedure has a creation of an activity from the src which has java files
In case a developer wants to add both files the can follow the above procedure. However, the can also
chose to create it under the res->layout as shown in the next slide.
 When a project is created we have the main default class main activity and the activity_main for the
layout which on can renamed, we are required to create other classes for various operation and also
add layout files depending on our design

 If individual files are to be added, the developer is to go on the package right click then go to new then
class incase java files need to be added for the xml one has to the layouts section to do that
SAMPLE CODES
Sample code for declare the activity in the manifest
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Basic code for a subclass of AppCompatActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
CREATE A NEW ANDROID PROJECT

 First Activity Create a New Android Project

 First, open a new project with Blank Activity. And give it a name as you want (e.g. FirstActivity).

 Open the layout file for this Activity. Here we are going to make a Button and an EditText, and on
Button click, we will navigate to another Activity. Paste the following code in your .xml file.
<?xml version="1.0" encoding="utf-8"?> Activity_First.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context="com.example.soumyaagarwal.myfirstproject.MainActivity"

android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Text"
android:textColor="#000000"
android:textSize="20dp"
android:textStyle="bold"
android:id="@+id/text" />
<Button
android:text="Click Me"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button" />
</LinearLayout>
Add Java Code to Switch between Activities

package com.example.soumyaagarwal.myfirstproject; Note: We enter some


import android.content.Intent; text in edit text and then
import android.support.v7.app.AppCompatActivity; click on the button. This
import android.os.Bundle; button will navigate us
import android.view.View; to Second Activity, and
import android.widget.Button; the text you have
import android.widget.EditText; entered will be visible
public class FirstActivity extends AppCompatActivity { there.
EditText text; The file name will be
Button clickme ; FirstActivity.java
String Texthere;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);

clickme = (Button)findViewById(R.id.button);
text = (EditText)findViewById(R.id.text);
clickme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Texthere = text.getText().toString();
Intent intent = new Intent(FirstActivity.this,
SecondActivity.class);
intent.putExtra("Text",Texthere);
startActivity(intent);
}
});
}
}
activity_second.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.soumyaagarwal.myfirstproject.SecondActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10dp"
android:text="Text from FirstActivity:"
android:textColor="#000000"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#000000"
android:id="@+id/textreceived"/>
<Button
android:text="Go Back"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button2" />
</LinearLayout>
SecondActivity.java
package com.example.soumyaagarwal.myfirstproject;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
TextView textreceived;
Button button2;
String text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
text = getIntent().getExtras().getString("Text");
textreceived = (TextView)findViewById(R.id.textreceived);
textreceived.setText(text);
button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SecondActivity.this,FirstActivity.class);
startActivity(intent);
}
});
}
}
SAMPLE OUTPUT
INTENTS
INTRODUCTION
 An intent is a messaging object used to request any action from another app component. Intents facilitate
communication between different components in several ways. The intent is used to launch an activity, start
the services, broadcast receivers, display a web page, dial a phone call, send messages from one activity to
another activity etc..

 It is used to navigate one activity to another

 Through the startActivity() method you can define that the intent should be used to start an activity. In the
target Activity, via startActivity() method, you can determine the sender's intention to start this Activity

 There are two types of intents , explicit and implicit Intent


1.EXPLICIT INTENT

 Explicit is mainly used in a single application (within the application)

 It is used to define which android component should be opened on some user action, such that the
external class to be invoked is provided by the intent as shown below:

 Intent intent=new Intent(this, B.class)


STEPS TO CREATE AN EXPLICIT INTENT

 You need to make an Intent object. The constructor of the Explicit Intent's object needs two parameters as
follows:

 Context c: This represents the object of the Activity from where you are calling the intent.

 Java file name: This represents the name of the java file of the Activity you want to open.

 Intent i = new Intent(this, home.class);

 Call startActivity() method and pass the intent's object as the parameter. This method navigates to the java
file mentioned in the Intent's object.

 startActivity(i);
 If you need to pass some information or data to the new Activity you are calling, you can do this by calling
putExtra() method before the startActivity() method. This method accepts key-value pair as its parameter.

 i.putExtra(“firstname", “First name");

 startActivity(i);

 Note: To receive the data in the new Activity and use it accordingly, you need to call the getIntent() method
and then getStringExtra() method in the java class of the Activity you want to open through explicit intent.
getStringExtra() method takes the key as the parameter.

 String t = getIntent().getStringExtra(“firstname");

 Doing this, stores the value stored at firstname into the string variable t.
2.IMPLICIT INTENT

 This is used to call an activity from other applications.

 Implicit intents do not name a specific component to perform a particular action, but instead it declares a
general action to be performed, which allows any component, even from another app to handle it. Thus can
be basically used as the examples below:

//An intent to access contacts

Intent intent = new Intent();

Intent.setAction(android.content.intent.ACTION_VIEW);

Intent.setDeta(ContactsContract.Contacts.intent.CONTENT_URI);

startActivity(intent);

// An intent to call
Intent calling = new Intent(Intent.ACTION_CALL,Uri.parse("tel:0999010101")); startActivity(calling);
STEPS TO CREATE AN IMPLICIT INTENT

 You need to make an Intent object. The constructor of the Implicit Intent's object needs a type of action you
want to perform.

 An action is a string that specifies the generic action to be performed. The action largely determines
how the rest of the intent is structured, particularly the information that is contained as data and extras
in the intent object. For example,

 ACTION_VIEW: This action is used when you have some information that an activity can show
to the user, such as a photo to view in a Gallery app, or an address to view in a Map app.

 ACTION_SEND: This action is used when you have some data that the user can share through
another app, such as an Email app or some Social Networking app.
 Note: You can specify your own actions for getting used by intents within your own app (or for getting
used by other apps to invoke components in your app), but you usually specify action constants defined
by the Intent class or other framework classes.

 Intent i = new Intent(Intent.ACTION_VIEW);

 You need to provide some data for the action to be performed. Data is typically expressed as a
URI(Uniform Resource Identifier) which provides data to the other app so that any other app which is
capable of handling the URI data can perform the desired action. For example, if you want to open a
website through your app, you can pass the Uri data using setData() method as follows:

 i.setData(Uri.parse("https://www.google.com"));

 Call startActivity() method in the end with the intent object as the parameter.

 startActivity(i);
INTENT OBJECT STRUCTURE
• An intent object is a bundle of information. It contains information of interest to the component that
receives the intent plus information of interest to the Android system. Principally, it can contain the
following:

 Component name

 Action

 Data

 Category

 Extras

 Flags
ACTION
 A string naming the action to be performed or, in the case of broadcast intents, the action that took place and
is being reported. The Intent class defines a number of action constants.

Constant Target component Action


ACTION_CALL activity Initiate a phone call.
ACTION_EDIT activity Display data for the user to edit.

ACTION_MAIN activity Start up as the initial activity of a task, with no


data input and no returned output.

ACTION_SYNC activity Synchronize data on a server with data on the


mobile device.

ACTION_BATTERY_LOW broadcast receiver A warning that the battery is low.

ACTION_HEADSET_PLUG broadcast receiver A headset has been plugged into the device, or
unplugged from it.

ACTION_SCREEN_ON broadcast receiver The screen has been turned on.

ACTION_TIMEZONE_CHANGED broadcast receiver The setting for the time zone has changed.
DATA
 The URI of the data to be acted on and the MIME type of that data. Different actions are paired with
different kinds of data specifications. For example, if the action field is ACTION_EDIT, the data field
would contain the URI of the document to be displayed for editing.
COMPONENT NAME
 The name of the component that should handle the intent.
 This field is a component name object which has a combination of the fully qualified class name of the
target component and the package name set in the manifest file of the application where the component
resides (for example, "com.example.project").
 The component name is set by setComponent(), setClass(), or setClassName() and read by
getComponent().
CATEGORY

 A string containing additional information about the kind of component that should handle the intent. Any
number of category descriptions can be placed in an Intent object. As it does for actions, the Intent class
defines several category constants.

EXTRAS

 Key-value pairs for additional information that should be delivered to the component handling the intent.
Just as some actions are paired with particular kinds of data URIs, some are paired with particular extras.

 These methods parallel those for Bundle objects. In fact, the extras can be installed and read as a Bundle
using the putExtras()and getExtras() methods.
Extras Field

• Key-value pairs for additional information that should be delivered to the component handling the intent.

• Just as some actions are paired with particular kinds of data URIs, some are paired with particular extras.

*ACTION_TIMEZONE_CHANGED action has a "timezone“ extra that identifies the new time zone

*ACTION_HEADSET_PLUG action has a "state" extra indicating whether the headset is now plugged in
or unplugged , as well as a "name" extra for the type of headset
Flags Field

• Flags of various sorts.

• Many instruct the Android system how to launch an activity (for example, which task the activity should
belong to) and how to treat it after it's launched (for example, whether it belongs in the list of recent
activities).

FLAGS

 Flags of various sorts. Many instruct the Android system how to launch an activity and how to treat it after
it's launched . All these flags are defined in the Intent class.
There are four intent flags and they may be described as follows:

FLAG_ACTIVITY_NEW_TASK:

 It starts the activity in a new task.If a task is already running for the activity , you are now starting that
task is brought to the foreground with the last state restored and the activity and the activity received the
new intent is onNewIntent().

FLAG_ACTIVITY_SINGLE_TOP:

 If the activity being started is just the content activity at the top of the back stack, then the executing
instance receives a call to onNewIntent(), instead of creating a new instance of the activity.
FLAG_ACTIVITY_NO_HISTORY:

 This flag implies that the called activity is not kept in the task’s stack when navigating away, the user
cannot restore to it.

FLAG_ACTIVITY_CLEAR_TOP:

 If the activity being started is already running in the current task, then instead of breaching the intent
of the activity , all of the other activities on top of the destroyed and the intent is delivered to the
returned instance of the activity .
INTENT FILTERS
 Intent Filters are the declarations that are present in your app’s manifest file<AndroidManifest.xml>. This
plays an essential role in defining the behavior of the intent thus used to specify the type of intents that the
component would like to receive. In addition, these filters help you in customizing your intents.

 In order to define the behavior of an intent, you require the following attribute tags in the intent filter:

 <actions>: It keeps all the actions you wish your intent to accept.

 <data>: It defines the type of data that the intent will take.

 <category>: It represents the name of the category that the intent will accept.
 Intent resolution is the process of searching for appropriate application components for your intents.
Usually, we see intent resolution in the case of implicit intent.

 In Implicit intent, since we don’t provide the component name, the system tries to find a component. This
finding of the android component is done in three steps based on tests:

 Action test

 Category test

 Data test
ACTION TEST

 An <intent-filter> element in the manifest file lists actions as <action>sub elements

CATEGORY TEST

 An <intent-filter> element also list categories as sub elements.

DATA TEST

 Like the action and categories, the data specification for an intent filter is contained in a sub
element. And, as in those cases, the sub element can appear multiple times, or not at all.
<activity android:name ``.MainActivity”>

<intent-filter>

<action android:name= “android.intent.action.SEND”>

<category android:name= “android.intent.category.HOME”>

<data android:mimeType= “text/plain”>

</intent-filter>

</activity>
ANDROID SERVICES
INTRODUCTION
 Android Services are the application components that run in the background

 They can be connected to other components and do inter-process communication

 The android services has three types namely:

 Fore background

 Background

 Bound
Foreground Services

 Foreground services are those services that are visible to the users. The users can interact with
them at ease and track what’s happening. These services continue to run even when users are
using other applications.

Background Services

 These services run in the background, such that the user can’t see or access them. These are the
tasks that don’t need the user to know them.
Bound Services

 Bound service runs as long as some other application component is bound to it. Many
components can bind to one service at a time, but once they all unbind, the service will destroy.

 To bind an application component to the service, bindService() is used.


ANDROID SERVICES LIFECYCLE
Android services life-cycle can have two forms of services and they follow two paths, that are:

1. Started Service

2. Bounded Service
STARTED SERVICE
 A service is Started when an application component, such as an activity calls startService() method. Once it
started, it will run indefinitely in background even if the component that started is destroyed.

 We can stop the Started service by using stopService() method or the service can stop itself by calling
stopSelf() method. In android, the Started service component will perform a single operation and it won’t
return any result to the caller.
BOUND SERVICE
 A service is Bound when another application component calls bindService() method. The bound service runs
as long as another application component is bound to it.

 We can unbind the service by calling unbindService() method based on our requirements. In android, we can
bind multiple components to a single service at once, but the service will be destroyed in case all the
components unbind.
BROADCASTS
Broadcasts are messages that the android system and android apps send when events occur that might affect the
functionality of other apps. Broadcasts have two types such as:

• System broadcasts are delivered by the system and are wrapped in Intent objects

• Custom broadcasts are delivered by your app.


Custom broadcasts are delivered in three ways

 For a normal broadcast, pass the intent to sendBroadcast().

 For an ordered broadcast, pass the intent to sendOrderedBroadcast().

 For a local broadcast, pass the intent to LocalBroadcastManager.sendBroadcast()


SAMPLE EXAMPLES FOR CUSTOM BROADCASTS
1. public void sendBroadcast() {

Intent intent = new Intent();

intent.setAction("com.example.myproject.ACTION_SHOW_TOAST");

// Set the optional additional information in extra field.

intent.putExtra("data","This is a normal broadcast");

sendBroadcast(intent);

}
2. public void sendOrderedBroadcast() {

Intent intent = new Intent();

// Set a unique action string prefixed by your app package name.

intent.setAction("com.example.myproject.ACTION_NOTIFY");

// Deliver the Intent.

sendOrderedBroadcast(intent);

3.LocalBroadcastManager.getInstance(this).sendBroadcast(customBroadcastIntent);
BROADCAST RECEIVER
 A broadcast receiver is an android component which allows you to register for system or application events. 

 Broadcast Receivers can send or receive messages from other applications or from the system itself. These
messages can be events or intents
METHODS TO RECEIVE/REGISTER A BROADCAST
STATICALLY (MANIFEST-DECLARED)
This receiver can be registered via the AndroidManifest.xml file as shown in the below code:
<receiver android:name=".MyBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE""/>
</intent-filter>
</receiver>
Then create class as a subclass of BroadcastReceiver class 
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
Dynamically (context-registered)

 This registers a receiver dynamically via the Context.registerReceiver() method.

Sample code on how it is used programmatically:

IntentFilter intentFilter = new IntentFilter();


intentFilter.addAction(getPackageName() + "android.net.conn.CONNECTIVITY_CHANGE");
MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();
registerReceiver(myReceiver, filter);
 To unregister a broadcast receiver in onStop() or onPause() of the activity.

@Override protected void onPause() {

unregisterReceiver(myReceiver);

super.onPause(); }
USEFUL WEBSITES FOR SELF STUDY
 Abhi Android
 Techotopia
 Android Developers
 Android|Tutlane

You might also like