0% found this document useful (0 votes)
25 views

UNIT4

The document discusses different types of text and input widgets in Android like TextView, EditText, AutoCompleteTextView, Button, ImageView and ListView. It provides details about their classes, attributes and usage.

Uploaded by

harshbadhe8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

UNIT4

The document discusses different types of text and input widgets in Android like TextView, EditText, AutoCompleteTextView, Button, ImageView and ListView. It provides details about their classes, attributes and usage.

Uploaded by

harshbadhe8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT4:

public class TextView


extends View implements ViewTreeObserver.OnPreDrawListener

java.lang.Object
↳ android.view.View
↳ android.widget.TextView

TextView in Android is one of the basic and important UI elements.


if the important part of the information is to be highlighted then the substring that contains, it
is to be italicized or it has to be made bold, one more scenario is where if the information in
TextView contains a hyperlink that directs to a particular web URL then it has to be spanned
with hyperlink and has to be underlined. Have a look at the following list and image to get an
idea of the overall discussion.

Formatting the TextView


Android offers mainly 3 types of typefaces
• normal
• sans
• serif
• monospace
android:typeface="normal"

Changing Text Style


In Android there are basically three text styles:
• Bold
• Italic
• Normal

“android:textStyle=”bold|italic”.
android:textColor="#B00020"

• Shadow for the text can also be given in Android. The attributes required for the shadowed
text view are:
android:shadowDx=”integer_value” -> which decides the distance of text from its shadow with
respect to x axis, if the integer_value is positive the shadow is on positive of the x axis and vice versa.

android:shadowDy=”integer_value” -> which decides the distance of text from its shadow with
respect to y axis, if the integer_value is positive the shadow is on negative of the y axis and vice
versa.

android:shadowRadius=”integer_value” -> which decides the amount of the shadow to be given for
the text view.

android:shadowDx="-15"
android:shadowDy="4"
android:shadowRadius="10"

android:letterSpacing=”floatingTypeValue” -> This attribute is used to give the space between each
of the letters.

android:textAllCaps=”trueOrfalse” -> This attribute decides, all the letters should be in uppercase or
not.

android:letterSpacing="0.15"
android:textAllCaps="true"

Adding Icons for TextView


• Android also allows adding drawable with the text views.
• There are three positions to add the icons for the TextView. They
are a start, end, top, and bottom.

android:drawableEnd="@drawable/ic_lappy"

Edit Text

public class EditText


extends TextView

java.lang.Object
↳ android.view.View
↳ android.widget.TextView
↳ android.widget.EditText

EditText is a Widget of user interface (UI) used to retrieve and modify text data from a user in
an Android app
Attributes Description

android:id It is used to uniquely identify the element

android:width It is used to set the width of EditText in pixels

android:hight It is used to set the height of EditText in pixels

android:text It is used to set the text value inside the EditText

android:inputType It is used to mention what type of value should pass in EditText,


like plain text, email, password, etc

android:hint It is used to highlight what should be input when text is empty

android:gravity gravity is used to align the text like left, right, center, top

android:textSize It is used to specify the size of the text

android:textStyle It is used to set the text style like bold, italic, bold italic, etc.

android:textColor It is used to set the color of the text

android:background It is used to set the background of your EditText

android:backgroundTint It is used to set tint to the background of your element

android:maxWidth It is used to set the maximum width of View in pixel

android:minWidth It is used to set the minimum width of View in pixel

android:drawableStart It is used to set the drawable to be drawn to the start of View

android:drawableEnd It is used to set the drawable to be drawn to the end of View

android:drawableBottom It is used to set the drawable to be drawn to the bottom of View

android:drawableLeft It is used to set the drawable to be drawn to the left of View

android:drawableRight It is used to set the drawable to be drawn to the right of View

android:drawablePadding It is used to set the drawable to be drawn from the set padding
of View

1. EditText edittext = findViewById(R.id.editText);


2. String value=edittext.getText().toString();

AutoCompleteTextView
java.lang.Object
↳ android.view.View
↳ android.widget.TextView
↳ android.widget.EditText
↳ android.widget.AutoCompleteTextView

An editable text view that shows completion suggestions automatically while


the user is typing. The list of suggestions is displayed in a drop down menu
from which the user can choose an item to replace the content of the edit box
with.

The drop down can be dismissed at any time by pressing the back key or, if no
item is selected in the drop down, by pressing the enter/dpad center key.

The list of suggestions is obtained from a data adapter and appears only after a given
number of characters defined by the threshold. <AutoCompleteTextView

android:layout_width="match_parent"
android:layout_height="100px"
android:placeholder="Enter your country name"
android:id="@+id/txtcountries"/>
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,cou
ntries);
AutoCompleteTextView
textView=(AutoCompleteTextView)findViewById(R.id.txtcountries);
textView.setThreshold(3);
textView.setAdapter(adapter);
}

<TextView

android:text="Visit our website at https://example.com"

android:autoLink="web" />

TextView textView = findViewById(R.id.my_text_view);


textView.setAutoLinkMask(Linkify.WEB_URLS); // Enables auto-linking for web URLs

java.lang.Object
↳ android.view.View
↳ android.widget.TextView
↳ android.widget.Button
public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.content_layout_id);

final Button button = findViewById(R.id.button_id);


button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses
button
}
});
}
}

Sr.No Attribute & Description

android:adjustViewBounds
1 Set this to true if you want the ImageView to adjust its
bounds to preserve the aspect ratio of its drawable.

android:baseline
2
This is the offset of the baseline within this view.

android:baselineAlignBottom
3 If true, the image view will be baseline aligned with based on
its bottom edge.

android:cropToPadding
4
If true, the image will be cropped to fit within its padding.

android:src
5
This sets a drawable as the content of this ImageView.

ToggleButton is basically a stop / play or on/off button with indicator light


indicating the current state of ToggleButton

public void onToggleClick(View view)


{
if (togglebutton.isChecked()) {
textview.setText("Toggle is ON");
}
else {
textview.setText("Toggle is OFF");
}
}

java.lang.Object

↳ android.view.View

↳ android.view.ViewGroup

↳ android.widget.AdapterView<android.widget.ListAdapter>

↳ android.widget.AbsListView

↳ android.widget.ListView

A list view is an adapter view that does not know the details, such as type and
contents, of the views it contains. Instead list view requests views on demand
from a ListAdapter as needed, such as to display new views as the user scrolls up
or down.

In order to display items in the list, call setAdapter(android.widget.ListAdapter) to


associate an adapter with the list.

Attribute Description

android:divider A color or drawable to separate list items.

android:dividerHeight Divider’s height.

Reference to an array resource that will populate


android:entries
the ListView.

When set to false, the ListView will not draw


android:footerDividersEnabled
the divider before each footer view.

When set to false, the ListView will not draw


android:headerDividersEnabled
the divider before each header view.
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

ListView l;
String tutorials[]
= { "Algorithms", "Data Structures",
"Languages", "Interview Corner",
"GATE", "ISRO CS",
"UGC NET CS", "CS Subjects",
"Web Technologies" };

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
ArrayAdapter<String> arr;
arr
= new ArrayAdapter<String>(
this,
R.layout.support_simple_spinner_dropdown_item,
tutorials);
l.setAdapter(arr);

public class GridView


extends AbsListView

java.lang.Object

↳ android.view.View

↳ android.view.ViewGroup

↳ android.widget.AdapterView<android.widget.ListAdapter>

↳ android.widget.AbsListView

↳ android.widget.GridView
A view that shows items in two-dimensional scrolling grid. The items in the grid
come from the ListAdapter associated with this view.

• android:numColumns: This attribute of GridView will be used to


decide the number of columns that are to be displayed in Grid.
• android:horizontalSpacing: This attribute is used to define the
spacing between two columns of GridView.
• android:verticalSpacing: This attribute is used to specify the
spacing between two rows of GridView.
• <GridView
• android:id="@+id/idGVcourses"
• android:layout_width="match_parent"
• android:layout_height="match_parent"
• android:horizontalSpacing="6dp"
• android:numColumns="2"
• android:verticalSpacing="6dp" />

Displays image resources, for example Bitmap or Drawable resources. ImageView is


also commonly used to apply tints to an image and handle image scaling.
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_image"
android:contentDescription="@string/my_image_description"
/>

java.lang.Object

↳ android.view.View

↳ android.view.ViewGroup

↳ android.widget.FrameLayout

↳ android.widget.ScrollView

A view group that allows the view hierarchy placed within it to be scrolled. Scroll view
may have only one direct child placed within it. To add multiple views within the scroll
view, make the direct child you add a view group, for example LinearLayout, and place
additional views within that LinearLayout.
Scroll view supports vertical scrolling only. For horizontal scrolling,
use HorizontalScrollView instead.

Never add a RecyclerView or ListView to a scroll view. Doing so results in poor user
interface performance and a poor user experience.

Defines whether the scrollview should stretch its


android:fillViewport
content to fill the viewport.

java.lang.Object

↳ android.view.View

↳ android.widget.ProgressBar

A user interface element that indicates the progress of an operation. Progress bar
supports two modes to represent progress: determinate, and indeterminate.

Use indeterminate mode for the progress bar when you do not know how long an
operation will take. Indeterminate mode is the default for progress bar and shows a
cyclic animation without a specific amount of progress indicated.

Use determinate mode for the progress bar when you want to show that a specific
quantity of progress has occurred. For example, the percent remaining of a file being
retrieved, the amount records in a batch written to database, or the percent remaining
of an audio file that is playing.

CheckBox is used for adding multiple selections of items from the given set
of options. This is seen used in many android applications for adding a
feature for multiple selections.

RadioGroup is a widget in android which is used to handle multiple radio


buttons within the android application. We can add multiple radio buttons
to our RadioGroup.
Android radio button is a widget that can have more than one option to
choose from.

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginTop="40dp"
android:layout_marginEnd="10dp"
android:gravity="center">

<!--adding a radio button -->


<RadioButton
android:id="@+id/javaRB"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:checked="false"
android:padding="4dp"
android:text="Java"
android:textAlignment="center"
android:textSize="20sp" />

<!--adding a radio button -->


<RadioButton
android:id="@+id/cRB"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:checked="false"
android:padding="4dp"
android:text="C++"
android:textAlignment="center"
android:textSize="20sp" />

<!--adding a radio button -->


<RadioButton
android:id="@+id/pythonRB"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:checked="false"
android:padding="4dp"
android:text="Python"
android:textAlignment="center"
android:textSize="20sp" />

</RadioGroup>

In Android, Toast is used to display information for a period of time.

Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast In Android", T


oast.LENGTH_LONG); // initiate the Toast with context, message and duration for th
e Toast
toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); // set gravity for the Toa
st.
toast.show(); // display the Toast

Inflate the Layout: To use the custom layout with a toast message, you need to inflate the
XML layout file to create a View object in memory

Custom Toast in Android:


In Android, Sometimes simple Toast may not be satisfactory, and then we can go for
customizing a Toast. For creating a custom layout, define a View layout, in XML and
pass the root View object to the setView(View) method.

Step1: Firstly Retrieve the Layout


Inflater with getLayoutInflater() (or getSystemService()) and then inflate the layout
from XML using inflate(int, ViewGroup). In inflate method first parameter is the layout
resource ID and the second is the root View.
Step 2: Create a new Toast with Toast(Context) and set some properties of the Toast,
such as the duration and gravity.
Step 3: Call setView(View) and pass the inflated layout in this method.
Step 4: Display the Toast on the screen using show() method of Toast.

DatePicker dialog is seen used in many android applications where we have


to select the date.
Android provides controls for the user to pick a time or date as ready-to-use dialogs.
These pickers provide controls for selecting each part of the time (hour, minute,
AM/PM) or date (month, day, year).

We recommend you use DialogFragment to host each time or date picker.


The DialogFragment manages the dialog lifecycle for you and lets you display pickers
in different layout configurations
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker.
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

// Create a new instance of TimePickerDialog and return it.


return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {


// Do something with the time the user picks.
}
}

To display a DatePickerDialog using DialogFragment, define a fragment class that


extends DialogFragment and return a DatePickerDialog from the
fragment's onCreateDialog() method.

public static class DatePickerFragment extends DialogFragment


implements DatePickerDialog.OnDateSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker.
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);

// Create a new instance of DatePickerDialog and return it.


return new DatePickerDialog(requireContext(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date the user picks.
}
}

Show the date picker


After you define a DialogFragment like the preceding example, you can display the
date picker by creating an instance of the DialogFragment and calling show().

For example, here's a button that, when tapped, calls a method to show the
dialog:

<Button
android:id="@+id/pickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick date"/>

When the user taps this button, the system calls the following method:

KotlinJava

findViewById<Button>(R.id.pickDate).setOnClickListener {
val newFragment = DatePickerFragment();
newFragment.show(supportFragmentManager, "datePicker");
}

Sure, here are the listeners used in date and time pickers:

### Date Picker Listeners

1. `DatePickerDialog.OnDateSetListener`

### Time Picker Listeners

1. `TimePickerDialog.OnTimeSetListener`

Methods for Creating a Custom Toast

1. Creating the Toast

• Toast.makeText(Context context, CharSequence text, int duration):


Creates a standard toast with the specified duration.
• Toast.makeText(Context context, int resId, int duration): Creates a
standard toast using a string resource for the text.
2. Setting a Custom View

• toast.setView(View view): Sets a custom view to be used as the content


of the Toast.

3. Getting the Current View

• toast.getView(): Returns the current view used in the Toast.

4. Setting the Duration

• toast.setDuration(int duration): Sets the duration for which the Toast


should be shown.

5. Setting the Position

• toast.setGravity(int gravity, int xOffset, int yOffset): Sets the gravity


and the x and y offsets for the Toast.

6. Showing the Toast

• toast.show(): Displays the Toast.

7. Static vs Dynamic: TableLayout is best for static content with known rows and
columns, whereas GridView is suited for dynamic content where the number of
items may vary.
8. Customization: TableLayout allows for more customization of individual cells,
while GridView relies on an adapter to manage its content.
9. Scrolling: GridView inherently supports scrolling if the content exceeds the
screen size, while TableLayout does not and requires additional handling for
scrolling.
UNIT 5
An Intent is a messaging object you can use to request an action from another app
component.

1. explicit intent: Explicit intent can do the specific application


action which is set by the code like changing activity, In explicit
intent user knows about all the things like after clicking a button
which activity will start and Explicit intents are used for
communication inside the application
2. Implicit Intent: Implicit intents do not name a specific
component like explicit intent, instead declare general action to
perform, which allows a component from another app to handle.
For example: when you tap the share button in any app you can see the
Gmail, Bluetooth, and other sharing app options.

Intent Filter
• Implicit intent uses the intent filter to serve the user request.
• The intent filter specifies the types of intents that an activity,
service, or broadcast receiver can respond.
• Intent filters are declared in the Android manifest file.
• Intent filter must contain <action>
Most of the intent filter are describe by its
1. <action>,
2. <category> and
3. <data>.
Examples of common action:
• ACTION_VIEW: Use this action in intent
with startActivity() when you have some information that
activity can show to the user like showing an image in a gallery
app or an address to view in a map app
• ACTION_SEND: You should use this in intent
with startActivity() when you have some data that the user can
share through another app, such as an email app or social
sharing app.
• CATEGORY_BROWSABLE: The target activity allows itself to be
started by a web browser to display data referenced by a link.
Fundamental use case of Intents
Starting Activity
An activity represents the single screen in an app
Starting a Service
A Service is a component that performs operations in the background
without a user interface, which is also called a background process.
Delivering a Broadcast
A broadcast is a message that any app can receive. In android, the
system delivers various broadcast system events like device starts
charging, disable or enable airplane mode, etc.
Broadcast Receivers simply respond to broadcast messages
from other applications or from the system itself. These
messages are sometime called events or intents.

There are following two important steps to make


BroadcastReceiver works for the system broadcasted intents −

• Creating the Broadcast Receiver.


• Registering Broadcast Receiver
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 classMyReceiver 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.

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

</receiver>

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.
Broadcasting Custom Intents

If you want your application itself should generate and send


custom intents then you will have to create and send those
intents by using the sendBroadcast() method inside your activity
class. If you use the sendStickyBroadcast(Intent) method, the
Intent is sticky, meaning the Intent you are sending stays around
after the broadcast is complete.

broadcastIntent(View view) {
public void
Intent intent = new Intent();

intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
sendBroadcast(intent);
}

This intent com.tutorialspoint.CUSTOM_INTENT can also be


registered in similar way as we have regsitered system generated
intent.

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

<intent-filter>
<action
android:name="com.tutorialspoint.CUSTOM_INTENT">
</action>
</intent-filter>

</receiver>
</application>

In Android, Content Providers are a very important component that


serves the purpose of a relational database to store the data of
applications. The role of the content provider in the android system is
like a central repository in which data of the applications are stored

In order to share the data, content providers have certain permissions


that are used to grant or restrict the rights to other applications to
interfere with the data.
Content URI
Content URI(Uniform Resource Identifier) is the key concept of Content
providers. To access the data from a content provider, URI is used as a
query string.
Structure of a Content URI: content://authority/optionalPath/optionalID
Structure of a Content
URI: content://authority/optionalPath/optionalID

Operations in Content Provider


Four fundamental operations are possible in Content Provider
namely Create, Read, Update, and Delete. These operations are often
termed as CRUD operations.
• Create: Operation to create data in a content provider.
• Read: Used to fetch data from a content provider.
• Update: To modify existing data.
• Delete: To remove existing data from the storage.
UI components of android applications like Activity and Fragments use
an object CursorLoader to send query requests
to ContentResolver. The ContentResolver object sends requests (like
create, read, update, and delete) to the ContentProvider as a client.
After receiving a request, ContentProvider process it and returns the
desired result. Below is a diagram to represent these processes in
pictorial form.
<fragment> tag is used to insert the fragment in an android activity
layout. By dividing the activity’s layout multiple fragments can be
added in it.
// Load Vertical Fragment
FragmentManager fragmentManager =
getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
VerticalFragment verticalFragment = new
VerticalFragment();
fragmentTransaction.add(R.id.vertical_fragment_cont
ainer, verticalFragment);
fragmentTransaction.commit();

// Load Horizontal Fragment


FragmentTransaction horizontalFragmentTransaction =
fragmentManager.beginTransaction();
HorizontalFragment horizontalFragment = new
HorizontalFragment();
horizontalFragmentTransaction.add(R.id.horizontal_f
ragment_container, horizontalFragment);
horizontalFragmentTransaction.commit();

Types of Android Fragments

1. Single Fragment: Display only one single view on the device


screen. This type of fragment is mostly used for mobile phones.
2. List Fragment: This Fragment is used to display a list-view from
which the user can select the desired sub-activity. The menu
drawer of apps like Gmail is the best example of this kind of
fragment.
3. Fragment Transaction: This kind of fragments supports the
transition from one fragment to another at run time. Users can
switch between multiple fragments like switching tabs.

Description
Methods

The very first method to be called when the fragment


has been associated with the activity. This method
executes only once during the lifetime of a fragment.
onAttach() When we attach fragment(child) to Main(parent) activity
then it call first and then not call this method any
time(like you run an app and close and reopen) simple
means that this method call only one time.

This method initializes the fragment by adding all the


onCreate()
required attributes and components.

System calls this method to create the user interface of


the fragment. The root of the fragment’s layout is
onCreateView() returned as the View component by this method to draw
the UI.
You should inflate your layout in onCreateView but
Description
Methods

shouldn’t initialize other views using findViewById in


onCreateView.

It indicates that the activity has been created in which


onViewCreated() the fragment exists. View hierarchy of the fragment also
instantiated before this function call.

The system invokes this method to make the fragment


onStart()
visible on the user’s device.

This method is called to make the visible fragment


onResume()
interactive.

It indicates that the user is leaving the fragment. System


onPause() call this method to commit the changes made to the
fragment.

Method to terminate the functioning and visibility of


onStop()
fragment from the user’s screen.

System calls this method to clean up all kinds of


resources as well as view hierarchy associated with the
onDestroyView()
fragment. It will call when you can attach new fragment
and destroy existing fragment Resoruce

It is called to perform the final clean up of fragment’s


onDestroy()
state and its lifecycle.

The system executes this method to disassociate the


fragment from its host activity.
onDetach()
It will call when your fragment Destroy(app crash or
attach new fragment with existing fragment)
Services in Android are a special component that facilitates an
application to run in the background in order to perform long-running
operation tasks.

Further, application components can bind itself to service to carry


out inter-process communication(IPC). There is a major difference
between android services and threads, one must not be confused
between the two. Thread is a feature provided by the Operating
system to allow the user to perform operations in the background.
While service is an android component that performs a long-running
operation about which the user might not be aware of as it does not
have UI.

Foreground Services:
Services that notify the user about its ongoing operations are termed as
Foreground Services.
Background services do not require any user intervention. These services
do not notify the user about ongoing background tasks and users also
cannot access them. The process like schedule syncing of data or storing
of data fall under this service.
3. Bound Services:
This type of android service allows the components of the application
like activity to bound themselves with it. Bound services perform their
task as long as any application component is bound to it. More than one
component is allowed to bind themselves with a service at a time. In
order to bind an application component with a
service bindService() method is used.
The Life Cycle of Android Services

The Life Cycle of Android Services


In android, services have 2 possible paths to complete its life cycle
namely Started and Bounded.
1. Started Service (Unbounded Service):
By following this path, a service will initiate when an application
component calls the startService() method. Once initiated, the service
can run continuously in the background even if the component is
destroyed which was responsible for the start of the service. Two option
are available to stop the execution of service:
• By calling stopService() method,
• The service can stop itself by using stopSelf() method.
2. Bounded Service:
It can be treated as a server in a client-server interface. By following this
path, android application components can send requests to the service
and can fetch results. A service is termed as bounded when an
application component binds itself with a service by
calling bindService() method. To stop the execution of this service, all
the components must unbind themselves from the service by
using unbindService() method.
MediaPlayer class
The android.media.MediaPlayer class is used to control the audio or video files.

videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// Code to execute when the video finishes playing
}
});

• Text-to-Speech (TTS): Converts text to spoken words using the TextToSpeech


class.
• Speech-to-Text (STT): Converts spoken words to text using RecognizerIntent
and SpeechRecognizer.
SQLite:

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

The main package is android.database.sqlite


package com.example.myapp;

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "example.db";

private static final int DATABASE_VERSION = 1;

// Table creation SQL statement

private static final String TABLE_CREATE =

"CREATE TABLE users (" +

"id INTEGER PRIMARY KEY AUTOINCREMENT, " +

"name TEXT NOT NULL, " +

"age INTEGER, " +

"email TEXT UNIQUE);";

public MyDatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);


}

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(TABLE_CREATE);

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS users");

onCreate(db);

In order to create the database:

SQLiteDatabase mydatabase = openOrCreateDatabase("your database


name",MODE_PRIVATE,null);

Creating and connecting to an SQLite database in Android involves using the


SQLiteOpenHelper class to manage database creation and version management.
Below is a step-by-step guide to set this up in an Android application.
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');");

Data Types in SQLite


SQLite supports the following storage classes (data types):
1. NULL: The value is a NULL value.
2. INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes
depending on the magnitude of the value.
3. REAL: The value is a floating-point value, stored as an 8-byte IEEE floating
point number.
4. TEXT: The value is a text string, stored using the database encoding (UTF-8,
UTF-16BE, or UTF-16LE).
5. BLOB: The value is a blob of data, stored exactly as it was input.

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

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.

• beginTransaction(): Starts a new transaction.


• setTransactionSuccessful(): Marks the current transaction as successful. This
must be called before endTransaction().
• endTransaction(): Ends the current transaction. If the transaction was marked as
successful, changes are committed. Otherwise, they are rolled back.

Ensure consistencyyyyy……………
UNIT 6
In Android, you can use SmsManager API or devices Built-in SMS
application to send SMS's.

SmsManager API

SmsManager smsManager = SmsManager.getDefault();


smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

Built-in SMS application

Intent sendIntent = new Intent(Intent.ACTION_VIEW);


sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

Of course, both need SEND_SMS permission.

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

Sign your app

Android requires that all APKs be digitally signed with a certificate before they
are installed on a device or updated. When releasing using Android App
Bundles, you need to sign your app bundle with an upload key before
uploading it to the Play Console, and Play App Signing takes care of the rest. For
apps distributing using APKs on the Play Store or on other stores, you must
manually sign your APKs for upload.

he following is a high-level overview of the steps you might need to take to sign
and publish a new app to Google Play:

1. Generate an upload key and keystore

2. Sign your app with your upload key

3. Configure Play App Signing

4. Upload your app to Google Play

5. Prepare & roll out release of your app


If instead your app is already published to the Google Play Store with an
existing app signing key, or you would like to choose the app signing key for a
new app instead of having Google generate it, follow these steps:

1. Sign your app with your app’s signing key.

2. Upload your app’s signing key to Play App Signing.

3. (Recommended) Generate and register an upload certificate for future updates


to your app

4. Upload your app to Google Play

5. Prepare & roll out release of your app

Step 1: Make a Developer Account

The account can be created in four simple steps:

1. Sign-In with Your Google Account


2. Accept Terms
3. Pay Registration Fee of $25.

Step 2: After you completed step 1 you will be redirected to this page
where you have to click on the CREATE APPLICATION button.

Once you click on it a pop up will be shown like this where you have to
choose your Default language and Title of your app. Then click on
the CREATE button.

Step 3: Store listing


After you completed step 2 you will be redirected to this page where you
have to provide the Short description and Full description of your App.
Then u need to hire icons for ur app

Then you have to provide the Screenshots of your app.

Ant next thing you have to provide is the Feature Graphic of your app.

Then come to Categorization part where you have to provide


your Application type and Category of your app.
Then come to Contact details part where you have to provide
your Website(if any), email, and Phone of yours.

And finally when you click on SAVE DRAFT button you can see
that Store listing tab is now become turned to green and you are done
for Store listing.

Step 4: App release


After completing step 3 go to App releases then scroll down
to Production track and click on MANAGE button.

After redirecting to the next page click on the CREATE RELEASE button.

After that on the next page, you have to upload your APK file in Android
App Bundles and APKs to add section.

After that simply click on the SAVE button.

..various steps

And after answering them correctly don’t forget to click on SAVE


QUESTIONNAIRE button.

Step 6: Pricing & distribution


Then go to the Pricing & distribution section. Then select the country in
which you want to available your app.
Step 7: App content
Then come to the App content section. And in the Privacy policy section
click on the Start button.

And then provide a valid Privacy policy URL. Note that google will
check this.

And finally, on the next page click on the START ROLLOUT TO


PRODUCTION button to send your app to review. And you are finally
done.

After usually 4 to 5 days they will review your app and let you know to
either approve or reject your app.
Android application run in android sandboxxx.

To achieve these objectives, Android provides these key security features:

• Robust security at the OS level through the Linux kernel

• Mandatory app sandbox for all apps

• Secure interprocess communication

• App signing

• App-defined and user-granted permissions

Using permissions in android:


<!-- Permissions -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:permission="your.namespace.permission.TEST" >

Custom permission recommendations

You can define custom permissions for your apps and request custom
permissions from other apps by defining <uses-permission> elements. However,
carefully assess whether it is necessary to do so.

Create a permission group

As shown in the previous section, you can use


the android:permissionGroup attribute to help the system describe permissions to
the user. In most cases, you set this to a standard system group (listed
in android.Manifest.permission_group), but you can also define your own group
with <permission-group>.

The <permission-group> element defines a label for a set of permissions—both


those declared in the manifest with <permission> elements and those declared
elsewhere. This affects only how the permissions are grouped when presented
to the user. The <permission-group> element doesn't specify the permissions that
belong to the group, but it gives the group a name.
You can place a permission in the group by assigning the group name to
the <permission> element's permissionGroup attribute.

The <permission-tree> element declares a namespace for a group of permissions


that are defined in code.

You might also like