0% found this document useful (0 votes)
7 views32 pages

Chapter 5-Activity and Multimedia with Databases

Chapter 5 discusses the use of Intents and Fragments in Android applications. It explains the two types of Intents: Explicit and Implicit, detailing how to create and utilize them for inter-component communication. Additionally, it covers the concept of Fragments, their lifecycle, and their importance in creating modular and reusable UI components in Android apps.

Uploaded by

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

Chapter 5-Activity and Multimedia with Databases

Chapter 5 discusses the use of Intents and Fragments in Android applications. It explains the two types of Intents: Explicit and Implicit, detailing how to create and utilize them for inter-component communication. Additionally, it covers the concept of Fragments, their lifecycle, and their importance in creating modular and reusable UI components in Android apps.

Uploaded by

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

Chapter 5

Activity and Multimedia with Databases

 Intent:
“Android application components can connect to other Android
applications. This connection is based on a task description represented by
an Intent object.”
Intent is a messaging object you can use to request an action from another
app component.
Intent is a messaging object which passes between components like services,
content providers, activities etc. Normally startActivity() method is used for
invoking any activity.

Some of the general functions of intent are:


1. Start service
2. Launch activity

1
3. Display web page
4. Display contact list
5. Message broadcasting

Methods and its Description

METHODS DESCRIPTION

This is to launch a new activity or get an existing


Context.startActivity() activity to be action.

This is to start a new service or deliver instructions


Context.startService() for an existence service.

Context.sendBroadcast() This is to deliver the message to broadcast receivers.

Types of Intent:
There are following two types of intents supported by Android

1. Explicit Intents

2
Explicit intent going to be connected internal world of application, suppose if you
wants to connect one activity to another activity, we can do this quote by explicit
intent, below image is connecting first activity to second activity by clicking
button.

These intents designate the target component by its name and they are typically
used for application-internal messages - such as an activity starting a subordinate
service or launching a sister activity.

Create an Explicit Intent


To create an explicit intent,
Step 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.

3
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);

Step 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);

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

2. Implicit Intents
These intents do not name a target and the field for the component name is left
blank. Implicit intents are often used to activate components in other applications.

4
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,
Step 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);

5
Step 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"));

Step 3: Call startActivity() method in the end with the intent object as the
parameter.
startActivity(i);

 Intent filters
To inform the system which implicit intents they can handle, activities, services,
and broadcast receivers can have one or more intent filters. Each filter describes a
capability of the component, a set of intents that the component is willing to
receive. It, in effect, filters in intents of a desired type, while filtering out unwanted
intents — but only unwanted implicit intents (those that don't name a target class).
An explicit intent is always delivered to its target, no matter what it contains; the
filter is not consulted. But an implicit intent is delivered to a component only if it
can pass through one of the component's filters.

A component has separate filters for each job it can do, each face it can present to
the user. For example, the NoteEditor activity of the sample Note Pad application
has two filters — one for starting up with a specific note that the user can view or

6
edit, and another for starting with a new, blank note that the user can fill in and
save.

An intent filter is an instance of the IntentFilter class. However, since the Android
system must know about the capabilities of a component before it can launch that
component, intent filters are generally not set up in Java code, but in the
application's manifest file (AndroidManifest.xml) as <intent-filter> elements. (The
one exception would be filters for broadcast receivers that are registered
dynamically by calling Context.registerReceiver(); they are directly created as
IntentFilter objects.)

A filter has fields that parallel the action, data, and category fields of an Intent
object. An implicit intent is tested against the filter in all three areas. To be
delivered to the component that owns the filter, it must pass all three tests. If it fails
even one of them, the Android system won't deliver it to the component — at least
not on the basis of that filter. However, since a component can have multiple intent
filters, an intent that does not pass through one of a component's filters might make
it through on another.

Syntax:

<intent-filter android:icon="drawable resource"


android:label="string resource"
android:priority="integer" >
...
</intent-filter>

7
1.<action>

syntax:
<action android:name="string" />

contained in:
<intent-filter>

description:
Adds an action to an intent filter. An <intent-filter> element must contain
one or more <action> elements. If there are no <action> elements in an
intent filter, the filter doesn't accept any Intent objects.

2. <category>

syntax:
<category android:name="string" />

contained in:
<intent-filter>

description:

Adds a category name to an intent filter.

3. <data>

syntax:
<data android:scheme="string"
android:host="string"

8
android:port="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />

contained in:
<intent-filter>

description:
Adds a data specification to an intent filter. The specification can be just a
data type (the mimeType attribute), just a URI, or both a data type and a
URI. A URI is specified by separate attributes for each of its parts:
<scheme>://<host>:<port>[<path>|<pathPrefix>|<pathPattern>]
These attributes that specify the URL format are optional, but also mutually
dependent:
 If a scheme is not specified for the intent filter, all the other URI attributes
are ignored.
 If a host is not specified for the filter, the port attribute and all the path
attributes are ignored.
All the <data> elements contained within the same <intent-filter> element
contribute to the same filter. So, for example, the following filter
specification,

<intent-filter . . . >
<data android:scheme="something" android:host="project.example.com"
/>
...
</intent-filter>

9
 Fragments

A Fragment in Android is a component which can be used over an


activity to define an independent modular UI component attached to the activity. It
functions independently, but as it is linked to the Activity, when an activity is
destroyed, the fragment also gets destroyed.
If you know Biology, and are aware of the concept
of Host and Parasite, then in Android, Activity is the host while a Fragment is a
parasite.
Fragment has its own lifecycle events, which are different from an Activity's
lifecylce events.
An Activity can have any number of fragments in it, although it is
suggested to not to use too many fragments in a single activity.
Also, a fragment is a re-usable component, hence, a single fragment can be
included in multiple activities, if required.
Generally, fragments are used to create multi-pane UI in Android apps.
A Fragment has it's own Layout for the UI(user interface), but we can
even define a fragment without any layout, to implement a behavious which has no
user interface, more like a background service.
So, Fragment is a very interesting component of Android OS which can
be used in multiple ways in an android app.

Why we need Fragments in Android?

If we already have Activity, and a Fragment is just like a sub-activity,


then what is the use of having an additional component in Android?
Well, before the introduction of Fragments(Fragments were added in Honeycomb
version of Android i.e API version 11), we could only have a single Activity on a
screen at a given point of time, and there was no way to divide the screen and
control the different parts separately.

10
And as the screen size of the Mobile devices are increasing, it makes
more sense to show more stuff at the same time on the screen, hence Fragments are
very useful, and are very popular amongst the Android developers community.

The usage of Fragment in an android app totally depends on the screen size of the
device on which the app is being used. If the screen size is big, then we can easily
show 2 or maybe more fragments on the screen, but if the display size is smaller, it
is advised to use Fragments in separate activities.

Therefore it is also suggested to keep the design of a Fragment modular and


independent, so that it can be used on different screens/activity based on the screen
size or any other factor.

11
Main use of Fragments in Android
Following are the 3 main usage of Fragments in Android, for which Fragments
were introduced:
1. Modularity: If a single activity is having too many functional components,
its better to divide it into independent fragments, hence making the code
more organized and easier to maintain.
2. Reusability: If we define aany particular feature in a fragment, then that
feature more or less becomes a reusable component which can be easily
intgerated into any activity.
3. Adaptability: If we break UI components of an app screen into fragments,
then it becomes easier to change their orientation and placement, based on
screen size etc.
 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

12
 Fragments transaction − Using with fragment transaction. we can move one
fragment to another fragment.

 Fragment Life Cycle


The Fragment lifecycle begins when it is attached to an activity. Below we have
shown the complete lifecycle of fragment in form of a flow chart.

13
Lifecycle Methods for Fragment
This is called when the fragment becomes active or interactive.
Method Name Description

onAttach(Activity) It is called once, when the fragment is attached to the


activity.

onCreate(Bundle) The system calls this method when a fragment is created.


This is an important method and you should implement the
essential components of the fragment in this method.

onCreateView() This method is called when the UI of the fragment has to


be initialised. It is called when the fragment is first created
and then when the fragment returns back to the layout from
the back stack. This method usually returns
a View component but if the fragment doesn't have a UI,
then you can return a null.

onActivityCreated() This method is called when the host activity is created. By


this time, we can even access the fragment's view using
the findViewById() method.

onStart() This method is called when the fragment becomes visible


on the device's screen.

onResume()

onPause() This is called when a fragemnt is no longer interactive and


the user is about to leave the fragment. At this point, it is
suggested to save any data for the existing user session, if
required.

14
onStop() This method is called when the fragment is no longer
visible.

onDestroyView() This is called when the fragment is to be be destroyed.


Here you can do the clean up the resources before the
fragment is destroyed.

onDestroy() This is called for the final clean up of fragment's state.

onDetach() It is called just before the fragment is detached from the


host activity.

Android Fragment Example


Let's have a look at the simple example of android fragment.

activity_main.xml
File: activity_main.xml

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


2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="fill_parent"
6. android:layout_height="fill_parent"
7. tools:context="example.javatpoint.com.fragmentexample.MainActivity">
8.
9. <fragment
10. android:id="@+id/fragment1"
11. android:name="example.javatpoint.com.fragmentexample.Fragment1"
12. android:layout_width="0px"
13. android:layout_height="match_parent"
14. android:layout_weight="1"

15
15. />
16.
17. <fragment
18. android:id="@+id/fragment2"
19. android:name="example.javatpoint.com.fragmentexample.Fragment2"
20. android:layout_width="0px"
21. android:layout_height="match_parent"
22. android:layout_weight="1"
23. />
24.
25. </LinearLayout>

File: fragment_fragment1.xml

1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:background="#F5F5DC"
6. tools:context="example.javatpoint.com.fragmentexample.Fragment1">
7.
8. <!-- TODO: Update blank fragment layout -->
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:text="@string/hello_blank_fragment" />
13.
14. </FrameLayout>

File: fragment_fragment2.xml

1. <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:background="#F0FFFF"

16
6. tools:context="example.javatpoint.com.fragmentexample.Fragment2">
7.
8. <!-- TODO: Update blank fragment layout -->
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:text="@string/hello_blank_fragment" />
13.
14. </FrameLayout>

MainActivity class
File: MainActivity.java

1. package example.javatpoint.com.fragmentexample;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }

File: Fragment1.java

1. package example.javatpoint.com.fragmentexample;
2. import android.os.Bundle;
3. import android.support.v4.app.Fragment;
4. import android.view.LayoutInflater;
5. import android.view.View;
6. import android.view.ViewGroup;
7.

17
8. public class Fragment1 extends Fragment {
9.
10. @Override
11. public void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_fragment1, container, false);
20. }
21. }

File: Fragment2.java

1. package example.javatpoint.com.fragmentexample;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class Fragment2 extends Fragment {
10.
11. @Override
12. public void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_fragment2, container, false);

18
21. }
22.
23. }

Output:

19
 What is SQLite?
SQLite is an open-source, embedded, relational database management system,
designed circa 2000. It is a lightweight database, with zero configuration, no
requirements of a server or installation. Despite its simplicity, it is laden with
popular features of database management systems.

Key Features

 SQLite is very lightweight (it is less than 500Kb size) compare to other
database management systems like SQL Server, or Oracle.
 SQLite is not a client-server database management system. It is an in-
memory library that you can call and use directly. No installation and no
configuration required.
 A typical SQLite database is contained on a single file on the computer disk
storage with all the database objects (tables, views, triggers, etc.) included in
that file. No dedicated server required.

When to use SQLite?


 If you are developing embedded software for devices like
televisions, Mobile phones, cameras, home electronic devices, etc., then
SQLite is a good choice.
 SQLite can handle low to medium traffic HTTP requests and manage
complex session information for a website
 When you need to store an archive of files, SQLite can produce smaller size
archives and with lesser metadata included than regular ZIP archives.
 If you want to do processing on some data within an application, you can use
SQLite as a temporary dataset. You can load the data into an SQLite in-
memory database and execute the desired queries. You can extract the data
in a format you want to display in your application.
 It gives you an easy and efficient way to process using in-memory variables.
For example, you are developing a program where you have to perform
calculations on some records. You can create an SQLite database and insert

20
the records there, and with only one query, you can select the records and
perform calculations.
 When you need a database system for learning and training purposes,
SQLite is a good fit. As we explained earlier, no installation or configuration
is required. Copy the SQLite libraries in your computer, and you are ready to
learn.

Why use SQLite?

Following guide will help you determine whether you should choose SQLite for
your next project

 It is free. SQLite is an open source, no commercial license required to work


with it.
 SQLite is cross-platform database management system. It can be used on a
broad range of platforms like Windows, Mac OS, Linux, and Unix. It can
also be used on a lot of embedded operating systems like Symbian, and
Windows CE.
 SQLite offers an efficient way of storing data, the length of the columns is
variable and is not fixed. So SQLite will allocate only space a field needs.
For example, if you have a varchar(200) column, and you put a 10
characters' length value on it, then SQLite will allocate only 20 characters'
space for that value and not the whole 200 space.
 A broad range of SQLite APIs – SQLite provides APIs for a broad range of
programming language, for example.Net languages (Visual Basic, C#), PHP,
Java, Objective C, Python and a lot of other programming languages.
 SQLite is very flexible.

21
SQLite limitations and Unsupported Features

The following are the list of unsupported features and limitations in SQLite:

 SQLite supports neither RIGHT OUTER JOIN nor FULL OUTER JOIN. It
supports only LEFT OUTER JOIN.
 Limitations in ALTER table statement: with ALTER TABLE statement in
SQLite you can only add a column or rename a table (as we will see in the
following tutorials). However, you can't do the following:
o ALTER column.
o DROP a column.
o ADD a constraint.
 VIEWs are read-only – you can't write INSERT, DELETE, or UPDATE
statements into the view. However, you can create a trigger on a view and do
the INSERT, DELETE, or UPDATE statements into it.
 GRANT and REVOKE commands are not implemented in SQLite. There
are only normal file access permissions implemented in SQLite. This is
because SQLite reads and writes to the disk files, unlike other Database
management systems.
 TRIGGERS – As we will see in the incoming tutorials, SQLite only
supports FOR EACH ROW triggers, and it doesn't support FOR EACH
STATEMENT triggers.

22
Differences between SQL and SQLite

SQL SQLite

SQL is a Structured Query SQLite is an Embeddable Relational


Language used to query a Database Management System which is
Relational Database System. It is written in ANSI-C.
written in C language.

SQL is a standard which specifies SQLite is file-based. It is different from


how a relational schema is other SQL databases because unlike most
created, data is inserted or other SQL databases, SQLite does not
updated in the relations, have a separate server process.
transactions are started and
stopped, etc.

Main components of SQL are SQLite supports many features of SQL


Data Definition Language(DDL) , and has high performance and does not
Data Manipulation support stored procedures.
Language(DML), Embedded
SQL and Dynamic SQL.

SQL is Structured Query SQLite is a portable database resource.


Language which is used with You have to get an extension of SQLite in
databases like MySQL, Oracle, whatever language you are programming
Microsoft SQL Server, IBM DB2, in to access that database. You can access
etc. It is not a database itself. all of the desktop and mobile applications.

A conventional SQL database SQLite database system doesn?t provide


needs to be running as a service such functionalities.
like OracleDB to connect to and

23
provide a lot of functionalities.

SQL is a query language which is SQLite is a database management system


used by different SQL databases. itself which uses SQL.
It is not a database itself.

 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);

 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 Table name (Username
VARCHAR,Password VARCHAR);");\

mydatabase.execSQL("INSERT INTO Table name VALUES('admin','admin');");

 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);
24
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

25
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, a 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)


{

}
}

26
 Android AsyncTask

AsyncTask is an abstract class which means that the class extending it need to implement
the below mentioned methods and also since the class is generic type the class extending it
should specify these 3 generic types.These are explained below:-

Ex: a class extending it will use the below line…


private class SomeTask extends AsyncTask<Params,Progress,Result>{….}

AsyncTask’s Generic Types:-

1. Params → The type of parameters sent to the background thread to be used


upon execution.

2. Progress → The progress which is used to publish the progress on the main
UI thread.

3. Result → The result which is obtained after the background thread has
finished execution.

AsyncTask is basically used to reduce the load of tasks off the UI thread. It creates a
background thread to perform an operation like that of fetching results from the Internet or
loading data from the database, etc. and then publish the results to the main UI thread.

USAGE:It should generally be used for short operations which should ideally be finished
in a matter of few seconds.

27
Methods of AsyncTask.
1. onPreExecute() --> This method is invoked just before the background
thread is created and here we can do some initialisation that we might
want to do before the background thread starts the task.
It is used to basically setup a task. Ex: showing a Progress Bar,etc.
It runs on the main UI thread.

2. doInBackground(Params...) --> This method is invoked on the


background thread immediately after onPreExecute has finished
executing and is used to perform the task which is supposed to be run on
the background thread.This method can also call
publishProgress(Progress...) method to puclish progress on the main UI
thread which is received by the onProgressUpdate(Progress...) method.
Ex: Fetching results from a network request, etc.
It runs on the background thread.

3. publishProgress() --> This method can optionally be called within the


doInBackground() method to publish progress to the main UI thread and
show that progress to the user.
It can be called several times within the doInBackground to keep
the user updated about the progress of the task happening.

4. onProgressUpdate(Progress...) --> This method is invoked on the


main UI thread just after publishProgress(Progress...) is invoked on the
background thread and it receives the current progress and can used to
display/update the progress on the main UI.
It runs on the main UI thread.

5. onPostExecute(Result) --> This method is invoked on the main UI


thread just after the background thread has finished executing and has
returned the result to this method as seen in the method parameter. The

28
result can be then be used to do anything the developer wants to do with
that result.
It runs on the main UI thread.

Fig.Methods of Async Task

 The main disadvantage of using an AsyncTask and why they should rarely be
used… (Limitations)

1. Block the main UI thread → one reason for this is the same as mentioned above that
it can block the UI thread thereby freezing the app.
2. Wastage of memory →The creation of another AsyncTask can not only happen
through refresh button but a rather more general and practical example is suppose an
AsyncTask is already running and the user rotates the screen, then another Activity
will created and the former activity will go to the Stopped State and since there is a
completely new Activity a new AsyncTask is created and a new background thread is

29
created and then suppose the user again rotates the screen before the task is
completed, then another AsyncTask is created with a new background thread, and it
can happen again and again creating multiple number of AsyncTasks in the memory
thereby creating a large number of AsyncTask objects is created in the memory which
in turn, wastes a lot of memory and since memory is a very precious resource in
Android and should be used as efficiently as possible, it is not at all recommended.
And if this scenario happens again & again than Android OS will have no coice but to
forcefully destroy your Activity which you definitely do not want to happen.

3. Can lead to Memory Leaks → If the user rotates the screen another AsyncTask is
created and as you know that the previous AsyncTask did not finish executing. Now,
after the 1st AsyncTask completes with the 2nd Activity in the foreground then that
AsyncTask will try to return the result to the onPostExecute() method of an Activity
which does not exist and hence it leads to memory leaks.

 Broadcast Receiver:

Definition
A broadcast receiver (receiver) is an Android component which allows
you to register for system or application events. All registered receivers for an event
are notified by the Android runtime once this event happens.

For example, applications can register for the ACTION_BOOT_COMPLETED


system event which is fired once the Android system has completed the boot process.

Implementation
A receiver can be registered via the AndroidManifest.xml file.

Alternatively to this static registration, you can also register a receiver dynamically
via the Context.registerReceiver() method.

The implementing class for a receiver extends the BroadcastReceiver class.

30
If the event for which the broadcast receiver has registered happens, the onReceive()
method of the receiver is called by the Android system.

Broadcast receiver lifecycle

A broadcast receiver has single callback method:

void onReceive(Context curContext, Intent broadcastMsg)

When a broadcast message arrives for the receiver, Android calls its onReceive() method
and passes it the Intent object containing the message. The broadcast receiver is
considered to be active only while it is executing this method. When onReceive() returns,
it is inactive.

A process with an active broadcast receiver is protected from being killed. But a process
with only inactive components can be killed by the system at any time, when the memory
it consumes is needed by other processes.

This presents a problem when the response to a broadcast message is time consuming
and, therefore, something that should be done in a separate thread, away from the main
thread where other components of the user interface run. If onReceive() spawns the
thread and then returns, the entire process, including the new thread, is judged to be
inactive (unless other application components are active in the process), putting it in
jeopardy of being killed. The solution to this problem is for onReceive() to start a service
and let the service do the job, so the system knows that there is still active work being
done in the process.

System broadcasts

Several system events are defined as final static fields in the Intent class. Other Android
system classes also define events, e.g., the TelephonyManager defines events for the
change of the phone state.

The following table lists a few important system events.

31
Event Description

Intent.ACTION_BOOT_COMPLET Boot completed. Requires


ED the android.permission.RECEIVE_BOOT_CO
MPLETED permission

Intent.ACTION_POWER_CONNEC Power got connected to the device.


TED

Intent.ACTION_POWER_DISCONN Power got disconnected to the device.


ECTED

Intent.ACTION_BATTERY_LOW Triggered on low battery. Typically used to


reduce activities in your app which consume
power.

Intent.ACTION_BATTERY_OKAY Battery status good again.

32

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy