0% found this document useful (0 votes)
34 views47 pages

Android UNIT 3

Uploaded by

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

Android UNIT 3

Uploaded by

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

UNIT 3

ARRAY ADAPTER
An adapter basically connects the User Interfaces and the Data Source. It
converts data from the data sources into view items that can be displayed into
the UI Component. Data Source can be Arrays, HashMap, Database, etc. and
UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the
most commonly used adapter in android. When you have a list of single type
items which are stored in an array you can use ArrayAdapter. The array
adapter uses Object.toString() for each data object to create a view, and
then place the result in a TextView. This type of android adapter is used for
ListView, GridView or Spinner.
ArrayAdapter is a class and can have various types of Constructors, those
constructors are mentioned below:

 ArrayAdapter( Context context, int resource)


 ArrayAdapter( Context context, int resource, int textViewResourceId)
 ArrayAdapter( Context context, int resource, T[] objects)
 ArrayAdapter( Context context, int resource, textViewResourceId, T[]
objects)
 ArrayAdapter( Context context, int resource, List<T> objects)
 ArrayAdapter( Context context, int resource, int textViewResourceId,
List<T> objects)

To include it we can use ArrayAdapter as follows:

public ArrayAdapter(this, int resource, int textViewResourceId, T[] objects)]

Description
Parameter

context current context

Resource the resource ID for a layout file

objects objects to display in the ListView


Example

In this example, the list of courses is displayed using a simple array


adapter. Note that we are going to implement this project using
the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a
New Project in Android Studio. Note that select Java as the programming
language.
Step 2: Working with the activity_main.xml file
Go to the layout folder and in activity_main.xml file change
the ConstraintLayout to RelativeLayout and insert a ListView with id
simpleListView. Below is the code for the activity_main.xml file.

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

<RelativeLayout

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<ListView

android:id="@+id/simpleListView"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

</RelativeLayout>

Step 3: Create a new layout file


Go to app > res > layout > right-click > New > Layout Resource File and
create a new layout file and name this file as item_view.xml and make the root
element as a LinearLayout. This will contain a TextView that is used to display
the array objects as output.
<?xml version="1.0" encoding="utf-8"?>

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<TextView

android:id="@+id/itemTextView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_gravity="center" />

</LinearLayout>

Step 4: Working with the MainActivity.java file


Now go to the java folder and in MainActivity.java and provide the
implementation to the ArrayAdapter. Below is the code for
the MainActivity.java file.
import android.os.Bundle;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

ListView simpleListView;

// array objects

String courseList[] = {"C-Programming", "Data Structure", "Database", "Python",

"Java", "Operating System", "Compiler


Design", "Android Development"};
@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

simpleListView = (ListView) findViewById(R.id.simpleListView);

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,

R.layout.item_view, R.id.itemTextView, courseList);

simpleListView.setAdapter(arrayAdapter);

OUTPUT

There are certain methods of Adapter class that are mentioned below:

 getCount() – This method represents the number of items present in the


data set.
 hasStableIds() – This method indicates whether the Item Ids are stable
under changes on the underlying data.
 getItem(int position) – This method gets the data item associated with a
particular position in the data set.
 getItemId(int position) – This method gets the Id of the item associated
with a particular position in the list.
 getViewTypeCount() – This method returns the number of types of Views
created using getView().
 getItemViewType(int position) – This method gets the type of View that
would be created using the getView() method.
 getView(int position, View convertView, ViewGroup parent) – This method
displays the data at a position in the data set.
 registerDataSetObserver(DataSetObserver observer) – This method
registers the observer that is called when the changes in the data occur.
 unregisterDataSetObserver(DataSetObserver observer) – This method
unregisters the observer that was registered using the
registerDataSetObserver(DataSetObserver observer) method.

ListView
A ListView is a type of AdapterView that displays a vertical list of scroll-able
views and each view is placed one below the other. Using adapter, items are
inserted into the list from an array or database. For displaying the items in the
list method setAdaptor() is used. Android ListView is a ViewGroup that is used
to display the list of items in multiple rows and contains an adapter that
automatically inserts the items into the list.
The main purpose of the adapter is to fetch data from an array or database and
insert each item that placed into the list for the desired result.

XML Attributes of ListView

Attribute Description

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

android:dividerHeight Divider’s height.

android:entries Reference to an array resource that will


Attribute Description

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

How to add a ListView in an Android App

Step 1: Create a new project


1. Click on File, then New => New Project.
2. Choose “Empty Activity” for the project template.
3. Select language as Java.
4. Select the minimum SDK as per your need.
Step 2: Modify activity_main.xml file
Add a ListView in the activity_main.xml file.
Step 3: Modify MainActivity.java file

LIST ACTIVITY
ListActivity is a subclass of Activity that includes a ListView object.
Through ListActivity class you can create an activity in your Android application that can
be connected to different data sources (query cursor or arrays) and can be displayed as a
set of list items on the screen. Actually, the use of the ListActivity class provides us a
more simplified way of handling the list of items because it contains a ListView by default.

Example of list activity


<LinearLayout

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

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

android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".MainActivity">

<ListView

android:id="@+id/simpleListView"

android:layout_width="match_parent"

android:layout_height="wrap_content" />

</LinearLayout>

Mainactivity.java
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MyListActivity extends ListActivity {

// Sample data for the list


private static final String[] items = {"Item 1", "Item 2", "Item 3", "Item
4"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Set the adapter to populate the ListView


ArrayAdapter<String> adapter = new ArrayAdapter<string>(this,
android.R.layout.simpleListView, items);
setListAdapter(adapter);
}

@Override
protected void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);

// Handle item click


String selectedItem = (String) getListAdapter().getItem(position);
Toast.makeText(this, "You clicked: " + selectedItem,
Toast.LENGTH_SHORT).show();
}
}
BASE ADAPTER
In Android programming, a BaseAdapter is a fundamental class that is used to
build unique adapters for different UI widgets like ListView, GridView, and others
that are built on AdapterView. It offers a fundamental framework on which you
can construct your own unique adapter to give the data for these UI components.
The functions of a BaseAdapter are summarised as follows:
 Data management: It controls the data source. The BaseAdapter receives
the data (for instance, an array of items), and it knows how to retrieve and
send this data to the UI component.
 VIEW CREATION: The creation of views for each item in your data source is
aided by this. These views provide your data a visual representation.
 View Recycling: BaseAdapter recycles views that are no longer displayed on
the page to improve speed.
 Count and Position: It keeps track of the number of items in your data source and the
position of each item.

List view using base adapters


3. In your main layout file (e.g., activity_main.xml), add a ListView:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MAIN ACTIVITY.JAVA
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

private String[] names = {"Alice", "Bob", "Charlie", "David", "Eva"};

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

ListView listView = findViewById(R.id.listView);


MyAdapter adapter = new MyAdapter();
listView.setAdapter(adapter);
}

private class MyAdapter extends BaseAdapter {

@Override
public int getCount() {
return names.length;
}

@Override
public Object getItem(int position) {
return names[position];
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView =
LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item, parent, false);
}
TextView textView = convertView.findViewById(R.id.textView);
textView.setText(names[position]);

return convertView;
}
}
}

GRID VIEW USING BASE ADAPTER


3. In your main layout file (e.g., activity_main.xml), add a GridView:

<!-- res/layout/activity_main.xml -->


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:columnWidth="100dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"/>
</LinearLayout>
MAIN ACTIVITY.JAVA
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

public class MainActivity extends Activity {

private String[] colors = {"Red", "Green", "Blue", "Yellow", "Orange",


"Purple"};

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

GridView gridView = findViewById(R.id.gridView);


MyAdapter adapter = new MyAdapter();
gridView.setAdapter(adapter);
}

private class MyAdapter extends BaseAdapter {

@Override
public int getCount() {
return colors.length;
}

@Override
public Object getItem(int position) {
return colors[position];
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView =
LayoutInflater.from(MainActivity.this).inflate(R.layout.grid_item, parent, false);
}

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


textView.setText(colors[position]);

return convertView;
}
}
}

CUSTOM TABS
Creating custom tabs in Android can be a useful way to implement tabbed navigation in your
app with a unique design or behavior. To create custom tabs, you'll typically use a combination
of views, layouts, and view pager for swappable tab content. In Android programming, the term
"custom tabs" refers to the capability of designing and styling tabbed user interfaces in Android
applications. An app's content and navigation can be organized using tabs, a standard UI
component. Although custom tabs provide developers complete control over the look and
behavior of tabs, Android comes with a default Tab Layout widget that makes the
implementation of tabs easier.

Implementation of Custom Chrome Tabs in Android


Step 1: Create a New Project
Step 2: Add dependency to build.gradle(Module:app)
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below
dependency in the dependencies section.
implementation ‘androidx.browser:browser:1.2.0’
Now sync option will appear at the top right corner click on the sync now option.
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the
code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/idBtnCustomChromeTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Custom Chrome Tabs" />

</RelativeLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the
code for the MainActivity.java file. Comments are added inside the code to
understand the code in more detail.
Main.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

Button Btn;

// url for loading in custom chrome tab


String url = "https://www.geeksforgeeks.org/";

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

// initializing button for opening custom chrome tabs.


Btn = findViewById(R.id.idBtn);
Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// initializing object for custom chrome tabs.
CustomTabsIntent.Builder customIntent = new
CustomTabsIntent.Builder();

// below line is setting toolbar color


// for our custom chrome tab.

customIntent.setToolbarColor(ContextCompat.getColor(MainActivity.this,
R.color.purple_200));

// we are calling below method after


// setting our toolbar color.
openCustomTab(MainActivity.this,
customIntent.build(), Uri.parse(url));
}
});
}

public static void openCustomTab(Activity activity, CustomTabsIntent


customTabsIntent, Uri uri) {
// package name is the default package
// for our custom chrome tab
String packageName = "com.android.chrome";
if (packageName != null) {

// we are checking if the package name is not null


// if package name is not null then we are calling
// that custom chrome tab with intent by passing its
// package name.
customTabsIntent.intent.setPackage(packageName);

// in that custom tab intent we are passing


// our url which we have to browse.
customTabsIntent.launchUrl(activity, uri);
} else {
// if the custom tabs fails to load then we are simply
// redirecting our user to users device default browser.
activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
}
}

STRING ARRAY
A string array is a data structure used in Android programming that contains an
organized group of strings. A list of string values or other resources that you want
to use in your Android application are frequently stored there. String arrays are
widely used for a variety of things, including establishing resource names,
populating spinner widgets, showing menu items, and more.
Define a String Array in res/values/strings.xml:
Open the res/values/strings.xml file and define your string array inside the
<resources> section. For example:
<resources>
<string-array name="my_string_array">
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
<!-- Add more items as needed -->
</string-array>
</resources>

Main.java
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


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

// Access the string array from resources


Resources resources = getResources();
String[] myStringArray = resources.getStringArray(R.array.my_string_array);
// Iterate through the string array and log each item
for (String item : myStringArray) {
Log.d("MyApp", item);
}
}
}

Creating list
Same as list view

THREADS
In Android programming, threads are used to perform tasks, allowing your app to
remain responsive and avoid freezing or lagging. Threads are essential for handling
time-consuming operations, such as network requests or heavy computations, without
blocking the main thread. Android provides several mechanisms for working with
threads:

1. UI Thread (Main Thread): The UI thread, also known as the main thread, is the primary
thread in an Android application responsible for handling the user interface and its
interactions. All user interface components, such as UI widgets and views, are created,
updated, and interacted with on this thread. It's crucial to keep the UI thread responsive,
as any long-running or blocking operations on this thread can lead to the app
becoming unresponsive and potentially causing an Application Not Responding (ANR)
error.
BACKGROUND THREAD: In Android programming, a background thread is any thread that is
not the main UI thread (also known as the main thread). Background threads are used to
perform tasks that are not directly related to the user interface, such as network requests, file
I/O, data processing, or any operation that might take a significant amount of time to complete.
Using background threads is essential to prevent blocking the UI thread, which could result in an
unresponsive or frozen user interface.

AsyncTaskLoader: This is an Android-specific component designed for loading data


asynchronously and delivering the result to an Activity or Fragment. It simplifies data
loading and ensures that the data is loaded efficiently without blocking the UI thread.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<!-- Display the result text -->


<TextView
android:id="@+id/result_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result will appear here"
android:textSize="25sp" />

<!-- Start button -->


<Button
android:id="@+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
</LinearLayout>
MAIN.JAVA
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private TextView resultTextView;

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

// Get reference to start button and result text view


Button startButton = findViewById(R.id.start_button);
resultTextView = findViewById(R.id.result_text_view);

// Set an OnClickListener for the start button


startButton.setOnClickListener(view -> new
BackgroundTask().execute());
}
// BackgroundTask inner class to perform the background task
private class BackgroundTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
// Perform background task
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Task Completed";
}

@Override
protected void onPostExecute(String result) {
// Update UI with the results
resultTextView.setText(result);
}
}
}
MULTI THREADING
Working on multiple tasks at the same time is Multitasking. In the same way,
multiple threads running at the same time in a machine is called Multi-
Threading. It allows an app to perform multiple tasks simultaneously, improving performance
and responsiveness.

Run on UI Thread
"Run on UI thread" refers to the action of executing a piece of code on the UI thread, even if
that code is currently running on a background thread. This is necessary when you need to
update the user interface because UI updates should always be performed on the UI thread to
ensure a smooth and responsive user experience. There are methods and mechanisms provided
in Android, such as runOnUiThread() and Handler, that allow you to perform tasks for
execution on the UI thread from a background thread.

Worker thread
In Android programming, a worker thread is a thread specifically designated to perform
background tasks, such as lengthy computations, network operations, or other I/O-bound
operations. The primary purpose of worker threads is to offload work from the main UI thread
(also known as the main thread) to ensure that the user interface remains responsive and
doesn't become blocked during time-consuming operations.

Handler:

A Handler is an Android class that provides a mechanism for scheduling and executing
code on a specific thread. It is often used to perform tasks on the main/UI thread or
other background threads.

A Handler is associated with a particular Looper, which represents a message loop for a
thread. The main/UI thread already has a Looper, so you can create a Handler for it
directly. For background threads, you can create a Handler associated with a
HandlerThread or other custom threads.

The primary function of a Handler is to post Runnable tasks for execution on a thread's
message queue. These tasks are typically implemented as anonymous inner classes that
implement the Runnable interface.
Handler mainHandler = new
Handler(Looper.getMainLooper());

mainHandler.post(new Runnable() {
@Override
public void run() {
// Code to update the UI here
}
});
RUNNABLE
In Android, a Runnable is a fundamental interface used to represent a block of code that can be
executed on a separate thread. Runnable instances are commonly used to perform background
tasks or execute code asynchronously without blocking the main/UI thread, thus ensuring the
responsiveness of the user interface. You create a Runnable by implementing its run()
method, which contains the code you want to execute. This code typically represents the
background task you want to perform.

Runnable myRunnable = new Runnable() {


@Override
public void run() {
// Code to execute in the background
}
};
You can pass data to a Runnable by declaring variables within the surrounding scope as final.
This allows the Runnable to access these variables when it's executed. This is especially useful
for passing data or configuration to the background task.

final String message = "Hello, Android!";

Runnable myRunnable = new Runnable() {


@Override
public void run() {
// Access message here
}
};
ASYNC TASK
Android has a class called AsyncTask that offers a practical
method for running background processes and updating the user
interface (UI) thread with the outcomes. It is perfect for actions
like network requests, database operations, and other time-
consuming procedures since it enables you to run code in the
background without stopping the UI thread. The basic methods used in
an android AsyncTask class are defined below :

 doInBackground() : This method contains the code which needs to be executed in


background. In this method we can send results multiple times to the UI thread by
publishProgress() method. To notify that the background processing has been
completed we just need to use the return statements
 onPreExecute() : This method contains the code which is executed before the
background processing starts
 onPostExecute() : This method is called after doInBackground method completes
processing. Result from doInBackground is passed to this method
 onProgressUpdate() : This method receives progress updates from doInBackground
method, which is published via publishProgress method, and this method can use this
progress update to update the UI thread

The three generic types used in an android AsyncTask class are given below :

 Params : The type of the parameters sent to the task upon execution
 Progress : The type of the progress units published during the background computation
 Result : The type of the result of the background computation

SENSORS

Sensors are hardware elements that let your app collect


information about the environment or movements of an Android
device. Different kinds of sensors that can detect changes in
light, motion, orientation, and other factors are included in
Android smartphones. From fitness trackers to augmented
reality experiences, you may access and use these sensors to
build a variety of applications. Android provides sensor api to work with
different types of sensors.

Types of Sensors
Android supports three types of sensors:

1) Motion Sensors

These are used to measure acceleration forces and rotational forces along with three
axes.

2) Position Sensors

These are used to measure the physical position of device.

3) Environmental Sensors

These are used to measure the environmental changes such as temperature, humidity
etc.
4 Gyroscope Sensor:
 Measures angular velocity around the device's three axes.
 Used for precise motion tracking and orientation detection in 3D space.
5 Magnetometer (Compass) Sensor:
 Measures the strength and direction of the magnetic field around the device.
 Used for determining the device's orientation relative to the Earth's magnetic
field and for implementing compass apps.
6 Proximity Sensor:
 Detects when an object is close to the device (usually used for detecting when
the user's face is near during phone calls to turn off the screen).
 Often used to implement "pocket mode" to prevent accidental touch input.
7 Light Sensor:
8 Measures ambient light levels.
9 Used to automatically adjust screen brightness based on lighting conditions and
for detecting changes in lighting.

USING ORIENTATION

To obtain the orientation of a device in Android using sensors, you typically combine data from
the accelerometer and magnetometer (compass) sensors. The orientation is represented as
azimuth, pitch, and roll angles, which describe the device's orientation along its yaw, pitch, and
roll axes, respectively

ACCELEROMETER

The accelerometer sensor in Android is a hardware component that measures the acceleration
of the device along its three primary axes: X, Y, and Z. It provides data related to the device's
motion and orientation changes. Accelerometers are commonly used in various applications,
including games, fitness tracking, screen rotation, and gesture recognition.

TELEPHONY
The android.telephony.TelephonyManager class provides information about the telephony
services such as subscriber id, sim serial number, phone network type etc. Moreover, you can
determine the phone state etc. IN Android programming, you can implement telephony services
to interact with the phone's telephony features such as making calls, sending SMS messages,
and monitoring phone state. To work with telephony services in Android, you typically use the
TelephonyManager class and request the necessary permissions in your AndroidManifest.xml
file.

activity_main.xml

Drag one textview from the pallete, now the xml file will look like this.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="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:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="38dp"
18. android:layout_marginTop="30dp"
19. android:text="Phone Details:" />
20.
21. </RelativeLayout>

Activity class

Now, write the code to display the information about the telephony services.

File: MainActivity.java

1. package com.javatpoint.telephonymanager;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.content.Context;
6. import android.telephony.TelephonyManager;
7. import android.view.Menu;
8. import android.widget.TextView;
9.
10. public class MainActivity extends Activity {
11. TextView textView1;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. textView1=(TextView)findViewById(R.id.textView1);
18.
19. //Get the instance of TelephonyManager
20. TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVI
CE);
21.
22. //Calling the methods of TelephonyManager the returns the information
23. String IMEINumber=tm.getDeviceId();
24. String subscriberID=tm.getDeviceId();
25. String SIMSerialNumber=tm.getSimSerialNumber();
26. String networkCountryISO=tm.getNetworkCountryIso();
27. String SIMCountryISO=tm.getSimCountryIso();
28. String softwareVersion=tm.getDeviceSoftwareVersion();
29. String voiceMailNumber=tm.getVoiceMailNumber();
30.
31. //Get the phone type
32. String strphoneType="";
33.
34. int phoneType=tm.getPhoneType();
35.
36. switch (phoneType)
37. {
38. case (TelephonyManager.PHONE_TYPE_CDMA):
39. strphoneType="CDMA";
40. break;
41. case (TelephonyManager.PHONE_TYPE_GSM):
42. strphoneType="GSM";
43. break;
44. case (TelephonyManager.PHONE_TYPE_NONE):
45. strphoneType="NONE";
46. break;
47. }
48.
49. //getting information if phone is in roaming
50. boolean isRoaming=tm.isNetworkRoaming();
51.
52. String info="Phone Details:\n";
53. info+="\n IMEI Number:"+IMEINumber;
54. info+="\n SubscriberID:"+subscriberID;
55. info+="\n Sim Serial Number:"+SIMSerialNumber;
56. info+="\n Network Country ISO:"+networkCountryISO;
57. info+="\n SIM Country ISO:"+SIMCountryISO;
58. info+="\n Software Version:"+softwareVersion;
59. info+="\n Voice Mail Number:"+voiceMailNumber;
60. info+="\n Phone Network Type:"+strphoneType;
61. info+="\n In Roaming? :"+isRoaming;
62.
63. textView1.setText(info);//displaying the information in the textView
64. }
65.
66.
67. }
AndroidManifest.xml

You need to provide READ_PHONE_STATE permission in the AndroidManifest.xml file.

File: AndroidManifest.xml

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


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.javatpoint.telephonymanager"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="17" />
10.
11. <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@drawable/ic_launcher"
16. android:label="@string/app_name"
17. android:theme="@style/AppTheme" >
18. <activity
19. android:name="com.javatpoint.telephonymanager.MainActivity"
20. android:label="@string/app_name" >
21. <intent-filter>
22. <action android:name="android.intent.action.MAIN" />
23.
24. <category android:name="android.intent.category.LAUNCHER" />
25. </intent-filter>
26. </activity>
27. </application>
28.
29. </manifest>
download this android example

Output:

CAMERA

In Android programming, you can use the Camera service to access and interact with the
device's camera hardware to capture photos and record videos. The Android Camera API has
undergone significant changes over the years, with the older Camera API (Camera1) being
replaced by the Camera2 API, which provides more control and flexibility

You must declare the camera permission in your AndroidManifest.xml file and request it at
runtime if your app targets Android 6.0 (API level 23) or higher: You can access the
CameraManager system service to interact with the camera hardware. This service provides
information about available cameras and allows you to open a camera device.

Android camera app example by camera intent


In this example, we are writing the simple code to capture image using camera and
displaying the image using imageview.

activity_main.xml

Drag one imageview and one button from the pallete, now the xml file will look like this:
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="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. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentBottom="true"
12. android:layout_centerHorizontal="true"
13. android:text="Take a Photo" >
14. </Button>
15.
16. <ImageView
17. android:id="@+id/imageView1"
18. android:layout_width="fill_parent"
19. android:layout_height="fill_parent"
20. android:layout_above="@+id/button1"
21. android:layout_alignParentTop="true"
22. android:src="@drawable/ic_launcher" >
23. </ImageView>
24. </RelativeLayout>

Activity class

Let's write the code to capture image using camera and displaying it on the image view.

File: MainActivity.java

1. package com.example.simplecamera;
2.
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.graphics.Bitmap;
6. import android.os.Bundle;
7. import android.view.Menu;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.ImageView;
11.
12. public class MainActivity extends Activity {
13. private static final int CAMERA_REQUEST = 1888;
14. ImageView imageView;
15. public void onCreate(Bundle savedInstanceState) {
16.
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. imageView = (ImageView) this.findViewById(R.id.imageView1);
21. Button photoButton = (Button) this.findViewById(R.id.button1);
22.
23. photoButton.setOnClickListener(new View.OnClickListener() {
24.
25. @Override
26. public void onClick(View v) {
27. Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTU
RE);
28. startActivityForResult(cameraIntent, CAMERA_REQUEST);
29. }
30. });
31. }
32.
33. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
34. if (requestCode == CAMERA_REQUEST) {
35. Bitmap photo = (Bitmap) data.getExtras().get("data");
36. imageView.setImageBitmap(photo);
37. }
38. }
39.
40. @Override
41. public boolean onCreateOptionsMenu(Menu menu) {
42. // Inflate the menu; this adds items to the action bar if it is present.
43. getMenuInflater().inflate(R.menu.activity_main, menu);
44. return true;
45. }
46.
47. }

download this android example

Output:

Bluetooth
Bluetooth is a way to exchange data with other devices wirelessly. Android provides
Bluetooth API to perform several tasks such as:

o scan bluetooth devices


o connect and transfer data from and to other devices
o manage multiple connections etc.

ndroid Bluetooth Example: enable, disable and make


discovrable bluetooth programmatically
You need to write few lines of code only, to enable or disable the bluetooth.

activity_main.xml

Drag one textview and three buttons from the pallete, now the activity_main.xml file will
like this:

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="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. tools:context=".MainActivity" >
6.
7. <TextView android:text=""
8. android:id="@+id/out"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content">
11. </TextView>
12. <Button
13. android:id="@+id/button1"
14. android:layout_width="wrap_content"
15. android:layout_height="wrap_content"
16. android:layout_alignParentLeft="true"
17. android:layout_alignParentTop="true"
18. android:layout_marginLeft="30dp"
19. android:layout_marginTop="49dp"
20. android:text="TURN_ON" />
21.
22. <Button
23. android:id="@+id/button2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_alignLeft="@+id/button1"
27. android:layout_below="@+id/button1"
28. android:layout_marginTop="27dp"
29. android:text="DISCOVERABLE" />
30.
31. <Button
32. android:id="@+id/button3"
33. android:layout_width="wrap_content"
34. android:layout_height="wrap_content"
35. android:layout_alignLeft="@+id/button2"
36. android:layout_below="@+id/button2"
37. android:layout_marginTop="28dp"
38. android:text="TURN_OFF" />
39.
40. </RelativeLayout>

Provide Permission

You need to provide following permissions in AndroidManifest.xml file.

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


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

The full code of AndroidManifest.xml file is given below.

File: AndroidManifest.xml

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


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.example.bluetooth"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="16" />
10.
11. <uses-permission android:name="android.permission.BLUETOOTH" />
12. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
13.
14. <application
15. android:allowBackup="true"
16. android:icon="@drawable/ic_launcher"
17. android:label="@string/app_name"
18. android:theme="@style/AppTheme" >
19. <activity
20. android:name="com.example.bluetooth.MainActivity"
21. android:label="@string/app_name" >
22. <intent-filter>
23. <action android:name="android.intent.action.MAIN" />
24.
25. <category android:name="android.intent.category.LAUNCHER" />
26. </intent-filter>
27. </activity>
28. </application>
29.
30. </manifest>

Activity class

Let's write the code to enable, disable and make bluetooth discoverable.

File: MainActivity.java
1. package com.example.bluetooth;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.app.Activity;
6. import android.bluetooth.BluetoothAdapter;
7. import android.content.Context;
8. import android.content.Intent;
9. import android.os.Bundle;
10. import android.util.Log;
11. import android.view.View;
12. import android.widget.Button;
13. import android.widget.TextView;
14. import android.widget.Toast;
15.
16. public class MainActivity extends Activity {
17. private static final int REQUEST_ENABLE_BT = 0;
18. private static final int REQUEST_DISCOVERABLE_BT = 0;
19. @Override
20. protected void onCreate(Bundle savedInstanceState) {
21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.activity_main);
23. final TextView out=(TextView)findViewById(R.id.out);
24. final Button button1 = (Button) findViewById(R.id.button1);
25. final Button button2 = (Button) findViewById(R.id.button2);
26. final Button button3 = (Button) findViewById(R.id.button3);
27. final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
28. if (mBluetoothAdapter == null) {
29. out.append("device not supported");
30. }
31. button1.setOnClickListener(new View.OnClickListener() {
32. public void onClick(View v) {
33. if (!mBluetoothAdapter.isEnabled()) {
34. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
35. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
36. }
37. }
38. });
39. button2.setOnClickListener(new View.OnClickListener() {
40. @Override
41. public void onClick(View arg0) {
42. if (!mBluetoothAdapter.isDiscovering()) {
43. //out.append("MAKING YOUR DEVICE DISCOVERABLE");
44. Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOVERABLE",
45. Toast.LENGTH_LONG);
46.
47. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERAB
LE);
48. startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
49.
50. }
51. }
52. });
53. button3.setOnClickListener(new View.OnClickListener() {
54. @Override
55. public void onClick(View arg0) {
56. mBluetoothAdapter.disable();
57. //out.append("TURN_OFF BLUETOOTH");
58. Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGTH_L
ONG);
59.
60. }
61. });
62. }
63.
64. @Override
65. public boolean onCreateOptionsMenu(Menu menu) {
66. // Inflate the menu; this adds items to the action bar if it is present.
67. getMenuInflater().inflate(R.menu.activity_main, menu);
68. return true;
69. }
70.
71. }

WIFI
In Android programming, you can use the Wi-Fi service to manage Wi-Fi connections, scan for
available Wi-Fi networks, and perform various Wi-Fi-related tasks. To work with Wi-Fi in Android,
you need to declare Wi-Fi permissions in your AndroidManifest.xml file You can check the
current state of Wi-Fi (enabled or disabled) using the isWifiEnabled() method: To scan for
available Wi-Fi networks, you can use the startScan() method. This initiates a Wi-Fi scan, and
you can receive the scan results through a broadcast receiver. You can programmatically
connect to a known Wi-Fi network by configuring a WifiConfiguration object and then
calling addNetwork() and enableNetwork()
Android Wifi Example
The android.net.wifi.WifiManager class can be used to manage the wifi connectivity. It
can be used to add network, disable network, scan for access points, disconnect etc.

Android wifi example to enable and disable wifi


Let's see the simple example of wifi to enable and disable the wifi service.

activity_main.xml
File: activity_main.xml

1. <RelativeLayout xmlns:androclass="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. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="76dp"
14. android:layout_marginTop="67dp"
15. android:text="Enable Wifi" />
16.
17. <Button
18. android:id="@+id/button2"
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"
21. android:layout_alignLeft="@+id/button1"
22. android:layout_below="@+id/button1"
23. android:layout_marginTop="44dp"
24. android:text="Disable Wifi" />
25.
26. </RelativeLayout>

Activity class
File: MainActivity.java

1. package com.example.wifi;
2.
3. import android.net.wifi.WifiManager;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.content.Context;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11.
12. public class MainActivity extends Activity {
13. Button enableButton,disableButton;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. enableButton=(Button)findViewById(R.id.button1);
20. disableButton=(Button)findViewById(R.id.button2);
21.
22. enableButton.setOnClickListener(new OnClickListener(){
23. public void onClick(View v){
24. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
25. wifi.setWifiEnabled(true);
26. }
27. });
28. disableButton.setOnClickListener(new OnClickListener(){
29. public void onClick(View v){
30. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
31. wifi.setWifiEnabled(false);
32. }
33. });
34. }
35.
36. @Override
37. public boolean onCreateOptionsMenu(Menu menu) {
38. // Inflate the menu; this adds items to the action bar if it is present.
39. getMenuInflater().inflate(R.menu.activity_main, menu);
40. return true;
41. }
42.
43. }
Add Permission in AndroidManifest.xml

You need to add following permissions in AndroidManifest.xml file.

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


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

download this android example


Output:

You might also like