0% found this document useful (0 votes)
121 views57 pages

Mad Chapter - 5 Notes

The document discusses the Android activity lifecycle and how it is controlled by 7 methods in the android.app.Activity class. It describes each of the 7 lifecycle methods and provides code examples to call them. It also discusses how to use intents to start new activities and services and how there are explicit and implicit intents.

Uploaded by

batepranay879
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views57 pages

Mad Chapter - 5 Notes

The document discusses the Android activity lifecycle and how it is controlled by 7 methods in the android.app.Activity class. It describes each of the 7 lifecycle methods and provides code examples to call them. It also discusses how to use intents to start new activities and services and how there are explicit and implicit intents.

Uploaded by

batepranay879
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Chapter -5 Activity and Multimedia with Databases

Android Activity Lifecycle

Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class.


The android Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.

By the help of activity, you can place all your UI components or widgets in a single
screen.

The 7 lifecycle method of Activity describes how activity will behave at different
states.

Android Activity Lifecycle methods


Let's see the 7 lifecycle methods of android activity.

Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.
onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.


activity_main.xml

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


<android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.activitylifecycle.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.java

package example.javatpoint.com.activitylifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}

Output:

You will not see any output on the emulator or device. You need to open logcat.
Now see on the logcat: onCreate, onStart and onResume methods are invoked.

Now click on the HOME Button. You will see onPause method is invoked.
After a while, you will see onStop method is invoked.

Now see on the emulator. It is on the home. Now click on the center button to
launch the app again.

Now click on the lifecycleactivity icon.


Now see on the logcat: onRestart, onStart and onResume methods are invoked.

If you see the emulator, application is started again.


Now click on the back button. Now you will see onPause methods is invoked.

After a while, you will see onStop and onDestroy methods are invoked.

The onCreate() and onDestroy() methods are called only once throughout the activity
lifecycle.

Intents in Android
Have you ever wondered how a new Activity opens when we click
on some button, suppose the settings button to show the Settings
screen in any app? How does the app opens up when we click on its
notification? How do we get Low battery alert in our mobile? All
these things are possible because of Intent in Android.

An Intent is a messaging object that you can use to request an


action from an app component. An Intent is basically an intention to
do an action. It's a way to communicate between Android
components to request an action from a component, by different
components.

It's like a message that Android listens for and then react
accordingly by identifying and invoking the app's appropriate
component (like an Activity, Service, Content Provider, etc.). It can
be within that same app or some other app as well.

If multiple apps are capable of responding to the message then


Android provides the user with a list of those apps from which a
choice can be made.

Uses of Intent in Android

There are three fundamental uses of intents:

1. To start an Activity

An Activity represents a single screen in an app. You can start a new


instance of an Activity by passing an Intent to startActivity(). The
Intent describes the activity to start and carries any necessary data
along.

2. To start a Service

A Service is a component that performs operations in the


background and does not have a user interface. You can start a
service to perform a one-time operation(such as downloading a file)
by passing an Intent to startService(). The Intent describes which
service to start and carries any necessary data.

3. To deliver a Broadcast

A broadcast is a message that any app can receive. The system


delivers various broadcasts for system events, such as when the
system boots up or the device starts charging. You can deliver a
broadcast to other apps by passing an Intent
to sendBroadcast() or sendOrderedBroadcast().
Types of Intents

In Android, there are two types of Intents:

1. Explicit Intents

2. Implicit Intents

Explicit Intents

When you explicitly define which Android component should be


opened on some user action, then you use explicit intents. You
generally use an explicit intent to start a new component in your
own app, because you know which exact activity or service you want
to start. For example, you can start a new activity in response to a
user action or start a service to download a file in the background.

Create an Explicit Intent

To create an explicit intent,

1. 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.

Note: You need to mention the java file name


with .class extension

Intent i = new Intent(this,


MyJavaFile.class);

2. 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);

3. 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.
4. i.putExtra("key1", "I am value1");

5. i.putExtra("key2", "I am value2");

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 a = getIntent().getStringExtra("key1");

Doing this, stores the value stored at key1 into the string
variable a.

Implicit Intent

When you just have to tell what action you want to perform without
worrying which component will perform it, then you can use 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.
For example, if you want to show a specific location of the user on a
map, you can use an implicit intent to pass the coordinates through
the intent and then any other app, which is capable of showing the
coordinates on a map will accept that intent.

Create an Implicit Intent

To create an implicit intent,

1. 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);

2. 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("http://
www.google.co.in"));

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


the parameter.

startActivity(i);

URI
Uniform Resource Identifier (URI) is a string of characters used to identify a
resource. A URI identifies a resource either by location, or a name, or both. Such
identification enables interaction with representations of the resource over a network,
typically the World Wide Web, using specific protocols.
Intent Filters
 You have seen how an Intent has been used to call an another activity. Android OS uses
filters 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
Intent. You will use <intent-filter> element in the manifest file to list down actions,
categories and data types associated with any activity, service, or broadcast receiver.
 Following is an example of a part of AndroidManifest.xml file to specify an
activity com.example.MyApplication.CustomActivity which can be invoked by either of
the two mentioned actions, one category, and one data –

<activity android:name=".CustomActivity"
android:label="@string/app_name">

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.example.My Application.LAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>

</activity>
 Once this activity is defined along with above mentioned filters, other activities will be
able to invoke this activity using either the android.intent.action.VIEW, or using
the com.example.MyApplication.LAUNCH action provided their category
is android.intent.category.DEFAULT.
 The <data> element specifies the data type expected by the activity to be called and for
above example our custom activity expects the data to start with the "http://"
 There may be a situation that an intent can pass through the filters of more than one
activity or service, the user may be asked which component to activate. An exception is
raised if no target can be found.
There are following test Android checks before invoking an activity −
 A filter <intent-filter> may list more than one action as shown above but this list cannot
be empty; a filter must contain at least one <action> element, otherwise it will block all
intents. If more than one actions are mentioned then Android tries to match one of the
mentioned actions before invoking the activity.
 A filter <intent-filter> may list zero, one or more than one categories. if there is no
category mentioned then Android always pass this test but if more than one categories
are mentioned then for an intent to pass the category test, every category in the Intent
object must match a category in the filter.
 Each <data> element can specify a URI and a data type (MIME media type). There are
separate attributes like scheme, host, port, and path for each part of the URI. An Intent
object that contains both a URI and a data type passes the data type part of the test
only if its type matches a type listed in the filter.

Broadcast Receiver
 Broadcast Receivers simply respond to broadcast messages from other applications or
from the system itself. These messages are sometime called events or intents. For
example, applications can also initiate broadcasts to let other applications know that
some data has been downloaded to the device and is available for them to use, so this
is broadcast receiver who will intercept this communication and will initiate appropriate
action.
 There are following two important steps to make BroadcastReceiver works for the
system broadcasted intents −
Creating the Broadcast Receiver.
Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents
then you will have to create and broadcast those intents.

Creating the Broadcast Receiver


A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding
the onReceive() method where each message is received as a Intent object parameter.

public class MyReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.",
Toast.LENGTH_LONG).show();
}
}

Registering Broadcast Receiver


An application listens for specific broadcast intents by registering a broadcast receiver
in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated
event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has
completed the boot process.

Broadcast-Receiver

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">

<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>

</receiver>
</application>
Now whenever your Android device gets booted, it will be intercepted by
BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be executed.
There are several system generated events defined as final static fields in the Intent class. The
following table lists a few important system events.

Sr.No Event Constant & Description

android.intent.action.BATTERY_CHANGED
1
Sticky broadcast containing the charging state, level, and other information about the
battery.

android.intent.action.BATTERY_LOW
2
Indicates low battery condition on the device.

android.intent.action.BATTERY_OKAY
3
Indicates the battery is now okay after being low.

android.intent.action.BOOT_COMPLETED
4
This is broadcast once, after the system has finished booting.

android.intent.action.BUG_REPORT
5
Show activity for reporting a bug.

android.intent.action.CALL
6
Perform a call to someone specified by the data.

android.intent.action.CALL_BUTTON
7 The user pressed the "call" button to go to the dialer or other appropriate UI for placing a
call.

android.intent.action.DATE_CHANGED
8
The date has changed.
android.intent.action.REBOOT
9
Have the device reboot.

Content Providers

A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. A content provider can use
different ways to store its data and the data can be stored in a database, in files, or even over a
network.
ContentProvider

sometimes it is required to share data across applications. This is where content


providers become very useful.

Content providers let you centralize content in one place and have many different applications
access it as needed. A content provider behaves very much like a database where you can
query it, edit its content, as well as add or delete content using insert(), update(), delete(), and
query() methods. In most cases this data is stored in an SQlite database.
A content provider is implemented as a subclass of ContentProvider class and must implement
a standard set of APIs that enable other applications to perform transactions.

public class MyApplication extends ContentProvider {


}

Content URIs
To query a content provider, you specify the query string in the form of a URI which has
following format −

<prefix>://<authority>/<data_type>/<id>
Here is the detail of various parts of the URI −

Sr.No Part & Description

1 prefix
This is always set to content://

2
authority
This specifies the name of the content provider, for example contacts, browser etc. For third-
party content providers, this could be the fully qualified name, such
as com.tutorialspoint.statusprovider

data_type
3 This indicates the type of data that this particular provider provides. For example, if you are
getting all the contacts from the Contacts content provider, then the data path would
be people and URI would look like thiscontent://contacts/people

id
4 This specifies the specific record requested. For example, if you are looking for contact
number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.

Create Content Provider


This involves number of simple steps to create your own content provider.
 First of all you need to create a Content Provider class that extends
the ContentProviderbaseclass.
 Second, you need to define your content provider URI address which will be used to
access the content.
 Next you will need to create your own database to keep the content. Usually, Android
uses SQLite database and framework needs to override onCreate() method which will
use SQLite Open Helper method to create or open the provider's database. When your
application is launched, the onCreate() handler of each of its Content Providers is called
on the main application thread.
 Next you will have to implement Content Provider queries to perform different database
specific operations.
 Finally register your Content Provider in your activity file using <provider> tag.
Here is the list of methods which you need to override in Content Provider class to have your
Content Provider working −
ContentProvider
 onCreate() This method is called when the provider is started.
 query() This method receives a request from a client. The result is returned as a Cursor
object.
 insert()This method inserts a new record into the content provider.
 delete() This method deletes an existing record from the content provider.
 update() This method updates an existing record from the content provider.
 getType() This method returns the MIME type of the data at the given URI.

Fragments
A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.

Following are important points about fragment −


 A fragment has its own layout and its own behaviour with its own life cycle callbacks.
 You can add or remove fragments in an activity while the activity is running.
 You can combine multiple fragments in a single activity to build a multi-pane UI.
 A fragment can be used in multiple activities.
 A fragment can implement a behaviour that has no user interface component.
 Fragments were added to the Android API in Honeycomb version of Android which API
version 11.
You create fragments by extending Fragment class and You can insert a fragment into your
activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.
Prior to fragment introduction, we had a limitation because we can show only a single activity on
the screen at one given point in time. So we were not able to divide device screen and control
different parts separately. But with the introduction of fragment we got more flexibility and
removed the limitation of having a single activity on the screen at a time. Now we can have a
single activity but each activity can comprise of multiple fragments which will have their own
layout, events and complete life cycle.
Following is a typical example of how two UI modules defined by fragments can be combined
into one activity for a tablet design, but separated for a handset design.
The application can embed two fragments in Activity A, when running on a tablet-sized device.
However, on a handset-sized screen, there's not enough room for both fragments, so Activity A
includes only the fragment for the list of articles, and when the user selects an article, it starts
Activity B, which includes the second fragment to read the article.

How to use Fragments?


This involves number of simple steps to create Fragments.
 First of all decide how many fragments you want to use in an activity. For example let's
we want to use two fragments to handle landscape and portrait modes of the device.
 Next based on number of fragments, create classes which will extend
the Fragment class. The Fragment class has above mentioned callback functions. You
can override any of the functions based on your requirements.
 Corresponding to each fragment, you will need to create layout files in XML file. These
files will have layout for the defined fragments.
 Finally modify activity file to define the actual logic of replacing fragments based on your
requirement.

Types of Fragments
Basically fragments are divided as three stages as shown below.
 Single frame fragments − Single frame fragments are using for hand hold devices like
mobiles, here we can show only one fragment as a view.
 List fragments − fragments having special list view is called as list fragment
 Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment.

This example demonstrate about Fragment Tutorial with Example in Android


Studio
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill
all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.

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


<LinearLayout xmlns:android =
"http://schemas.android.com/apk/res/android"

xmlns:app = "http://schemas.android.com/apk/res-auto"

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

android:layout_width = "match_parent"

android:layout_height = "match_parent"

tools:context = ".MainActivity"

android:orientation = "vertical">

<Button

android:id = "@+id/fragment1"

android:layout_width = "wrap_content"

android:layout_height = "wrap_content"

android:layout_alignParentTop = "true"

android:layout_centerHorizontal = "true"

android:layout_marginTop = "27dp"

android:text = "fragment1"/>

<Button

android:id = "@+id/fragment2"

android:layout_width = "wrap_content"

android:layout_height = "wrap_content"

android:layout_alignParentTop = "true"

android:layout_centerHorizontal = "true"

android:layout_marginTop = "27dp"

android:text = "fragment2"/>

<LinearLayout

android:id = "@+id/layout"

android:layout_width = "wrap_content"

android:layout_height = "wrap_content"

android:orientation = "vertical">
</LinearLayout>

</LinearLayout>

In the above code, we have taken button views and linear layout to show different
fragments.
Step 3 − Add the following code to src /MainActivity.java

package com.example.myapplication;

import android.os.Build;

import android.os.Bundle;

import android.support.annotation.RequiresApi;

import android.support.v4.app.FragmentManager;

import android.support.v4.app.FragmentTransaction;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

public class MainActivity extends AppCompatActivity {

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

final android.support.v4.app.Fragment first = new


FirstFragment();

final android.support.v4.app.Fragment second = new


SecondFragment();

findViewById(R.id.fragment1).setOnClickListener(new
View.OnClickListener() {

@Override

public void onClick(View v) {

android.support.v4.app.FragmentManager fm =
getSupportFragmentManager();
android.support.v4.app.FragmentTransaction
fragmentTransaction = fm.beginTransaction();

fragmentTransaction.replace(R.id.layout, first);

fragmentTransaction.commit();

});

findViewById(R.id.fragment2).setOnClickListener(new
View.OnClickListener() {

@Override

public void onClick(View v) {

FragmentManager fm = getSupportFragmentManager();

FragmentTransaction fragmentTransaction =
fm.beginTransaction();

fragmentTransaction.replace(R.id.layout, second);

fragmentTransaction.commit();

});

Step 4 − Add the following code to src / FirstFragment.java

package com.example.myapplication;

import android.annotation.SuppressLint;

import android.os.Bundle;

import android.support.annotation.NonNull;

import android.support.annotation.Nullable;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("ValidFragment")

public class FirstFragment extends Fragment {

TextView textView;

@Nullable

@Override

public View onCreateView(@NonNull LayoutInflater inflater,


@Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {

View view = inflater.inflate(R.layout.fragment,


container, false);

textView = view.findViewById(R.id.text);

textView.setText("first");

return view;

Step 5 − Add the following code to src / SecondFragment.java

package com.example.myapplication;

import android.annotation.SuppressLint;

import android.os.Bundle;

import android.support.annotation.NonNull;

import android.support.annotation.Nullable;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.TextView;
public class SecondFragment extends Fragment {

TextView textView;

@Nullable

@Override

public View onCreateView(@NonNull LayoutInflater inflater,


@Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {

View view = inflater.inflate(R.layout.fragment,


container, false);

textView = view.findViewById(R.id.text);

textView.setText("Second");

return view;

Step 6 − Add the following code to res/layout/ fragment.xml.

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

<LinearLayout

xmlns:android =
"http://schemas.android.com/apk/res/android"

android:layout_width = "match_parent"

android:gravity = "center"

android:layout_height = "match_parent">

<TextView

android:id = "@+id/text"

android:textSize = "30sp"

android:layout_width = "match_parent"

android:layout_height = "match_parent" />

</LinearLayout>

Let's try to run your application. I assume you have connected your actual
Android Mobile device with your computer. To run the app from android studio,
open one of your project's activity files and click Run icon from the toolbar.
Select your mobile device as an option and then check your mobile device which
will display your default screen –

Now click on buttons, it will show the result as shown below –


Services

A service is a component that runs in the background to perform long-running operations without
needing to interact with the user and it works even if application is destroyed. A service can
essentially take two states –

Sr.No. State & Description

1
Started
A service is started when an application component, such as an activity, starts it by
calling startService(). Once started, a service can run in the background indefinitely, even if
the component that started it is destroyed.

2
Bound
A service is bound when an application component binds to it by calling bindService(). A
bound service offers a client-server interface that allows components to interact with the
service, send requests, get results, and even do so across processes with interprocess
communication (IPC).

A service has life cycle callback methods that you can implement to monitor changes in the
service's state and you can perform work at the appropriate stage. The following diagram on the
left shows the life cycle when the service is created with startService() and the diagram on the
right shows the life cycle when the service is created with bindService(): (image courtesy :
android.com )

To create an service, you create a Java class that extends the Service base class or one of its
existing subclasses. The Service base class defines various callback methods and the most
important are given below. You don't need to implement all the callbacks methods. However, it's
important that you understand each one and implement those that ensure your app behaves the
way users expect.

Sr.No Callback & Description


.
1
onStartCommand()
The system calls this method when another component, such as an activity, requests that the
service be started, by calling startService(). If you implement this method, it is your
responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.

2
onBind()
The system calls this method when another component wants to bind with the service by
calling bindService(). If you implement this method, you must provide an interface that clients
use to communicate with the service, by returning an IBinder object. You must always
implement this method, but if you don't want to allow binding, then you should return null.

3
onUnbind()
The system calls this method when all clients have disconnected from a particular interface
published by the service.

4
onRebind()
The system calls this method when new clients have connected to the service, after it had
previously been notified that all had disconnected in its onUnbind(Intent).

5
onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind(). This call is required to perform one-time set-up.

6
onDestroy()
The system calls this method when the service is no longer used and is being destroyed.
Your service should implement this to clean up any resources such as threads, registered
listeners, receivers, etc.

Discuss the need of permissions in Android. Describe the permissions to set system
functionalities like bluetooth,camera.

Need of permissions in Android


1. The purpose of a permission is to protect the privacy of an Android user.
2. Android apps must request permission to access sensitive user data (such as contacts and
SMS), as well as certain system features (such as camera and internet).
3. Depending on the feature, the system might grant the permission automatically or might
prompt the user to approve the request.
4. A central design point of the Android security architecture is that no app, by default, has
permission to perform any operations that would adversely impact other apps, the operating
system, or the user.
5. This includes reading or writing the user's private data (such as contacts or emails), reading or
writing another app's files, performing network access, keeping the device awake, and so on.
6. An user must publicize the permissions it requires by including <uses-permission> tags in
the app manifest.

7. For example, an app that needs to send SMS messages would have this line in the manifest :
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">

<uses-permission android:name="android.permission.SEND_SMS"/>

<application ...>
...
</application>
</manifest>
8. app that needs to allow phone call would have this line in the manifest:

<uses-permission android:name="android.permission.CALL_PHONE" />

9. app that needs to allow bluetooth would have this line in the manifest:

<uses-permission android:name="android.permission.BLUETOOTH" />


<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

10. app that needs to allow use of camera would have this line in the manifest:

<uses-permission android:name="android.permission.CAMERA" />

11. app that needs to allow use of wifi would have this line in the manifest:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

12. app that needs to allow use of Simple Caller Talker would have this line in the manifest:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

13. app that needs to allow use of Google maps for location would have this line in the manifest:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Android multimedia framework


The Android multimedia framework includes support for playing variety of common media
types, so that you can easily integrate audio, video and images into your applications. You
can play audio or video from media files stored in your application's resources (raw
resources), from standalone files in the filesystem, or from a data stream arriving over a
network connection, all using MediaPlayer APIs.

The following classes are used to play sound and video in the Android framework:

MediaPlayer

This class is the primary API for playing sound and video.

AudioManager

This class manages audio sources and audio output on a device.

Manifest declarations
Before starting development on your application using MediaPlayer, make sure your
manifest has the appropriate declarations to allow use of related features.

 Internet Permission - If you are using MediaPlayer to stream network-based content, your
application must request network access.

<uses-permission android:name="android.permission.INTERNET" />

 Wake Lock Permission - If your player application needs to keep the screen from dimming or
the processor from sleeping, or uses
the MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode()
methods, you must request this permission.

<uses-permission android:name="android.permission.WAKE_LOCK" />

Using MediaPlayer
One of the most important components of the media framework is the MediaPlayer class. An
object of this class can fetch, decode, and play both audio and video with minimal setup. It
supports several different media sources such as:

 Local resources
 Internal URIs, such as one you might obtain from a Content Resolver
 External URLs (streaming)
For a list of media formats that Android supports, see the Supported Media Formats page.
Here is an example of how to play audio that's available as a local raw resource (saved in your
application's res/raw/ directory):
MediaPlayer mediaPlayer = MediaPlayer.create(context,
R.raw.sound_file_1);
mediaPlayer.start(); // no need to call prepare(); create() does that
for you

In this case, a "raw" resource is a file that the system does not try to parse in any particular way.
However, the content of this resource should not be raw audio. It should be a properly encoded
and formatted media file in one of the supported formats.
And here is how you might play from a URI available locally in the system (that you obtained
through a Content Resolver, for instance):

Uri myUri = ....; // initialize Uri here


MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();

Playing from a remote URL via HTTP streaming looks like this:

String url = "http://........"; // your URL here


MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();

Android Media Player


Android provides many ways to control playback of audio/video files and streams. One of this
way is through a class called MediaPlayer.
Android is providing MediaPlayer class to access built-in mediaplayer services like playing
audio,video e.t.c. In order to use MediaPlayer, we have to call a static Method create() of this
class. This method returns an instance of MediaPlayer class. Its syntax is as follows −
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

The second parameter is the name of the song that you want to play. You have to make a new
folder under your project with name raw and place the music file into it.
Once you have created the Mediaplayer object you can call some methods to start or stop the
music. These methods are listed below.

mediaPlayer.start();
mediaPlayer.pause();
On call to start() method, the music will start playing from the beginning. If this method is called
again after the pause() method, the music would start playing from where it is left and not from
the beginning.
In order to start music from the beginning, you have to call reset() method. Its syntax is given
below.
mediaPlayer.reset();

Apart from the start and pause method, there are other methods provided by this class for better
dealing with audio/video files. These methods are listed below −

Sr.No Method & description

1
isPlaying()
This method just returns true/false indicating the song is playing or not

2
seekTo(position)
This method takes an integer, and move song to that particular position millisecond

3
getCurrentPosition()
This method returns the current position of song in milliseconds

4
getDuration()
This method returns the total time duration of song in milliseconds

5
reset()
This method resets the media player

6
release()
This method releases any resource attached with MediaPlayer object

7
setVolume(float leftVolume, float rightVolume)
This method sets the up down volume for this player

8
setDataSource(FileDescriptor fd)
This method sets the data source of audio/video file

9
selectTrack(int index)
This method takes an integer, and select the track from the list on that particular index

10
getTrackInfo()
This method returns an array of track information

Android Media Player Example for Audio


Android MediaPlayer Example of controlling the audio

activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:text="Audio Controller" />

<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="48dp"
android:text="start" />

<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="pause" />

<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button2"
android:layout_toRightOf="@+id/button2"
android:text="stop" />

</RelativeLayout>

MainActivity.java
package com.example.audioplay;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {


Button start,pause,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

start=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);
stop=(Button)findViewById(R.id.button3);
//creating media player
final MediaPlayer mp=new MediaPlayer();
try{
//you can change the path, here path is external directory(e.g. sdcard)
/Music/maine.mp3
mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/
maine.mp3");

mp.prepare();
}catch(Exception e){e.printStackTrace();}

start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
}
});
}
}
Output:

Android Video Player Example


By the help of MediaController and VideoView classes, we can play the video files in android.

MediaController class

The android.widget.MediaController is a view that contains media controls like play/pause,


previous, next, fast-forward, rewind etc.

VideoView class

The android.widget.VideoView class provides methods to play and control the video player. The
commonly used methods of VideoView class are as follows:

Method Description

public void sets the media controller to the video


setMediaController(MediaController view.
controller)

public void setVideoURI (Uri uri) sets the URI of the video file.

public void start() starts the video view.

public void stopPlayback() stops the playback.

public void pause() pauses the playback.


public void suspend() suspends the playback.

public void resume() resumes the playback.

public void seekTo(int millis) seeks to specified time in miliseconds.

activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<VideoView
android:id="@+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />

</RelativeLayout>

MainActivity.java
package com.example.video1;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

VideoView videoView =(VideoView)findViewById(R.id.videoView1);

//Creating MediaController
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);

//specify the location of media file


Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/media/1.mp4");
//Setting MediaController and URI, then starting the videoView
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

TextToSpeech
Android allows you convert your text into voice. Not only you can convert it but it also allows you
to speak text in variety of different languages.

Android provides TextToSpeech class for this purpose. In order to use this class, you need to
instantiate an object of this class and also specify the initListener. Its syntax is given below −

private EditText write;


ttobj=new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
}
});

In this listener, you have to specify the properties for TextToSpeech object , such as its language
,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given below −

ttobj.setLanguage(Locale.UK);
The method setLanguage takes an Locale object as parameter. The list of some of the locales
available are given below −

Sr.No Locale

1 US

2 CANADA_FRENCH

3 GERMANY
4 ITALY

5 JAPAN

6 CHINA

Once you have set the language, you can call speak method of the class to speak the text. Its
syntax is given below −

ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);

Sensors
Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device.
Android provides sensor api to work with different types of sensors.

Types of Sensors
Android supports three types of sensors:
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
2) Position Sensors
These are used to measure the physical position of device.
3) Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity etc.

Android Sensor API


Android sensor api provides many classes and interface. The important classes and interfaces of
sensor api are as follows:
1) SensorManager class
The android.hardware.SensorManager class provides methods :

to get sensor instance,


to access and list sensors,
to register and unregister sensor listeners etc.
You can get the instance of SensorManager by calling the method getSystemService() and
passing the SENSOR_SERVICE constant in it.
SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
2) Sensor class
The android.hardware.Sensor class provides methods to get information of the sensor such as
sensor name, sensor type, sensor resolution, sensor type etc.
3) SensorEvent class
Its instance is created by the system. It provides information about the sensor.
4) SensorEventListener interface
It provides two call back methods to get information when sensor values (x,y and z) change or
sensor accuracy changes.

Public and abstract methods Description

void onAccuracyChanged(Sensor sensor, it is called when sensor


int accuracy) accuracy is changed.

void onSensorChanged(SensorEvent it is called when sensor


event) values are changed.

Android simple sensor app example


A sensor example that prints x, y and z axis values. Here, we are going to see that.

activity_main.xml

There is only one textview in this file.

activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="114dp"
android:text="TextView" />

</RelativeLayout>

Activity class

Let's write the code that prints values of x axis, y axis and z axis.

MainActivity.java

package com.example.sensorsimple;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import java.util.List;
public class MainActivity extends Activity {
SensorManager sm = null;
TextView textView1 = null;
List list;

SensorEventListener sel = new SensorEventListener(){


public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
textView1.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/* Get a SensorManager instance */


sm = (SensorManager)getSystemService(SENSOR_SERVICE);

textView1 = (TextView)findViewById(R.id.textView1);

list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(list.size()>0){
sm.registerListener(sel, (Sensor) list.get(0), SensorManager.SENSOR_DELAY_N
ORMAL);
}else{
Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENGTH_
LONG).show();
}
}

@Override
protected void onStop() {
if(list.size()>0){
sm.unregisterListener(sel);
}
super.onStop();
}
}

Output:
Android Camera
These are the following two ways, in which you can use camera in your application
 Using existing android camera application in our application
 Directly using Camera API provided by android in our application

Using existing android camera application in our


application

You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera


application installed on your phone. Its syntax is given below
Intent intent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

Apart from the above, there are other available Intents provided by MediaStore. They are listed
as follows

Sr.No Intent type and description

1 ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured

2
ACTION_VIDEO_CAPTURE
It calls the existing video application in android to capture video

EXTRA_SCREEN_ORIENTATION
3
It is used to set the orientation of the screen to vertical or landscape

EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage

INTENT_ACTION_VIDEO_CAMERA
5
This intent is used to launch the camera in the video mode

EXTRA_SIZE_LIMIT
6
It is used to specify the size limit of video or image capture size

Now you will use the function startActivityForResult() to launch this activity and wait for its
result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity. There
are methods defined in the activity class that does the same job , but used when you are not
calling from the activity but from somewhere else. They are listed below

Sr.No Activity function description

1 startActivityForResult(Intent intent, int requestCode, Bundle options)


It starts an activity , but can take extra bundle of options with it

startActivityFromChild(Activity child, Intent intent, int requestCode)


2
It launch the activity when your activity is child of any other activity

startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options)


3
It work same as above , but it can take extra values in the shape of bundle with it

startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)


4
It launches activity from the fragment you are currently inside
startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle
5 options)
It not only launches the activity from the fragment , but can take extra values with it

Bluetooth
Bluetooth is a way to send or receive data between two different devices. Android platform
includes support for the Bluetooth framework that allows a device to wirelessly exchange data
with other Bluetooth devices.
Android provides Bluetooth API to perform these different operations.
 Scan for other Bluetooth devices
 Get a list of paired devices
 Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of
this calling by calling the static method getDefaultAdapter(). Its syntax is given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth
constant ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Apart from this constant, there are other constants provided the API , that supports different
tasks. They are listed below.

Sr.No Constant & description

1 ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth

ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed

ACTION_FOUND
3
This constant is used for receiving information about each device that is discovered

Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Apart form the parried Devices , there are other methods in the API that gives more control over
Blueetooth. They are listed below.

Sr.No Method & description

1 enable()
This method enables the adapter if not enabled

isEnabled()
2
This method returns true if adapter is enabled

disable()
3
This method disables the adapter

getName()
4
This method returns the name of the Bluetooth adapter

setName(String name)
5
This method changes the Bluetooth name

getState()
6
This method returns the current state of the Bluetooth Adapter.

startDiscovery()
7
This method starts the discovery process of the Bluetooth for 120 seconds.

SQLite Database
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes
in with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't
need to establish any kind of connections for it like JDBC,ODBC e.t.c

Database - Package
The main package is android.database.sqlite that contains the classes to manage your own
databases

Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. It returns an instance of SQLite database which you
have to receive in your own object.Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
Apart from this , there are other functions available in the database package , that does this job.
They are listed below

Sr.N Method & Description


o

1
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,
DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode. The common flags
mode could be OPEN_READWRITE OPEN_READONLY

2
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
It is similar to the above method as it also opens the existing database but it does not define any
handler to handle the errors of databases

3
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
It not only opens but create the database if it not exists. This method is equivalent to
openDatabase method.

4
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
This method is similar to above method but it takes the File object as a path rather then a string.
It is equivalent to file.getPath()

Database - Insertion
We can create table or insert data into table using execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS
TutorialsPoint(Username VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint
VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the
same job but take some additional parameter is given below

Sr.No Method & Description

1
execSQL(String sql, Object[] bindArgs)
This method not only insert data , but also used to update or modify already existing data in
database using bind arguments

Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to the
table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from
TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the
data. That includes

Sr.No Method & Description

1
getColumnCount()
This method return the total number of columns of the table.

2
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column

3
getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column

4
getColumnNames()
This method returns the array of all the column names of the table.

5
getCount()
This method returns the total number of rows in the cursor
6
getPosition()
This method returns the current position of the cursor in the table

7
isClosed()
This method returns true if the cursor is closed and return false otherwise

Database - Helper class


For managing all the operations related to the database , an helper class has been given and is
called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its
syntax is given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {}
}

Android AsyncTask
Android AsyncTask going to do background operation on background thread and
update on main thread. In android we cannot directly touch background thread to
main thread in android development. asynctask help us to make communication
between background thread to main thread.

Methods of AsyncTask
 onPreExecute() − Before doing background operation we should show
something on screen like progressbar or any animation to user. we can
directly comminicate background operation using on doInBackground() but for
the best practice, we should call all asyncTask methods .
 doInBackground(Params) − In this method we have to do background
operation on background thread. Operations in this method should not touch
on any mainthread activities or fragments.
 onProgressUpdate(Progress…) − While doing background operation, if you
want to update some information on UI, we can use this method.
 onPostExecute(Result) − In this method we can update ui of background
operation result.

Generic Types in Async Task


 TypeOfVarArgParams − It contains information about what type of params
used for execution.
 ProgressValue − It contains information about progress units. While doing
background operation we can update information on ui using
onProgressUpdate().
 ResultValue −It contains information about result type.
This example demonstrate about how to use asyncTask in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all
required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.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/rootview"

android:layout_width = "match_parent"

android:layout_height = "match_parent"

android:orientation = "vertical"

android:background = "#c1c1c1"

android:gravity = "center_horizontal"

tools:context = ".MainActivity">

<Button

android:id = "@+id/asyncTask"

android:text = "Download"

android:layout_width = "wrap_content"

android:layout_height = "wrap_content" />

<ImageView

android:id = "@+id/image"

android:layout_width = "300dp"

android:layout_height = "300dp" />

</LinearLayout>
In the above xml we have created a button, when user click on the button it going to
download image and append image to imageview.
Step 3 − Add the following code to src/MainActivity.java

package com.example.andy.myapplication;

import android.app.ProgressDialog;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.AsyncTask;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

public class MainActivity extends AppCompatActivity {

URL ImageUrl = null;

InputStream is = null;

Bitmap bmImg = null;

ImageView imageView= null;

ProgressDialog p;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button button=findViewById(R.id.asyncTask);

imageView=findViewById(R.id.image);
button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

AsyncTaskExample asyncTask=new AsyncTaskExample();

asyncTask.execute("https://www.tutorialspoint.com/images/tp-logo-
diamond.png");

});

private class AsyncTaskExample extends AsyncTask<String,


String, Bitmap> {

@Override

protected void onPreExecute() {

super.onPreExecute();

p = new ProgressDialog(MainActivity.this);

p.setMessage("Please wait...It is downloading");

p.setIndeterminate(false);

p.setCancelable(false);

p.show();

@Override

protected Bitmap doInBackground(String... strings) {

try {

ImageUrl = new URL(strings[0]);

HttpURLConnection conn = (HttpURLConnection)


ImageUrl.openConnection();

conn.setDoInput(true);

conn.connect();

is = conn.getInputStream();
BitmapFactory.Options options = new
BitmapFactory.Options();

options.inPreferredConfig = Bitmap.Config.RGB_565;

bmImg = BitmapFactory.decodeStream(is, null,


options);

} catch (IOException e) {

e.printStackTrace();

return bmImg;

@Override

protected void onPostExecute(Bitmap bitmap) {

super.onPostExecute(bitmap);

if(imageView!=null) {

p.hide();

imageView.setImageBitmap(bitmap);

}else {

p.show();

In the above code we are downloading image using asyncTask and appending
image to imageview.
Step 4 − Add the following code to manifest.xml

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

<manifest xmlns:android =
"http://schemas.android.com/apk/res/android"

package = "com.example.andy.myapplication">
<uses-permission android:name =
"android.permission.INTERNET"/>

<application

android:allowBackup = "true"

android:icon = "@mipmap/ic_launcher"

android:label = "@string/app_name"

android:roundIcon = "@mipmap/ic_launcher_round"

android:supportsRtl = "true"

android:theme = "@style/AppTheme">

<activity android:name = ".MainActivity">

<intent-filter>

<action android:name = "android.intent.action.MAIN"


/>

<category android:name =
"android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>

In the above AndroidManifest.xml file we have added internet permission to access


internet to download image.
Let's try to run your application. I assume you have connected your actual Android
Mobile device with your computer. To run the app from android studio, open one of
your project's activity files and click Run Eclipse Run Icon icon from the toolbar.
Select your mobile device as an option and then check your mobile device which will
display your default screen.
Now click on download button it will show progress on UI and download image at
background as shown below

After downloading image, it will update on UI as shown below

You might also like