Android SMS & Email Guide
Android SMS & Email Guide
o send SMS in an Android Kotlin program, you will use the SmsManager class, which
T
allows youtosendtextmessagesdirectlyfromyourapp.Belowisastep-by-stepguideand
code implementation.
ince sending SMS requires explicit user permission, you need to add the necessary
S
permission to the [Link] and request runtime permissions in your activity.
In [Link], add the SEND_SMS permission and Telephony Hardware feature:
<uses-permission
android
:name
="[Link].SEND_SMS"
/>
<
uses-feature
android
:name
="[Link]"
/>
I n your activity_main.xml, add an EditText to enter the phone number, another EditText for
the message, and a Button to send the SMS.
?
< xml version
="1.0"
encoding
="utf-8"
?>
<
LinearLayout
android
:orientation
="vertical"
android
:padding
="16dp"
>
<
TextView
android
:layout_width
="match_parent"
android
:layout_height
="wrap_content"
android
:text
="Sending SMS App"
android
:textColor
="#D81B60"
android
:textSize
="26dp"
android
:layout_marginTop
="50dp"
android
:gravity
="center_horizontal"
/>
<
EditText
android
:id
="@+id/phonenumber"
android
:layout_width
="match_parent"
android
:layout_height
="wrap_content"
android
:hint
="Enter Phone Number"
android
:inputType
="phone"
android
:layout_marginTop
="50dp"
/>
<
EditText
ndroid
a :id
="@+id/messageinput"
android
:layout_width
="match_parent"
android
:layout_height
="wrap_content"
android
:hint
="Enter Message"
android
:inputType
="textMultiLine"
/>
<
Button
android
:id
="@+id/sendbtn"
android
:layout_width
="wrap_content"
android
:layout_height
="wrap_content"
android
:text
="Send SMS"
android
:layout_marginTop
="16dp"
/>
</
LinearLayout
>
Step 3. Implement [Link] Code for sending SMS message
I n your [Link], you will need to check for runtime permissions and use the
SmsManager to send an SMS when the button is clicked
mport
i android.
Manifest
import
[Link].PackageManager
import
[Link].
Bundle
import
[Link].SmsManager
import
[Link].
Button
import
[Link].
EditText
import
[Link].
Toast
import
[Link]
import
[Link].AppCompatActivity
import
[Link].ActivityCompat
class
MainActivity
: AppCompatActivity() {
override fun
onCreate(
savedInstanceState:
Bundle
?) {
super
.onCreate(
savedInstanceState
)
enableEdgeToEdge
()
setContentView(
R
.
layout
.
activity_main)
al
v phonefield:
EditText
= findViewById( R
.
id
.
phonenumber)
val
msgfield
:
EditText
= findViewById( R
.
id
.
messageinput)
val
sendbtn
:
Button= findViewById(
R
.
id
.
sendbtn
)
sendbtn
.setOnClickListener
{
//Request Runtime Permission to SEND_SMS
f
i (
A
ctivityCompat.checkSelfPermission(
this
,
Manifest
.
permission
.
SEND_
SMS
)!=
PackageManager
.
PERMISSION_GRANTED
){
ActivityCompat
.requestPermissions(
this
,
arrayOf
(
M
anifest
.
permission
.
SEND_SMS
),
1
)
}
ar
v phonenumber=
phonefield.getText().toString()
var
msg
=
msgfield.getText().toString()
if
(
phonenumber
.
isNotEmpty
() &&
msg
.
isNotEmpty
()){
val
smsManager =
SmsManager
.getDefault()
smsManager
.sendTextMessage(
phonenumber
,
null
,
msg
,
null
,
null
)
Toast
.makeText(
this
,
"SMS Send
Successfully"
,
Toast
.
LENGTH_LONG).show()
}
else
{
Toast
.makeText(
this
,
"Please Enter Phone Number and
Message"
,
Toast
.
LENGTH_LONG
).show()
}
}}}
Open Messages in your emulator
2. Sending Email
I n Android, sending an email can be achieved by using intents. An intent allows your app to
interact with other apps on the device. In the case of sending an email, we use an implicit
intent to launch an email client installed on the user’s device.
I ntent.ACTION_SENDis used specifically for sendingemails which ensures that only apps
that handle email (and not other sharing services) will respond to the intent.
val
intent
= Intent(
Intent
.
ACTION_SEND
)
val
emailIntent
= Intent(Intent
.
ACTION_SENDTO).
apply
{
data
=
Uri
.parse(
"[Link]
)
type
=
"message/rfc822"
putExtra(
Intent
.
EXTRA_EMAIL,
arrayOf
(
"example@[Link]"
))
putExtra(
Intent
.
EXTRA_SUBJECT ,
"Subject of theemail"
)
putExtra(
Intent
.
EXTRA_TEXT
,
"Body of the email" )
}
● dd the recipient email address, subject, and message body using the
A putExtra()
method.
startActivity(
Intent
.createChooser(
intent
,
"Choose
Email App.."
))
Example Program: Sending an Email Message using Intent
ny special permissions are not needed for sending emails using intents. However, if
A
internet-based services are used later on, the Internet permission should be needed in the
[Link]file.
<
TextView
android
:layout_width
="match_parent"
android
:layout_height
="wrap_content"
android
:text
="Sending Email"
/>
<
EditText
android
:id
="@+id/toemail"
android
:layout_width
="300dp"
android
:layout_height
="wrap_content"
android
:hint
="To Email.."
/>
<
EditText
android
:id
="@+id/subject"
android
:layout_width
="300dp"
android
:layout_height
="wrap_content"
android
:hint
="Subject"
/>
<
EditText
android
:id
="@+id/message"
ndroid
a :layout_width
="300dp"
android
:layout_height
="wrap_content"
android
:hint
="Message"
android
:inputType
="textMultiLine"
/>
<
Button
android
:id
="@+id/sendbtn"
android
:layout_width
="wrap_content"
android
:layout_height
="wrap_content"
android
:text
="Send Email"
/>
</
LinearLayout
>
al
v toemail
:
EditText
= findViewById(R
.
id
.
toemail
)
val
subject
:
EditText
= findViewById(R
.
id
.
subject
)
val
message
:
EditText
= findViewById(R
.
id
.
message
)
val
sendbtn
:
Button
= findViewById(
R
.
id
.
sendbtn
)
sendbtn
.setOnClickListener
{
val
intent= Intent(Intent
.
ACTION_SEND
).
apply
{
data
=
Uri
.parse(
"[Link]
)
putExtra(
Intent
.
EXTRA_EMAIL,
arrayOf(
toemail
.
text
.toString()))
type
=
"message/rfc822"
putExtra(
Intent
.
EXTRA_SUBJECT ,
subject
.
t
ext.toString())
putExtra(
Intent
.
EXTRA_TEXT,
message.
text.toString())
}
startActivity(
Intent
.createChooser(
intent
,
"Choose
Email
App.."
))
}
}
}
his ensures that the app can only be installed on devices that have a camera:-
T
<
u
ses-feature android :name
="[Link]"
/>
o allow the app to write and read the image files from external storage.
T
<
u
ses-permission
android
:name
="[Link].WRITE_EXTERNAL_STORAGE"
/>
<
u
ses-permission
android
:name
="[Link].READ_EXTERNAL_STORAGE"
/>
Also,
● FileProvider:You need to define aFileProviderinthe[Link]to
securely share the image file between the android app and the camera app. The file
paths are defined in a separate XML file (file_paths.xml)inside res/xml directory
<
manifest>
<
uses-permissionandroid
:name
="[Link]"
/>
<
uses-featureandroid
:name
="[Link]"
/>
<
uses-permission
android
:name
="[Link].WRITE_EXTERNAL_STORAGE"
/>
<
uses-permission
android
:name
="[Link].READ_EXTERNAL_STORAGE"
/>
<
application
<
activity>
…
</
activity
>
<
provider
android
:name
="[Link]"
android
:authorities
="${applicationId}.provider"
android
:exported
="false"
android
:grantUriPermissions
="true"
>
<
meta-data
android
:name
="[Link].FILE_PROVIDER_PATHS"
android
:resource
="@xml/file_paths"
/>
</
provider
>
</
application
>
</
manifest
>
tep 3:Define thefile pathsin res/xml/file_paths.xml:
S
?
< xml version
="1.0"
encoding ="utf-8"
?>
<
p
aths xmlns: android
="[Link]
>
<
e
xternal-path name ="images"
path ="."
/>
</
paths
>
In Android, <external-path>refers to the shared storagespace where files can be stored
and accessed by all applications. This storage is often represented as the/storage/emulated/0/
directory on devices.
Step 4: Design a Simple UI for Taking Photo from camera
<?
xml version
="1.0"
encoding ="utf-8"
?>
<
LinearLayout
xmlns:
android
="[Link]
xmlns:
app
="[Link]
xmlns:
tools
="[Link]
android
:id
="@+id/main"
android
:layout_width
="match_parent"
android
:layout_height
="match_parent"
tools
:context
=".MainActivity"
android
:orientation
="vertical"
>
<
Button
android
:id
="@+id/btn"
android
:layout_width
="200dp"
android
:layout_height
="wrap_content"
android
:text
="Take Photo"
android
:layout_marginTop
="50dp"
android
:layout_gravity
="center_horizontal"
/>
<
ImageView
android
:id
="@+id/imageView"
android
:layout_width
="300dp"
android
:layout_height
="400dp"
tools
:srcCompat
="@tools:sample/avatars"
android
:layout_marginTop
="20dp"
android
:layout_gravity
="center_horizontal"
/>
</
LinearLayout
>
Step 5: Implement the [Link] code to request permission and take photo.
package
[Link]
mport
i android.
Manifest
import
[Link].
Intent
import
[Link].PackageManager
import
[Link].BitmapFactory
import
[Link].
Uri
mport
i [Link].
Build
import
[Link].
Bundle
import
[Link].
Environment
import
[Link].MediaStore
import
[Link].
Button
import
[Link].
ImageView
import
[Link].
Toast
import
[Link]. ActivityResultLauncher
import
[Link]. ActivityResultContracts
import
[Link]. AppCompatActivity
import
[Link].ActivityCompat
import
[Link].FileProvider
import
[Link].
File
import
[Link].
SimpleDateFormat
import
[Link].
Date
class
MainActivity
: AppCompatActivity() {
rivate
p lateinit var
imageView
:
ImageView
private
lateinit var
btnCapture:
Button
private
lateinit var
photoUri
:
Uri
private
var
photoFile
:
File
? =
null
rivate val
p cameraLauncher :
ActivityResultLauncher<
Intent
>
=
registerForActivityResult(
ActivityResultContracts
.StartActivityForResult())
{
result ->
if
(
r
esult.
resultCode
==
RESULT_OK
&&
photoFile !=
null ) {
val
bitmap
=
BitmapFactory.decodeFile(
photoFile
!!.
absolutePath
)
imageView
.setImageBitmap(
bitmap
)
Toast
.makeText(
this
,
photoFile
!!.
absolutePath
,
Toast
.
LENGTH_LONG
).show()
}
else{
Toast
.makeText(
this
,
"Capture cancelled"
,
Toast .
L
ENGTH_SHORT ).show()
}
}
override fun
onCreate
(
savedInstanceState :
Bundle
?)
{
super
.onCreate(
savedInstanceState
)
setContentView(
R
.
layout
.
activity_main
)
mageView
i = findViewById(R
.
id
.
imageView
)
btnCapture
= findViewById(
R
.
id
.
btn
)
btnCapture
.setOnClickListener
{
val
cameraPermission =
ActivityCompat
.checkSelfPermission(
this
,
Manifest
.
permission
.
CAMERA
)
val
storagePermission =
ActivityCompat
.checkSelfPermission(
this
,
Manifest
.
permission
.
WRITE_EXTERNAL_STORAGE
)
f
i (
cameraPermission
==PackageManager .
PERMISSION_GRANTED &&
storagePermission
==
PackageManager .
PERMISSION_GRANTED ){
capturePhoto()
}
else
{
val
permissions =mutableListOf(
Manifest .
p
ermission.
CAMERA
)
if
(
Build
.
VERSION
.
SDK_INT
<
Build.
V
ERSION_CODES .
TIRAMISU)
{
permissions
.add(
Manifest
.
permission
.
WRITE_EXTERNAL_STORAGE
)
}
requestPermissions(
permissions
.
t
oTypedArray(),
101
)
}
}
}
verride fun
o onRequestPermissionsResult (
requestCode
:
Int
,
permissions
:
Array
<
out
String>,
grantResults:
IntArray) {
super
.onRequestPermissionsResult(
requestCode
,
permissions,
grantResults
)
if
(
requestCode
==101
&&
grantResults .
isNotEmpty ()
&&
grantResults
.
all{ it
==PackageManager
.
PERMISSION_GRANTED
}
) {
capturePhoto()
}
else
{
Toast
.makeText(
this
,
"Permissions denied" ,
Toast.
LENGTH_SHORT
).show()
}
}
private fun
capturePhoto () {
val
intent= Intent( MediaStore
.
ACTION_IMAGE_CAPTURE
)
val
timeStamp :
String
=
SimpleDateFormat(
"yyyyMMdd_HHmmss"
).format(Date())
val
storageDir :
File
? =
getExternalFilesDir(
Environment
.
DIRECTORY_PICTURES
)
photoFile
=File .createTempFile(
"JPEG_
${
timeStamp
}
_"
,
".jpg"
,
storageDir
)
if
(
photoFile !=null
) {
photoUri
=FileProvider .getUriForFile(
this
,
"
${
applicationContext
.
packageName }
.provider" ,
photoFile !!)
intent
.putExtra(
MediaStore
.
EXTRA_OUTPUT
,
photoUri )
cameraLauncher
.launch(
intent
)
}
}
}
4. Accessing Bluetooth
luetoothAdapterisaclassinAndroidthatrepresentsthedevice'sBluetoothadapter,which
B
isthehardwarecomponentthatmanagesBluetoothcommunication.Thisclassallowsyouto
perform various Bluetooth operations, such as checking if Bluetooth is supported,
enabling/disabling Bluetooth, discovering devices, and managing paired devices.
● G et the Default Adapter: You can get the default Bluetooth adapter by calling
[Link]().
● C heck Bluetooth Support: Before attempting to use Bluetooth features, you can
check if the device supports Bluetooth.
● E nable Bluetooth: You can enable Bluetooth programmatically (if not already
enabled) or prompt the user to enable it:
if (![Link]) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
● G et Paired Devices: You can get a set of paired devices (bonded devices) using
bondedDevices:
● D iscoverDevices:TodiscovernearbyBluetoothdevices,youcanstartthediscovery
process:
● Check Bluetooth State: You can also check the currentstate of Bluetooth using the
BluetoothAdapterstate constants:
luetoothAdapter.STATE_ON
B
BluetoothAdapter.STATE_OFF
BluetoothAdapter.STATE_TURNING_ON
BluetoothAdapter.STATE_TURNING_OFF
Example Program to display all Bluetooth Paired Devices
<uses-permission
android
:name
="[Link].BLUETOOTH_CONNECT"
/>
?
< xml version
="1.0"
encoding="utf-8"
?>
<
LinearLayout
xmlns:
android
="[Link]
xmlns:
app
="[Link]
xmlns:
tools
="[Link]
android
:id
="@+id/main"
android
:layout_width
="match_parent"
android
:layout_height
="match_parent"
tools
:context
=".MainActivity"
android
:orientation
="vertical"
>
<
B
utton
android
:id
="@+id/button"
android
:layout_width
="200dp"
android
:layout_height
="wrap_content"
android
:text
="View Paired Devices"
android
:layout_gravity
="center_horizontal"
android
:layout_marginTop
="50dp"
/>
<
L
istView
android
:id
="@+id/listView"
android
:layout_width
="wrap_content"
android
:layout_height
="match_parent"
android
:layout_marginTop
="20dp"
android
:padding
="20dp"
/>
</
LinearLayout
>
mport
i [Link].
BluetoothAdapter
import
[Link].
BluetoothDevice
import
[Link].PackageManager
import
[Link].
Bundle
import
[Link].
ArrayAdapter
import
[Link].
Button
import
[Link].
ListView
import
[Link].
TextView
import
[Link].
Toast
import
[Link]
import
[Link].AppCompatActivity
class
MainActivity
: AppCompatActivity() {
private lateinit var
tvDevices:
TextView
override fun
onCreate(
savedInstanceState
:
Bundle
?)
{
super
.onCreate(
savedInstanceState
)
enableEdgeToEdge
()
setContentView(
R
.
l
ayout.
a
ctivity_main
)
al
v button
:
B
utton= findViewById(
R
.
id
.
button
)
val
listView:
L
istView
= findViewById( R
.
id
.
listView
)
val
bluetoothAdapter
:
BluetoothAdapter
=
BluetoothAdapter
.getDefaultAdapter()
f
i (checkSelfPermission(android.
Manifest
.
p
ermission
.
BLUETOOTH_CONNECT
)!=
PackageManager
.
P
ERMISSION_GRANTED
) {
equestPermissions(
r arrayOf
(android.
Manifest
.
p
ermission
.
B
LUETOOTH_CONNECT
),
1
)
}
button
.setOnClickListener
{
val
pairedDevices :
Set
<
BluetoothDevice
>
=
bluetoothAdapter
.
b
ondedDevices
val
deviceList =
mutableListOf <
String
>()
if
(pairedDevices
.
isNotEmpty
()) {
for
(
device
in pairedDevices ) {
deviceList
.add(
"
$
{device
.
n
ame
}
(
$
{device
.
a
ddress
}
)"
)
}
val
adapter= ArrayAdapter( this
,
android.
R
.
layout
.
s
imple_list_item_1 ,
deviceList )
listView
.
a
dapter =adapter
}
else {
Toast
.makeText(
this
,
"No paired devices found",
Toast
.
LENGTH_SHORT
).show()
}
}
}
}
val
telephonyManager
= getSystemService(Context
.
TELEPHONY_SERVICE
)
as
TelephonyManager
Permission Required
<uses-permission
android
:name
="[Link].READ_PHONE_STATE"
/>
val
telephonyManager
= getSystemService(Context
.
TELEPHONY_SERVICE
)
as
TelephonyManager
val
imei
=
telephonyManager
.
i
mei
val
subscriberId
=
telephonyManager
.
s
ubscriberId
val
telephonyManager= getSystemService( Context
.
T
ELEPHONY_SERVICE
)
as
TelephonyManager
val
simOperatorName=telephonyManager .
simOperatorName
val
networkOperatorName =
telephonyManager .
networkOperatorName
val
countryIso
=telephonyManager.
simCountryIso
val
networkType=
when(
t
elephonyManager .
d
ataNetworkType )
{
TelephonyManager
.
N
ETWORK_TYPE_LTE ->"4G LTE"
TelephonyManager
.
N
ETWORK_TYPE_NR ->"5G"
else
->
"Unknown Network"
}
e are able to make a phone call in android via implicit intent. You need to set two
W
permissions in [Link]
<uses-permission
android
:name
="[Link].CALL_PHONE"
/>
<
uses-feature
android
:name
="[Link]"
android
:required
="false"
/>
omakecalldirectlyfrom,youalsoneedtohaveruntimepermissioninkotlincodeas
T
given below
if(A
ctivityCompat.checkSelfPermission(this,M anifest.p
ermission.CALL_PHONE)!=
PackageManager.P ERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,arrayOf(M
anifest.p
ermission.C
ALL_PHONE),
PackageManager.P ERMISSION_GRANTED)
}
al phoneno:EditText =
v findViewById(R.id.p hone)
val btn: Button =
findViewById(R.id.b
tn)
btn.setOnClickListener {
//Request User Permission
if(ActivityCompat.checkSelfPermission(this,M anifest.permission.CALL_PHONE)!=
PackageManager.P ERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,arrayOf(M anifest.permission.C
ALL_PHONE),
PackageManager.P ERMISSION_GRANTED)
}
else {
var intent: Intent = Intent(Intent.A
CTION_CALL)
intent.setData((Uri.parse("[Link] + phoneno.text.toString())))
startActivity(intent)
}
}
}
}
Design Code
?
< xml version
="1.0"
encoding
="utf-8"
?>
<
LinearLayout
xmlns:
android
="[Link]
xmlns:
tools
="[Link]
android
:id
="@+id/main"
android
:layout_width
="match_parent"
android
:layout_height
="match_parent"
tools
:context
=".MainActivity"
android
:orientation
="vertical"
>
<
EditText
android
:id
="@+id/phone"
android
:layout_width
="wrap_content"
android
:layout_height
="match_parent"
/>
<
Button
android
:id
="@+id/btn"
android
:layout_width
="wrap_content"
ndroid
a :layout_height
="wrap_content"
android
:text
="Call"
/>
</
LinearLayout
>
ost Android-powered devices have built-in sensors that measure motion, orientation,and
M
various environmental conditions.
hese sensors are capable of providing raw data with high precisionandaccuracy,andare
T
usefulifyouwanttomonitorthree-dimensionaldevicemovementorpositioning,oryouwant
to monitor changes in the ambient environment near a device
or example, a game might track readings from a device's gravitysensortoinfercomplex
F
user gestures and motions, such as tilt, shake, rotation, or swing.
ikewise, a weather application might use a device's temperature sensor and humidity
L
sensortocalculateandreportthedewpoint,oratravelapplicationmightusethegeomagnetic
field sensor and accelerometer to report a compass bearing.
otion sensors
M
These sensors measure acceleration forces and rotational forces along three axes. This
category includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
nvironmental sensors
E
These sensors measure various environmental parameters, such as ambient air temperature
and pressure, illumination, and humidity. This category includes barometers, photometers,
and thermometers.
osition sensors
P
These sensors measure the physical position ofadevice.Thiscategoryincludesorientation
sensors and magnetometers.
ommon
C
Sensor Type Description
Uses
TYPE_ACCELEROMETER easures the acceleration force in m/s2that
Hardware M otion
M
is applied to a device on all three physical detection
axes (x, y, and z), including the force of (shake, tilt,
gravity. etc.).
TYPE_AMBIENT_TEMPERATURE Hardware Measures the ambient room temperature in Monitoring
degrees Celsius (°C). See note below. air
temperatures.
TYPE_GRAVITY oftware or Measures the force of gravity in m/s2that is Motion
S
Hardware applied to a device on all three physical axesdetection
(x, y, z). (shake, tilt,
etc.).
TYPE_GYROSCOPE Hardware Measures a device's rate of rotation in rad/s Rotation
around each of the three physical axes (x, y, detection
and z). (spin, turn,
etc.).
TYPE_LIGHT Hardware Measures the ambient light level Controlling
(illumination) in lx. screen
brightness.
2
TYPE_LINEAR_ACCELERATION Software or Measures the acceleration force in m/s that Monitoring
Hardware is applied to a device on all three physical acceleration
axes (x, y, and z), excluding the force of along a single
gravity. axis.
YPE_MAGNETIC_FIELD
T Hardware Measures the ambient geomagnetic field for Creating a
all three physical axes (x, y, z) in μT. compass.
TYPE_ORIENTATION Software Measures degrees of rotation that a device Determining
makes around all three physical axes (x, y, device
z). As of API level 3 you can obtain the position.
inclination matrix and rotation matrix for a
device by using the gravity sensor and the
geomagnetic field sensor in conjunction
with the getRotationMatrix()method.
TYPE_PRESSURE Hardware Measures the ambient air pressure in hPa or Monitoring
mbar. air pressure
changes.
TYPE_PROXIMITY Hardware Measures the proximity of an object in cm Phone
relative to the view screen of a device. This position
sensor is typically used to determine during a call.
whether a handset is being held up to a
person's ear.
TYPE_RELATIVE_HUMIDITY Hardware Measures the relative ambient humidity in Monitoring
percent (%). dewpoint,
absolute, and
relative
humidity.
TYPE_ROTATION_VECTOR Software or Measures the orientation of a device by Motion
Hardware providing the three elements of the device's detection and
rotation vector. rotation
detection.
TYPE_TEMPERATURE Hardware Measures the temperature of the device in
degrees Celsius (°C). This sensor
implementation varies across devices and
this sensor was replaced with
the T
YPE_AMBIENT_TEMPERATUREs
ensor in API Level 14
Sensor Framework
SensorManager
oucanusethisclasstocreateaninstanceofthesensorservice.Thisclassprovides
Y
variousmethodsforaccessingandlistingsensors,registeringandunregisteringsensor
eventlisteners,andacquiringorientationinformation.Thisclassalsoprovidesseveral
s ensorconstantsthatareusedtoreportsensoraccuracy,setdataacquisitionrates,and
calibrate sensors.
Sensor
ou can use this class to create an instance of a specific sensor. This class provides
Y
various methods that let you determine a sensor's capabilities.
SensorEvent
hesystemusesthisclasstocreateasensoreventobject,whichprovidesinformation
T
about a sensor event. A sensor event object includes the followinginformation:the
rawsensordata,thetypeofsensorthatgeneratedtheevent,theaccuracyofthedata,
and the timestamp for the event.
SensorEventListener
ou can use this interface to create two callback methods that receive notifications
Y
(sensor events) when sensor values change or when sensor accuracy changes.
al
v sensorManager
= getSystemService(
Context
.
SENSOR_SERVICE
)
as
SensorManager
?
< xml version
="1.0"
encoding
="utf-8"
?>
<
LinearLayout
xmlns:android
="[Link]
xmlns:
app
="[Link]
xmlns:
tools
="[Link]
android
:id
="@+id/main"
android
:layout_width
="match_parent"
android
:layout_height
="match_parent"
tools
:context
=".MainActivity"
android
:orientation
="vertical"
>
<
B
utton
android
:id
="@+id/viewBtn"
android
:layout_width
="wrap_content"
android
:layout_height
="wrap_content"
android
:text
="View All Sensors"
android
:layout_marginTop
="40dp"
android
:layout_gravity
="center_horizontal"
/>
<
L
istView
android
:id
="@+id/listView"
android
:layout_width
="379dp"
android
:layout_height
="wrap_content"
android
:layout_gravity
="center_horizontal"
android
:layout_marginTop
="20dp"
android
:textColor
="#D81B60"
ndroid
a :textSize
="25dp"
/>
</
LinearLayout
>
mport
i [Link].Context
import
[Link].Sensor
import
[Link].SensorManager
import
[Link].
Bundle
import
[Link].
ArrayAdapter
import
[Link].
Button
import
[Link].
ListView
import
[Link]
import
[Link].AppCompatActivity
class
MainActivity : AppCompatActivity() {
override fun
onCreate(
savedInstanceState
:
Bundle ?)
{
super
.onCreate(
savedInstanceState
)
enableEdgeToEdge
()
setContentView(
R
.
l
ayout .
a
ctivity_main )
val
btn
:
Button
= findViewById( R
.
i
d.
viewBtn
)
val
listView:
ListView = findViewById( R
.
i
d.
listView
)
val
sensorManager = getSystemService( Context
.
S
ENSOR_SERVICE
)
as
SensorManager
btn
.setOnClickListener
{
// Initialize the SensorManager
val
sensorManager = getSystemService( Context
.
S
ENSOR_SERVICE
)
as
SensorManager
// Get a list of all available sensors
val
sensorList :
List<
S
ensor > =
sensorManager
.getSensorList(
Sensor
.
TYPE_ALL
)
// Extract sensor names into a string
list
val
sensorNames =
sensorList .
m
ap { it .
name
}
// Set up an ArrayAdapter to display sensor
names in the
ListView
val
adapter= ArrayAdapter( this
,
android.
R
.
layout
.
s
imple_list_item_1 ,
sensorNames )
listView
.
a
dapter =adapter
}
}
}