Android Note
Android Note
In android, application components are the basic building blocks of an application and these
components will act as an entry point to allow system or user to access our app.
The following are the basic core application components that can be used in Android
application.
• Activities
• Intents
• Content Providers
• Broadcast Receivers
• Services
All these application components are defined in the android app description file
(AndroidMainfest.xml) like as shown below.
</application>
</manifest>
Android Activities
In android, Activity represents a single screen with a user interface (UI) and it will acts an entry
point for the user’s to interact with app.
For example, a contacts app that is having multiple activities like showing a list of contacts, add
a new contact, and another activity to search for the contacts. All these activities in the contact
app are independent of each other but will work together to provide a better user experience.
Android Intents
In android, Intent is a messaging object which is used to request an action from another
component.
2
• Starting an Activity
• Starting a Service
• Delivering a Broadcast
1. Implicit Intents 2.
Explicit Intents.
Android Services
In android, Service is a component that keeps an app running in the background to perform
long-running operations based on our requirements. For Service, we don’t have any user
interface and it will run the apps in background like play music in background when the user in
different app.
• Local Services
• Remote Services
In android, Broadcast Receiver is a component that will allow a system to deliver events to the
app like sending a low battery message to the app. The apps can also initiate broadcasts to let
other apps know that required data available in a device to use it.
Generally, we use Intents to deliver broadcast events to other apps and Broadcast Receivers use
status bar notifications to let the user know that broadcast event occurs.
In android, Content Providers are useful to exchange the data between the apps based on the
requests. The Content Providers can share the app data that stores in the file system, SQLite
database, on the web or any other storage location that our app can access.
By using Content Providers, other apps can query or modify the data of our app based on the
permissions provided by content provider. For example, android provides a Content Provider
(ContactsContract.Data) to manage contacts information, by using proper permissions any
app can query the content provider to perform read and write operations on contacts
information.
3
Additional Components
In android, we have additional components which are used to build the relationship between the
above components (Activities, Intents, Content Providers, Services and Broadcast Receivers) to
implement our application logic, those are
Component Description
Fragments These are used to represent the portion of user interface in an activity
Layouts These are used to define the user interface (UI) for an activity or app
These are used to build a user interface for an app using UI elements like buttons,
Views
lists, etc.
To build an android app we required external elements like images, audio files,
Resources
etc. other than coding
It’s a configuration file (AndroidManifest.xml) for the application and it will
Manifest
contain the information about Activities, Intents, Content Providers, Services,
File
Broadcast Receivers, permissions, etc.
These are the main application components which are required to build an android application
based on our requirements.
In android, Implicit Intents won’t specify any name of the component to start instead, it declare
an action to perform and it allows a component from other apps to handle it. For example, by
using implicit intents we can request another app to show the location details of the user or etc.
Following is the pictorial representation of how Implicit intents send a request to the android
system to start another activity.
4
Activity A creates an intent with the required action and sends it to an android system using the
startActivity() method. The android system will search for an intent filter that matches the
intent in all apps. Whenever the match found the system starts matching activity (Activity B)
by invoking the onCreate() method.
In android when we create implicit intents, the android system will search for matching
components by comparing the contents of intent with intent filters which defined in the
manifest file of other apps on the device. If the matching component found, the system
starts that component and sends it to the Intent object. In case, if multiple intent filters are
matched then the system displays a dialOg so that the user can pick which app to use.
In android, an Intent Filter is an expression in the app’s manifest file and it is used to specify
the type of intents that the component would like to receive. In case if we create an Intent
Filter for activity, there is a possibility for other apps to start our activity by sending a certain
type of intent otherwise the activity can be started only by an explicit intent.
Following is the simple code snippet of implicit intent in the android application.
When we observe above implicit intent we didn’t defined any specific name of component to
start, instead we defined an action (ACTION_VIEW) to open the defined URL
(http://www.google.com) in browser within the device.
Intent Filter is an expression in the app’s manifest file (ActivityMainfest.xml) and it is used
to specify the type of intents that the component would like to receive. In case if we create
5
Intent Filter for an activity, there is a possibility for other apps to start our activity by sending
a certain type of intent otherwise the activity can be started only by an explicit intent. we can
specify the type of intents to accept using these three elements.
<action>
It defines the name of an intended action to be accepted and it must be a literal string value of
an action, not the class constant.
<category>
It defines the name of an intent category to be accepted and it must be the literal string value of
an action, not the class constant.
<data>
It defines the type of data to be accepted and by using one or more attributes we can specify
various aspects of the data URI (scheme, host, port, path) and MIME type.
MAIN - It indicates the app’s main entry point that means it starts the activity which defines
with the MAIN action when the user initially launches the app with a launcher icon.
LAUNCHER - It indicates that this activity icon should be placed on the home screen list of
apps. In case if the <activity> element doesn’t specify an icon with icon, then the system uses
the icon from the <application> element.
These two (MAIN, LAUNCHER) elements must be paired together in order for the activity to
appear in the app launcher.
Layout is used to define the user interface for an app or activity and it will hold the UI
elements that will appear to the user.
The user interface in an android app is made with a collection of View and ViewGroup objects.
Generally, the android apps will contain one or more activities and each activity is a one screen
of app. The activities will contain a multiple UI components and those UI components are the
instances of View and ViewGroup subclasses.
The user interface in an android app is made with a collection of View and ViewGroup objects.
Generally, the android apps will contain one or more activities and each activity is a one screen
of the app. The activities will contain multiple UI components and those UI components are the
instances of View and ViewGroup subclasses.
6
Android View
The View is a base class for all UI components in android. For example, the EditText class is
used to accept the input from users in android apps, which is a subclass of View.
The ViewGroup is a subclass of View and it will act as a base class for layouts and layouts
parameters. The ViewGroup will provide an invisible containers to hold other Views or
ViewGroups and to define the layout properties.
For example, Linear Layout is the ViewGroup that contains a UI controls like button, textview,
etc. and other layouts also.
• Linear Layout
• Relative Layout
• Table Layout
• Frame Layout
• Web View
• List View
• Grid View
WHAT IS FRAGMENT?(MARKS:15)
In android, Fragments are the modular section of activity design and these are used to
represent the behavior of user interface (UI) in an activity. By using fragments we can create
flexible UI designs that can be adjusted based on the device screen size such as tablets,
smartphones.
We can build multi-pane UI by combining multiple fragments in a single activity and we can
reuse the same fragment in multiple activities. The fragment has its own lifecycle call-backs
and accepts its own input events.
We can add or remove fragments in an activity while the activity is running. In android, the
fragment will act as a sub-activity and we can reuse it in multiple activities.
Generally in android, the fragment must be included in an activity due to that the fragment
lifecycle will always be affected by the host activity life cycle. In case if we pause an activity,
all the fragments related to an activity will also be stopped.
7
In android, we can insert the fragment into activity layout by using <fragment> element and by
dividing the layout of activity into fragments, we can modify the appearance of an app design at
runtime. We can also implement a fragment without having any user interface (UI).
It’s an optional to use fragments into activity but by doing this it will improve the flexibility of
our app UI and make it easier to adjust our app design based on the device size.
Following is the example of defining a multiple fragments in single activity for the tablet design
to display the details of an item which we selected in the app, but separated for mobile design.
If you observe above example for Tablet we defined an Activity A with two fragments such as
one is to show the list of items and second one is to show the details of item which we selected
in first fragment.
Following is a pictorial representation of the android fragment life cycle while its activity is
running.
8
Following are the list of methods which will perform during the lifecycle of fragment in
android applications.
9
Method Description
It is called when the fragment has been associated with an
onAttach()
activity.
In android, Service is a component which keep an app running in the background to perform
long-running operations based on our requirements. For Service, we don’t have any user
interface and it will run the apps in the background like playing the music in the background or
handle network operations when the user in a different app.
In android, the life cycle of service will follow two different paths Started or Bound.
Started Service
We can stop the Started service by using stopService() method or the service can stop itself by
calling stopSelf() method. In android, the Started service component will perform a single
operation and it won’t return any result to the caller.
Bound Service
A service is Bound when another application component calls bindService() method. The
bound service runs as long as another application component is bound to it.
We can unbind the service by calling unbindService() method based on our requirements. In
android, we can bind multiple components to a single service at once, but the service will be
destroyed in case all the components unbind.
Following diagram shows the lifecycle of Started service, when the service created with
startService() and the lifecycle of Bound service, when the service created with bindService().
To create a service, we need to create a class that extends a Service base class or one of its
existing subclasses. During our service implementation, we must need to override some of the
11
callback methods that handle the key aspects of the service lifecycle and provide the
functionality that allows our components to bind to the service.
The life cycle for a service is similar to that for an activity, but there are some important
differences 1. Client calls the Context.startService Intent() method. This creates the service if it
is not already running.
2. If the service is not already running- Android calls onCreate() and then on Start(). Example,
if we need to play some music, but only while our activity is running, we might create a thread
in onCreate(). If service is already running, then only on Start() is called with the new intent,
3. Client calls the Context bind Service Intent) method. This creates the service if it is not
running
4. If the service is not already running- Android calls onCreate() and then on Window. If
services already running, then only onBind() is called with the client's intent.
5. Service generally has no user interface. So there is no need for the onPause, onResume(), or
on Stop() methods.
6. The activity calls the onDestroy method when the service is to be terminated. Android
terminates a service when there are no more clients starting or bound to it. Android also
terminates a service when memory is getting low. 7. If due to memory low, it terminates then
android will attempt to restart the service when memory pressure passes. So if the service
requires to store persistent information for that restart, it uses the onStart() method.
Create a Service
Generally, in android to create a service we must create a subclass of Service or use one of
existing subclass. In android the application component such as an activity can start the service
by calling startService() which results in calling the service’s onStartCommand() ethod.
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
Once we create a service, we need to register that in android manifest file using <service>
element like as shown below
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.services2">
<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>
</intent-filter>
</activity>
<service android:name=".Myservices"></service>
</application>
13
</manifest>
Start a Service
In android, the component such as an activity, service or receiver can start the service using
startService() method. Following is the sample code snippet of starting a service using the
startService method.
Content Providers, firing Intents, and triggering Notifications etc to which all Android
application can use them permissions. Each service should have a matching <service>
declaration in its package AndroidManifest.xml.
b. Context.bind Service()
Services are the faceless components of Android as they do not have their individual
interfaces. They typically run in the background to perform long-running operations or work
for remote processes
Services can communicate with other Android components and use the Android's notification
framework to notify the users.
Services are job-specific and they are unaffected by the switching activity. They will continue
to run in the background even if you switch to the interface of a different application.
• A feature for the application where the user is not directly interacting with the application
corresponds to calls to Context.startService() method, which ask the system to agenda work
for the service, to be run until the service or someone stops it forcefully.
14
• A feature for an application to expose some of its functionality to other applications. This
corresponds to calls to Context.bindService(), which allows a established connection to be
made to the service in order to interact with it.
To use this custom layout as Toast notification in our android application, we need to inflate the
layout using following code.
to the inflated layout.Once we are done with required configurations, then we can show the
custom toast notification by calling show() method
The layout inflater in Android Toasts is used to create custom toast layouts1. It inflates a custom layout
XML file, allowing you to design Toasts with ImageView and TextView elements12. You retrieve the layout
inflater, inflate the layout from XML, and then pass the inflated layout to the setView() method of the
Toast1. This allows you to display custom messages and images in your Toasts1. The inflate() method's
second parameter helps to ensure that LayoutParams are handled correctly, which is important for
features like margins2.
Spinner is a view that allows a user to select one value from the list of values. The spinner in
android will behave same as a dropdown list in other programming languages.
Generally, the android spinners will provide a quick way to select one item from the list of
values and it will show a dropdown menu with a list of all values when we click or tap on it.
By default, the android spinner will show its currently selected value and by using Adapter
we can bind the items to spinner objects.
ArrayAdapter: It will expect an Array or List as input.
This is how we can define and bind data to Spinner control in android applications.
If we observe above code we are calling our layout using setContentView method in the
form of R.layout.layout_file_name. Here our xml file name is activity_main.xml so
we used file name activity_main and we are setting text to one of our TextView control
(textView2) in our activity file
EXPLAIN GRID VIEW AND LIST view(15 MARKS)
n android, ListView is a ViewGroup that is used to display the list of scrollable of items
in multiple rows and the list items are automatically inserted to the list using an
adapter.
Generally, the adapter pulls data from sources such as an array or database and converts
each item into a result view and that’s placed into the list.
Once we are done with creation of layout, now we will bind data to our ListView using
ArrayAdapter, for that open main activity file MainActivity.java from
\java\com.tt.listview path and write the code like as shown below.
MainActivity.java
package com.tt.listview; import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle; import
android.widget.ArrayAdapter; import
android.widget.ListView;
GRID VIEW
17
In android, Grid View is a ViewGroup that is used to display items in a two dimensional, scrollable grid
and grid items are automatically inserted to the gridview layout using a list adapter.Generally, the adapter
pulls data from sources such as an array or database and converts each item into a result view and that’s
placed into the list.
R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6,
R.drawable.img7, R.drawable.img8,
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6,
R.drawable.img7, R.drawable.img8,
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5
};
}
numColumns property has to be specified otherwise GridView behaves like a ListView with just singleChoice. We can
specify numColumns property specified that there is 3 columns to show,or 4 columns to show.
If we set it to auto_fit then it automatically display as many column as possible to fill the available space of the
screen. Even if the phone is in portrait mode or landscape mode it automatically fill the whole space.
Generally, the android ScrollView is useful when we have content that doesn’t fit our android app layout
screen. The ScrollView will enable a scroll to the content which is exceeding the screen layout and allow users
to see the complete content by scrolling.
The android ScrollView can hold only one direct child. In case, if we want to add multiple views within the
scroll view, then we need to include them in another standard layout like linearlayout, relativelayout,
framelayout, etc.
To enable scrolling for our android applications, ScrollView is the best option but we should not use
ScrollView along with ListView or Gridview because they both will take care of their own vertical scrolling.
In android, ScrollView supports only vertical scrolling. In case, if we want to implement horizontal scrolling,
then we need to use a HorizontalScrollView component.
The android ScrollView is having a property called android:fillViewport, which is used to define whether the
ScrollView should stretch it’s content to fill the viewport or not.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:fillViewport="false">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"> <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_gravity="center"
android:layout_marginTop="60dp" android:text="Button One" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Two" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Three" />
</ScrollView>
If the activity in the center of the screen, it is active or running when it is in the
foreground of the screen. This is the activity that is the focus for the user's actions.
stopped if it completely obscured by one more activity. It still retains all state and
member information. However, it is no longer able to be seen to the user so its window
is hidden and it will often be killed by the system when memory is needed another place.
There are three key loops that we may be interested in monitoring within our activity:
➢ An activity happens between the first call to onCreate(Bundle) through to a single final
call to onDestroy(). An activity will do all setup of global state in onCreate(), and release
all remain resources in onDestroy.
➢ The lifetime of an activity happens between a call to onStart () until a corresponding call
to onStop (). During this time the user can see the activity on-screen, though it might not
be in the foreground and interacting with the user. Between these two methods we can
maintain resources that are needed to show the activity to the user. For example, we can
register a broadcast Receiver in onStart() to monitor for changes that impact our UI, and
unregister it in onStop(). when the user no longer sees what you are displaying. The
onStart () and onStop methods can be called numerous times, as the activity becomes
visible and hidden to the user.
The foreground lifetime of an activity happens between a call to onResume until a
corresponding call to onPause(). Throughout this time the activity is in front of all
other activities and interacting with the user. An activity can habitually go between the
resumed and paused state for example when the device go to sleep mode, when an
activity result delivered, when a new intent is delivered then the code in these methods
should be fairly lightweight.
Broadcast Receiver
▪ A broadcast receiver is a component that do nothing but receive and react to broadcast
announcements,
▪ Many broadcasts originate in system code (e.g. "I got mail“) but any other application also
initiate broadcasts.
21
Broadcast receivers do not display a user interface. However, they may perhaps start
activity in response to the information they receive, or - as services do - they may
possibly use the notification manager to alert the user.
SQLite is an open source database engine which implements a self-contained, Serverless, zero-
configuration, transactions. SQLite is an open-source relational database i.e. used to perform database
operations on android devices such as storing, manipulating or retrieving persistent data from the
database.
It is embedded in android by default. So, there is no need to perform any database setup or
administration task.
The code of SQLite is open to use for any purpose, i.e., commercial or private, because of it is in
Why SQLite?
Serverless: SQLite is Serverless which does not need a server or system to operate
Less memory: SQLite is very small and light-weight, less than 400KB needed
Transaction: SQLite transactions are supported ACID properties (Atomicity, Consistency, Isolation,
and Durability − commonly known as ACID properties) to allow safe access from multiple processes
or threads.
Languages and Operating System: SQLite supports most of the query language features found in SQL
standard. SQLite is accessible on UNIX, Linux, Mac, Android and windows.
➢ Transactions
When we want to execute a series of queries that either all complete or all fail, at that
situation we use transactions which is supported by SQLite. When a SQLite transaction fails, an
A transaction is the propagation of one or more changes to the database. For example, if you
are creating, updating, or deleting a record from the table, then you are performing transaction on
the table.
Properties of Transactions
Transactions have the following four standard properties, usually referred to by the acronym ACID.
Atomicity
Ensures that all operations within the work unit are completed successfully; otherwise, the
transaction is aborted at the point of failure and previous operations are rolled back to their former
state.
• Consistency
Ensures that the database properly changes states upon a successfully committed transaction.
• Isolation
Enables transactions to operate independently of and transparent to each other.
Durability
Ensures that the result or effect of a committed transaction persists in case of a system failure.
2. COMMIT Command
COMMIT;
or
END TRANSACTION;
ROLLBACK Command
ROLLBACK command is the transactional command used to undo transactions that have not
already been saved to the database. ROLLBACK command can only be used to undo transactions
since the last COMMIT or ROLLBACK command was issued.
Example
Consider COMPANY table with the following records.
25
Now, let's start a transaction and delete records from the table having age = 25. Then, use
ROLLBACK command to undo all the changes.
sqlite> BEGIN;
sqlite> DELETE FROM COMPANY WHERE AGE = 25;
sqlite> ROLLBACK;
Now, if you check COMPANY table, it still has the following records −
ID NAME AGE ADDRESS SALARY
sqlite> BEGIN;
sqlite> DELETE FROM COMPANY WHERE AGE = 25; sqlite>
COMMIT;
If you now check COMPANY table is still has the following records –
ID NAME AGE ADDRESS SALARY
26
Example
1. Start with a call to beginTransaction ( ) to inform SQLite to execute the queries in transaction
mode.
3. Perform the queries and the call setTransactionSuccessful ( ) to inform SQLite that our transaction
is complete
27
4. It an error is not thrown, then endTransaction ( ) can be called to perform the transaction.
WI-FI
android, Wi-Fi is a wireless network protocol that allows devices to connect to the internet or connect
wirelessly with other devices to exchange the data.
Generally, in android applications by using Wi-Fi API’s we can manage all aspects of WI-FI connectivity,
such as a scan or search for available networks, add/save/delete Wi-Fi connections and managing the data
transfer between devices within the range.
By using android Wi-Fi API’s in android applications, we can perform following functionalities.
Following is the example of defining the Bluetooth permissions in android manifest file.
..
</manifest>
By using WifiManager class, we can perform the operations that are related to network connectivity. We
can instantiate this class by using Context.getSystemService(Class) with the argument
WifiManager.class or Context.getSystemService(String) with the argument Context.WIFI_SERVICE.
Following is the code snippet to initialize WifiManager class using Context.getSystemService(String)
with the argument Context.WIFI_SERVICE.
28
If you observe above code snippet, we used getSystemService() method to instantiate a WifiManager
class.
In case if getSystemService() method returns NULL, then the device does not support Wi-Fi and we can
disable all Wi-Fi features.
Following is the code snippet to enable a Wi-Fi in android application by using setWifiEnabled() method.
If you observe above code snippet, we used setWifiEnabled(true) method to turn ON or Enable a Wi-Fi
in our android application.
By using setWifiEnabled(false) method we can Disable or turn OFF a Wi-Fi in android applications.
DATE PICKER.JAVA
package com.example.datepicker; import
androidx.appcompat.app.AppCompatActivity;
@Override
29
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month + 1, day);
}
30
WRITE THE JAVA CODE AND XML CODE FOR IMPLICIT INTENT
IMPLICIT INTENT.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<EditText
android:id="@+id/editText1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</RelativeLayout>
IMPLICIT INTENT.JAVA
package com.example.implicitintentdemo; import
androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri; import
android.os.Bundle; import
android.view.View; import
android.widget.Button; import
android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Bind the components to their respective objects
// by assigning their IDs
// with the help of findViewById() method
final EditText editText1 = (EditText)findViewById(R.id.editText1);
Button button = (Button)findViewById(R.id.button1);
31
</manifest>
EXPLICIT INTENT.XML
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First Activity"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="callSecondActivity"
android:text="Call second activity"/>
</RelativeLayout>
EXPLICIT INTENT.JAVA-service package
com.example.intentdemo; import
androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
EXPLICIT.XML
<TextView
android:layout_width="wrap_content"
33
android:layout_height="wrap_content"
android:text="Second Activity” /> <Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="callFirstActivity" android:text="Call
first activity”/>
</RelativeLayout >
SECOND ACTIVITY.JAVA
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TEXTTOSPEECH.XML
<?xml version="1.0" encoding="utf-8"?>
34
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="34">
</EditText>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speak to me"
/>
</LinearLayout>
TEXTTOSPEECH.JAVA
androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent; import
android.os.Bundle;
import android.speech.tts.TextToSpeech; import
android.speech.tts.TextToSpeech.OnInitListener; import
android.view.View; import android.widget.Button;
import android.widget.EditText; import
android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputText = (EditText)findViewById(R.id.input);//xml code to javacode linking
speakButton = (Button)findViewById(R.id.button);
@Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text != null && text.length() > 0) {
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
android:layout_width="match_parent"
android:layout_height="match_parent” android:orientation="vertical"
>
<Button
android:id="@+id/startbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Service"/>
<Button
android:id="@+id/stopbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Service”/>
</LinearLayout>
SERVICE ACTIVITY.JAVA
<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">
<service
android:name=".MyService2"
android:enabled="true"
android:exported="true"></service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
SERVICE2.JAVA
package com.example.servicesnew;
MediaPlayer player;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {//call from start
button player=MediaPlayer.create(this, R.raw.song);//setting ring tone
player.setLooping(true);//continuously ringing player.start(); return
START_STICKY;//return 1 to make the player success
}
38
<EditText android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="NAME"
android:layout_below="@+id/title"
android:inputType="txtName"
/>
<EditText
android:id="@+id/contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="CONTACT NO”
android:layout_below="@+id/name"
android:inputType="number"
/>
<EditText android:id="@+id/dob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="date of birth”
39
android:layout_below="@+id/contact"
android:inputType="number” />
<Button
android:id="@+id/btninsert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="INSERT"
android:layout_below="@+id/dob"
/>
<Button
android:id="@+id/btnupdate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="UPDATE"
android:layout_below="@+id/btninsert” />
<Button
android:id="@+id/btndelete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="DELETE"
android:layout_below="@+id/btnupdate"/>
<Button android:id="@+id/btnview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="VIEW"
android:layout_below="@+id/btndelete” />
</RelativeLayout>
DATABASE.JAVA
package com.example.mydatabase;
insert = findViewById(R.id.btninsert);
update=findViewById(R.id.btnupdate);
delete = findViewById(R.id.btndelete);
view = findViewById(R.id.btnview);
DB = new DBHelper(this);
insert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String nameTXT = name.getText().toString();
String contactTXT = contact.getText().toString();
String dobTXT = dob.getText().toString();
Boolean checkinsertdata =
DB.insertuserdata(nameTXT,contactTXT,dobTXT);
if (checkinsertdata==true)
Toast.makeText(MainActivity.this,"NEW ENTRY
INSERTED",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"NEW ENTRY NOT
INSERTED",Toast.LENGTH_LONG).show();
}
});
update.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String nameTXT = name.getText().toString();
String contactTXT = contact.getText().toString();
String dobTXT = dob.getText().toString();
Boolean checkupdatedata =
DB.updateuserdata(nameTXT,contactTXT,dobTXT);
if (checkupdatedata==true) Toast.makeText(MainActivity.this,"
ENTRY
UPDATED",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this," ENTRY NOT
41
UPDATED",Toast.LENGTH_LONG).show();
}
});
delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String nameTXT = name.getText().toString();
Boolean checkdeletedata = DB.deletedata(nameTXT);
if (checkdeletedata==true)
Toast.makeText(MainActivity.this," ENTRY
DELETED",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this," ENTRY NOT
DELETED",Toast.LENGTH_LONG).show();
}
});
view.setOnClickListener(new OnClickListener() {
@Override public void
onClick(View view) { Cursor
res = DB.getdata(); if
(res.getCount()==0){
Toast.makeText(MainActivity.this,"NO
ENTRY",Toast.LENGTH_SHORT).show();
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()){ buffer.append("name"
+ res.getString(0) + "\n"); buffer.append("contact"
+ res.getString(1) + "\n"); buffer.append("dob" +
res.getString(2) + "\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true); builder.setMessage(buffer.toString());
builder.setTitle("USER ENTRIES");
builder.show();
}
});
}
}
DBHELPER.JAVA
package com.example.mydatabase;
import android.content.ContentValues;
42
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase DB) {
DB.execSQL("create Table userdetails(name TEXT Primary key,contact
TEXT,dob TEXT)");
}
return true;
}
} else {
return false; }
DATABASE TABLE
44
SMS TELEPHONY
SMS.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/sms_editText1"
android:inputType="phone"/>
<EditText
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/sms_editText2" />
<Button android:id="@+id/btn1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Send SMS"/>
</LinearLayout>
SMS.JAVA
package com.example.sms; import
androidx.appcompat.app.AppCompatActivity;
import android.app.Activity; import
android.os.Bundle; import android.content.Intent;
import android.net.Uri; import
android.provider.Telephony; import
android.telephony.SmsManager; import
android.view.View; import android.widget.Button;
import android.widget.EditText; import
android.widget.Toast;
String message;
SmsManager sm; @Override protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); sendBtn =
(Button) findViewById(R.id.btn1); txtMobile = (EditText)
findViewById(R.id.sms_editText1); txtMessage = (EditText)
findViewById(R.id.sms_editText2);
sendBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
try{
SmsManager smgr = SmsManager. getDefault();
smgr.sendTextMessage(txtMobile.getText().toString(),null,txtMessage.getText().toString(),nul
l,null);
Toast.makeText(MainActivity.this, "SMS Sent Successfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "SMS Failed to Send, Please try again",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
MEDIA PLAYER .XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/txtVw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Now Playing: "
/>
<TextView
android:id="@+id/txtSname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
46
<ImageButton android:id="@+id/btnBackward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_media_rew" />
<ImageButton android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_media_play" />
<ImageButton
android:id="@+id/btnPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_media_pause" />
<ImageButton android:id="@+id/btnForward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnPause"
android:src="@android:drawable/ic_media_ff" />
<TextView
android:id="@+id/txtStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0 min, 0 sec" />
<SeekBar android:id="@+id/sBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/txtStartTime" />
<TextView
android:id="@+id/txtSongTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0 min, 0 sec " />
</RelativeLayout>
MEDIA PLAYER.JAVA
package com.example.medianew;
android.widget.Toast; import
java.util.concurrent.TimeUnit;
playbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Playing Audio",
Toast.LENGTH_SHORT).show();
mPlayer.start(); eTime =
mPlayer.getDuration(); sTime =
mPlayer.getCurrentPosition();
if(oTime == 0){
songPrgs.setMax(eTime); oTime =1;
}
songTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(eTime),
TimeUnit.MILLISECONDS.toSeconds(eTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(eTime))) );
startTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(sTime),
TimeUnit.MILLISECONDS.toSeconds(sTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(sTime))) );
songPrgs.setProgress(sTime); hdlr.postDelayed(UpdateSongTime, 100);
pausebtn.setEnabled(true); playbtn.setEnabled(false);
}
});
48
pausebtn.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View v) {
mPlayer.pause();
pausebtn.setEnabled(false);
playbtn.setEnabled(true);
Toast.makeText(getApplicationContext(),"Pausing Audio",
Toast.LENGTH_SHORT).show();
}
});
forwardbtn.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View v) { if((sTime
+ fTime) <= eTime)
{
sTime = sTime + fTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds",
Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
backwardbtn.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View v) {
if((sTime - bTime) > 0)
{
sTime = sTime - bTime;
mPlayer.seekTo(sTime);
}
else
{
Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds",
Toast.LENGTH_SHORT).show();
}
if(!playbtn.isEnabled()){
playbtn.setEnabled(true);
}
}
});
49
}
private Runnable UpdateSongTime = new Runnable() {
@Override public void run() {
sTime = mPlayer.getCurrentPosition();
startTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(sTime),
TimeUnit.MILLISECONDS.toSeconds(sTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(sTime))) );
songPrgs.setProgress(sTime); hdlr.postDelayed(this, 100);
}
};
}
WIFI.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btnOn" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Wifi Turn On" android:layout_marginLeft="70dp"
android:layout_marginTop="200dp" />
<Button
android:id="@+id/btnOFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btnOn"
android:layout_toRightOf="@+id/btnOn"
android:text="Wifi Turn OFF" /> </RelativeLayout>
50
MainActivity.java
package com.tf.wifiexample; import
android.content.Context; import
android.net.wifi.WifiManager; import
android.support.v7.app.AppCompatActivity; import
android.os.Bundle; import android.view.View;
import android.widget.Button;
If you observe above code, we used setWifiEnabled() method of WifiManager class to enable or disable a
Wi-Fi in our application.
As discussed, we need to set Wi-Fi permissions in android manifest file (AndroidManifest.xml) to access
WiFi features in android applications. Now open android manifest file (AndroidManifest.xml) and write the
code like as shown below
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tf.wifiexample">
<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"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
51
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>
Unit 1
Introduction to Android, Android Versions, Android Activity, Android Features and
Architecture, Java JDK, Android SDK, Android Development Tools, Android Virtual
Devices,Emulators, Dalvik Virtual Machine, Layouts –Linear, Absolute, Frame, Relative and
Table layout
Answer all questions .Each question carries2 marks each
1.Explain Resource manager?
2.What is Linux kernel?
3.what is SSL?
4.What is SQL LITE?
5.What is view?
6.What is absolute layout?
7.What is linear layout?Explain its properties?
8.What is SGL?
ANSWER ALL QUESTIONS.Each carries 5 marks
9.Explain Application framework?
10.Explain SGL?
11.Explain JRE?
12.What is android SDK? Explain AVD?
13.Explain the properties of Frame layout and Table layout?
14.Discuss Emulator and its features?
15.Explain android user interface?What is FRAGMENT?
16.Explain Frame layout?Discuss fill parent and wrap content?
Answer all questions.Each question carries 15 marks each
17.Explain android archietecture?
52
20.Explain WI-FI?
21.Explain ACID properties?
Answer 10 questions .Each question carries2 marks each
1.Explain WI-FI?
2.Explain XML?
3.what is meant by name-value pair in JSON?
4.What is google play services?
5.What is linux kernel?
6.What is webkit?Explain JRE?
7.What is Activitymanager ?
8.What is SQLITE in android?
9.Explain intentfilter?
10.Explain Manifest file?
11.Explain onBind()?
12.Explain java code for progress bar? ANSWER
24.Explain Multimedia Architecture?Give the xml and java code for playing audio and video?
OR
(a)Explain Cursors?
(b)Give xml code and java code for sms telephony?
(c)Name the packages imported in playing audio and video?
when your action is important but your • <actions> – Action name defines the
application is not capable of performing it. intent action that it’ll accept.
• <data> – Data defines the data that is
acceptable.
• <category> – Category defines the
Let’s check the following so we can learn name of the Intent Category that is
how to use it: acceptable.
UNIT 5
1.How to loop an JSON object?
2.What is nested JSONObject?