Unit 06 - MAD
Unit 06 - MAD
SMS (Short Message Service) telephony in Android refers to the system of sending, receiving,
and managing SMS messages (text messages) within an Android app. It involves using specific
APIs and permissions to interact with the device's SMS functionality. Android offers various
tools and features for telephony services, including sending SMS, receiving SMS, querying for
SMS-related information, and more.
1. SMSManager
SMSManager is the primary class used for sending SMS messages in Android. It allows
developers to send SMS messages from the app in both normal and multipart formats, as
well as handle delivery reports.
Besides using SMSManager, you can also send SMS messages using Intent. This is often used
to open the default messaging app with a prefilled SMS message.
This code opens the SMS app with the pre-filled recipient number and message content,
allowing the user to send the message manually.
Android allows you to listen for incoming SMS messages using a BroadcastReceiver. You can
register a receiver to handle SMS delivery, receipt, or read actions.
1
Example of BroadcastReceiver to Listen for Incoming SMS:
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String sender = messages[0].getOriginatingAddress();
String messageBody = messages[0].getMessageBody();
Log.d("SMS", "From: " + sender + ", Message: " + messageBody);
}
}
}
In this example, when a new SMS is received, the onReceive method is triggered. The
SmsMessage class helps to extract the originating address (phone number) and message
content.
Registering the Receiver in the Manifest: You must declare the receiver in your app’s
AndroidManifest.xml file to listen for incoming SMS broadcasts.
<receiver android:name=".SmsReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Sending and receiving SMS requires specific permissions, and these must be declared in the
app’s AndroidManifest.xml. Depending on the actions you intend to perform, permissions may
vary.
Android stores all SMS messages in its content provider, which can be queried to read the
messages stored on the device. The Sms.CONTENT_URI allows access to SMS messages.
This code queries the SMS inbox and retrieves the sender’s address and the body of the
message. You can adjust the query to target other folders like sent messages.
When an SMS is sent, you can request a delivery report to be notified when the message has
been delivered successfully.
7. SMSManager vs Intent
Both SmsManager and Intent can be used for sending SMS, but they serve different purposes:
SmsManager is a more direct approach, useful for background SMS operations without
requiring user interaction.
Intent opens the default SMS application and pre-fills the recipient and message. It’s
used when you want the user to review the message before sending it.
8. Security Considerations
Sending and receiving SMS messages can have security implications. It's important to ensure:
You can send SMS messages from background services. However, sending SMS in the
background might be subject to restrictions, especially in newer Android versions. Always
ensure that you have the correct permissions and follow best practices for background tasks.
Android’s SMS telephony system offers powerful tools for integrating SMS functionality into
apps. With classes like SmsManager and SmsMessage, Android developers can send, receive,
and manage SMS messages efficiently. By using BroadcastReceiver for listening to incoming
messages and delivery reports, apps can offer dynamic SMS-based interactions. However,
SMS-related features are subject to strict permissions, and developers must follow security
guidelines to ensure proper handling of SMS data.
Location-based services (LBS) in Android enable apps to use location data to provide relevant,
location-based content and services. LBS uses GPS, Wi-Fi, or cellular network data to determine
the user’s location and tailor the app's functionality based on that location.
When you want to integrate location-based services into your Android project, follow these
initial setup steps:
4
2. Add Necessary Dependencies: Open your build.gradle (app-level) file and add
dependencies for location services and Google Maps.
3. dependencies {
4. implementation 'com.google.android.gms:play-services-maps:17.0.0'
5. implementation 'com.google.android.gms:play-services-location:17.0.0'
6. }
Starting with Android 6.0 (API level 23) and above, you need to ask for location
permissions at runtime as well. We'll discuss this later.
To use Google Maps in your app, you need to obtain an API key. Here are the steps to get the
Google Maps API key:
Once the project is set up, and the Google Maps API key is added, displaying the map is quite
straightforward.
5
1. Set up a GoogleMap fragment: The best way to display a map is using a
SupportMapFragment, which integrates the map into your activity or fragment. Update
the activity layout (XML file) to include a Fragment element:
2. <fragment
3. android:id="@+id/map"
4. android:name="com.google.android.gms.maps.SupportMapFragment"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"/>
7. Initialize the map in your activity: In your activity, implement OnMapReadyCallback
and initialize the map as follows:
8. import com.google.android.gms.maps.GoogleMap;
9. import com.google.android.gms.maps.OnMapReadyCallback;
10.import com.google.android.gms.maps.SupportMapFragment;
11.
12.public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback
{
13.
14. private GoogleMap mMap;
15.
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_maps);
20.
21. // Get the map fragment and call the callback when it's ready
22. SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
23. .findFragmentById(R.id.map);
24. mapFragment.getMapAsync(this);
25. }
26.
27. @Override
28. public void onMapReady(GoogleMap googleMap) {
29. mMap = googleMap;
30.
31. // Set default location or update map settings here
32. }
33.}
34.Run the Application: When the app is launched, the map should be visible on the
screen.
Google Maps for Android comes with built-in controls for zooming, such as buttons to zoom in
or out. To enable these controls, simply use:
mMap.getUiSettings().setZoomControlsEnabled(true);
You can focus the map on a specific location and zoom to that location using the moveCamera
method.
6
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.LatLng;
latitude and longitude are the coordinates of the location you want to navigate to.
zoomLevel is an integer between 2 and 21 that controls the zoom level (higher is closer).
Geocoding is the process of converting an address into geographic coordinates (latitude and
longitude). Reverse Geocoding is the process of converting coordinates into an address.
1. Geocoding: You can use Geocoder to convert an address to latitude and longitude.
2. Geocoder geocoder = new Geocoder(this, Locale.getDefault());
3. try {
4. List<Address> addresses = geocoder.getFromLocationName("1600 Amphitheatre
Parkway, Mountain View, CA", 1);
5. if (addresses != null && !addresses.isEmpty()) {
6. Address address = addresses.get(0);
7. double latitude = address.getLatitude();
8. double longitude = address.getLongitude();
9. LatLng latLng = new LatLng(latitude, longitude);
10. mMap.addMarker(new MarkerOptions().position(latLng).title("Marker at
Address"));
11. mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
12. }
13.} catch (IOException e) {
14. e.printStackTrace();
15.}
16.Reverse Geocoding: To convert latitude and longitude to an address:
17.double latitude = 37.423343;
18.double longitude = -122.072881;
19.Geocoder geocoder = new Geocoder(this, Locale.getDefault());
20.try {
21. List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
22. if (addresses != null && !addresses.isEmpty()) {
23. Address address = addresses.get(0);
24. String addressText = address.getAddressLine(0);
25. Log.d("ReverseGeocoding", "Address: " + addressText);
26. }
27.} catch (IOException e) {
28. e.printStackTrace();
29.}
To get the user’s current location, you can use FusedLocationProviderClient which is part of
the Google Play Services API.
1. Setup FusedLocationProviderClient:
7
2. FusedLocationProviderClient fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
3.
4. fusedLocationClient.getLastLocation()
5. .addOnSuccessListener(this, new OnSuccessListener<Location>() {
6. @Override
7. public void onSuccess(Location location) {
8. if (location != null) {
9. double latitude = location.getLatitude();
10. double longitude = location.getLongitude();
11. LatLng userLocation = new LatLng(latitude, longitude);
12. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,
15));
13. }
14. }
15. });
16.Requesting Location Updates: To monitor location continuously, request location
updates:
17.LocationRequest locationRequest = LocationRequest.create();
18.locationRequest.setInterval(10000); // 10 seconds
19.locationRequest.setFastestInterval(5000); // 5 seconds
20.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
21.
22.fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback,
Looper.getMainLooper());
8. Monitoring Location:
Make sure to stop location updates when they are no longer needed to conserve battery:
fusedLocationClient.removeLocationUpdates(locationCallback);
Conclusion:
Android provides robust tools for working with Location-Based Services (LBS). You can display
maps, geocode and reverse geocode addresses, get location data, and monitor location updates
using the FusedLocationProviderClient for efficient battery usage. Proper setup, including
getting an API key for Google Maps and handling permissions, is critical to successfully
integrating location-based features into your app.
8
Android Security Model:
The Android Security Model is designed to protect both users and developers from malicious
behavior and unauthorized access to sensitive data. Android provides several layers of security,
including user-level, app-level, and platform-level protection, to ensure that each app and
component interacts securely within the operating system and with other apps.
1. App Sandboxing:
o Every Android application runs in its own isolated process, which is called
sandboxing. Each app is granted its own user ID (UID), which is a unique
identifier. This prevents one app from accessing another app’s private data and
resources unless explicitly allowed.
o Apps can only access their own files and data unless they request access to other
resources, such as shared storage or specific system resources.
2. Permissions:
o Android’s permission system controls how apps can access system features and
user data. Apps must explicitly declare the permissions they require in their
AndroidManifest.xml file.
o The user is prompted at install time (for normal permissions) or during runtime
(for dangerous permissions) to grant or deny these permissions.
3. Processes and User IDs (UIDs):
o Each app runs as a unique user in its own process. Android assigns a unique UID
to every app, and this UID is used to determine the permissions for accessing
certain resources.
4. Runtime Permissions:
o Starting from Android 6.0 (API level 23), Android introduced runtime
permissions, meaning the app must request certain permissions during the
execution of the app (e.g., accessing location or camera).
o This provides more control to users and helps mitigate the risk of apps requesting
unnecessary permissions.
5. Signature-based Permissions:
o Android allows apps to define permissions that can only be granted to other apps
signed with the same cryptographic key. This enables secure inter-app
communication.
6. Security Updates and Patches:
o Android devices receive security patches and updates to keep the OS secure
from known vulnerabilities and exploits. It is important for users to keep their
devices updated with the latest patches.
Permissions in Android are defined in the AndroidManifest.xml file. They are required when an
app intends to access sensitive system resources or user data, such as the camera, location,
contacts, etc.
Declaring Permissions:
To request permissions, you need to declare them in your app's AndroidManifest.xml file. There
are two types of permissions: Normal Permissions and Dangerous Permissions.
1. Normal Permissions: These permissions do not affect user privacy and can be granted
automatically by the system when the app is installed.
9
Example:
o This permission is required to access the internet, and it's automatically granted.
2. Dangerous Permissions: These permissions access sensitive user data or system
resources, such as location, camera, contacts, etc. The user must explicitly grant these
permissions during runtime.
Example:
Starting from Android 6.0 (API level 23), for dangerous permissions, the app must
request them at runtime, even if they are declared in the AndroidManifest.xml.
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_LOCATION_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission granted, proceed with accessing the location
} else {
// Permission denied, handle accordingly
}
}
}
Handling Permissions:
Permission Granted: When the user grants the permission, the app can safely access
the resource (e.g., location, camera).
Permission Denied: If the user denies the permission, the app must handle the denial
gracefully, possibly providing an alternative feature or explaining why the permission is
necessary.
10
Using Custom Permissions:
Android also allows you to define custom permissions that can be used to control access to
your app's components (activities, services, broadcast receivers). This enables apps to share
data or interact securely with each other.
Custom permissions are declared in the AndroidManifest.xml file using the <permission>
element. This permission can then be enforced on the components (like activities, services,
etc.) of your app.
<permission
android:name="com.example.app.permission.MY_CUSTOM_PERMISSION"
android:protectionLevel="normal"/>
Here, the protectionLevel attribute defines how the permission will be handled:
Once you declare the custom permission, you can assign it to specific components. For instance,
you can restrict access to a service using your custom permission:
<service
android:name=".MyService"
android:permission="com.example.app.permission.MY_CUSTOM_PERMISSION">
</service>
In this case, only apps that have been granted MY_CUSTOM_PERMISSION can interact with
MyService.
To access a component with a custom permission from another app, you must request the
permission in that app’s AndroidManifest.xml:
<uses-permission
android:name="com.example.app.permission.MY_CUSTOM_PERMISSION"/>
In the code, you would handle the permission request just as you would with any other
permission:
11
if (ContextCompat.checkSelfPermission(this,
"com.example.app.permission.MY_CUSTOM_PERMISSION")
== PackageManager.PERMISSION_GRANTED) {
// Access the restricted component
} else {
// Handle permission denial or request permission
ActivityCompat.requestPermissions(this, new
String[]{"com.example.app.permission.MY_CUSTOM_PERMISSION"}, 1);
}
You can restrict the use of certain components to only apps signed with the same certificate.
This is commonly used in apps that communicate within the same organization or vendor.
Only apps signed with the same certificate will be able to access SensitiveActivity.
9. Request Signature Permission: Apps that need to interact with this service or activity
don’t need to request permissions in the AndroidManifest.xml file. Instead, the system
checks whether both apps are signed with the same certificate at runtime.
1. Use Least Privilege: Only request permissions that are absolutely necessary for your
app’s functionality. Avoid over-permissioning to protect user privacy.
2. Use HTTPS for Sensitive Communication: Always ensure that communication with
servers, especially involving sensitive data, is done over HTTPS.
3. Check Permissions at Runtime: For dangerous permissions, always check for
permission status at runtime before accessing any resource.
4. Handle Permission Denial Gracefully: If the user denies a permission, explain why
the permission is necessary or offer an alternative feature that doesn’t require it.
5. Use Strong Encryption: For storing sensitive data locally, use strong encryption
methods to prevent unauthorized access, even if the device is compromised.
Conclusion:
12
Application Deployment in Android:
Deploying an Android application involves several important steps, including creating the app,
signing it, and finally, publishing it on the Google Play Store. Below is a detailed breakdown of
each of these steps, including how to create a small application, how to sign it, and how to
manage its release on the Play Store.
Before deploying your app, you must create it. Let's go through the basic steps of creating a
simple Android app using Android Studio.
Run the application on an Android emulator or a physical device to test its functionality
and fix any issues that may arise.
13
2. Signing of Application:
Before deploying an app to the Google Play Store, it must be signed. Signing an app ensures
that the app is from a known source and hasn't been tampered with.
Security: It helps ensure that only you, as the developer, can update your app.
App Identity: It establishes the identity of the app, confirming it was created by the
developer.
1. Generate a Keystore: You must create a keystore file, which is used to sign the app.
This file contains the cryptographic key used to sign the application.
o Open Android Studio.
o Click Build > Generate Signed Bundle / APK.
o Choose APK or App Bundle (for Play Store).
o Click Next.
o Select Create new under the Key store path section.
o Enter the path, password, key alias, key password, and validity (usually 25 years
or more) for your keystore.
o Click OK.
2. Sign the APK or App Bundle:
o After generating your keystore, you can sign the APK or App Bundle:
o Specify the key alias and key password in the wizard.
o Click Next.
o Choose the release build variant for your application (instead of debug).
o Click Finish to generate the signed APK or App Bundle.
3. Verify the APK: After signing, you can verify that the APK is signed by checking the
signatures or simply by uploading it to the Play Store.
Once you have a signed APK or App Bundle, you can deploy your app to the Google Play Store.
Below are the detailed steps for deploying your Android app:
Before publishing, you need to create a Google Play Developer account. This involves the
following steps:
1. Visit the Google Play Console and sign in with your Google account.
2. Click Go to Play Console and accept the terms and conditions.
3. Pay a one-time registration fee (usually $25) via Google Play's payment system.
4. Complete your developer profile with necessary details like your developer name, email,
website, and contact info.
Once registered, you'll have access to the Play Console, where you can manage and publish
your apps.
Fill out the details that will appear in the Google Play Store listing:
Pricing: Decide whether your app will be free or paid. You cannot change a free app to
a paid app later, so choose wisely.
Countries: Choose the countries where you want your app to be available.
Device Compatibility: Check the list of devices your app supports. You can filter by
screen size, API level, and other factors.
Once you have completed the above steps, click "Review" to ensure everything is in order. If
everything looks good, click "Start Rollout to Production" to submit your app for review.
Review Process: Google will review your app to ensure it complies with the Play Store
policies. This can take anywhere from a few hours to a few days.
Approval: Once your app is approved, it will be published on the Play Store and available
for users to download.
15
4. Become a Publisher and Manage the Developer Console:
To become a publisher on the Google Play Store, you need to create a Google Play Developer
account, which we discussed earlier. Once you're registered and have submitted your app,
your account will be linked to your apps and you will be recognized as a publisher.
You can manage your app listings, track installs and updates, and interact with users through
the Play Console.
Once your app is published, you can manage various aspects of your app using the Google Play
Console:
1. Track Downloads & Installs: Monitor how many users have downloaded and installed
your app.
2. App Updates: Upload new versions of your app to fix bugs or add new features.
3. User Reviews: Respond to user reviews and gather feedback to improve your app.
4. App Analytics: Use the built-in analytics to track app performance, user demographics,
and retention.
When you release new versions of your app, you’ll need to upload the new APK or App
Bundle, update the version number, and provide release notes.
The new version will go through the review process before being made available to users.
Conclusion:
The deployment process for an Android app involves creating the app, signing it, and finally
publishing it on the Google Play Store. After registration as a developer, you'll create an app
listing, upload the APK or App Bundle, and provide information like descriptions, screenshots,
and privacy policies. Once your app is approved by Google, it will be available for download on
the Play Store. Managing your app through the Google Play Console allows you to track installs,
respond to user reviews, and update your app with new versions.
16