Mobile Application Development Activities, Services, Broadcast, Etc
Mobile Application Development Activities, Services, Broadcast, Etc
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.
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 .
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
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
onResume() — the activity starts interacting with the user
onPause() — the current activity is being paused and the previous activity is being resumed
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
*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.
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.
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:
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, 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
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
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
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:
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.
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.
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
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:
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.
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.
ACTION_HEADSET_PLUG broadcast receiver A headset has been plugged into the device, or
unplugged from it.
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
• 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
CATEGORY TEST
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>
</intent-filter>
</activity>
ANDROID SERVICES
INTRODUCTION
Android Services are the application components that run in the background
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.
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
intent.setAction("com.example.myproject.ACTION_SHOW_TOAST");
sendBroadcast(intent);
}
2. public void sendOrderedBroadcast() {
intent.setAction("com.example.myproject.ACTION_NOTIFY");
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)
unregisterReceiver(myReceiver);
super.onPause(); }
USEFUL WEBSITES FOR SELF STUDY
Abhi Android
Techotopia
Android Developers
Android|Tutlane