Mad U6
Mad U6
SMS Telephony
If we use SmsManager api, it will directly send SMS from our application. In case
if we use Intent with proper action (ACTION_VIEW), it will invoke built-in SMS
app to send SMS from our application.
Any SMS sending requires add android.permission.SEND_SMS permission to the
manifest:
<uses-permission android:name="android.permission.SEND_SMS"/>
if (SIM_STATE == TelephonyManager.SIM_STATE_READY)
return true;
else {
// we can inform user about sim state
switch (SIM_STATE) {
case TelephonyManager.SIM_STATE_ABSENT:
case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
case TelephonyManager.SIM_STATE_PIN_REQUIRED:
case TelephonyManager.SIM_STATE_PUK_REQUIRED:
case TelephonyManager.SIM_STATE_UNKNOWN:
break;
}
return false;
}
}
Option 1
To send SMS using Intent object, we need to write the code like as shown below.
String phone = "+38091234567";
String message = "Hello";
Android has built-in support to add phone number and text message to send an
SMS as follows
String phones = "+38091234567;+38091234568";
smsIntent.putExtra("address", phones);
smsIntent.putExtra("sms_body", message);
Here address and sms_body are case sensitive and should be specified in small
characters only. You can specify more than one number in single string but
separated by semi-colon (;).
Option 2
try {
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(MobileNumber, null, message, null, null);
Toast.makeText(MainActivity.this, "SMS Sent Successfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "SMS Failed to Send, Please try again",
Toast.LENGTH_SHORT).show();
}
activity_main.xml
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/msgTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Send SMS" />
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
AndroidManifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>
Before starting Email Activity, You must know Email functionality with intent,
Intent is carrying data from one component to another component with-in the
application or outside the application.
To send an email from your application, you don’t have to implement an email
client from the beginning, but you can use an existing one like the default Email
app provided from Android, Gmail, Outlook, K-9 Mail etc. For this purpose, we
need to write an Activity that launches an email client, using an implicit Intent with
the right action and data. In this example, we are going to send an email from our
app by using an Intent object that launches existing email clients.
Following section explains different parts of our Intent object required to send an
email.
1 EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.
2 EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.
3 EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.
4 EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with
ACTION_SEND to supply an alternative to EXTRA_TEXT as HTML
formatted text.
5 EXTRA_SUBJECT
A constant string holding the desired subject line of a message.
6 EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent.
7 EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a
ACTION_CHOOSER.
setType - We use this property to set the MIME type of data that we want to send.
Here we used “message/rfc822” and other MIME types are “text/plain” and
“image/jpg”.
activity_main.xml
package com.tutlane.sendmailexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
ACTION_SEND - It’s an activity action that specifies that we are sending some
data.
putExtra - we use this putExtra() method to add extra information to our Intent.
Here we can add the following things.
EXTRA_EMAIL - It’s an array of email addresses
setType - We use this property to set the MIME type of data that we want to send.
Here we used “message/rfc822” and other MIME types are “text/plain” and
“image/jpg”.
We need to add MIME type in our android manifest file for that open android
manifest file (AndroidManifest.xml) and write the code like as shown below
AndroidManifest.xml
By using Google Maps Android API we can integrate google maps in android
applications to show the location details on map based on our requirements.
To use google maps in our android applications we need to install Google Play
Services SDK in our Android Studio because google made Google Mas API as a
part of Google Play Services SDK.
Create a new android application using android studio and give names as
GoogleMapExample like as shown below.
Now we need to select the form factors which we need for our app. In case if
you're not sure what you need, just select Phone and Tablet and then click Next
like as shown below.
Now select the Google Maps Activity in 'Add an activity to Mobile' dialog and
click Next like as shown below.
Customize the activity by entering activity name, layout name and title as
prompted. In case if default values are fine, then click Finish like as shown below.
The Google Maps API Key:
The API key is a unique identifier that authenticates requests associated with your
project for usage and billing purposes. You must have at least one API key
associated with your project.
To create an API key:
Step 1: Open Google developer console and signin with your gmail account:
https://console.developers.google.com/project
Step 2: Now create new project. You can create new project by clicking on the
Create Project button and give name to your project.
Step 3: Now click on APIs & Services and open Dashboard from it.
Step 8: Now API your API key will be generated. Copy it and save it somewhere
as we will need it when implementing Google Map in our Android project.
Android Google Map
Android provides facility to integrate Google map in our application. Google map
displays your current location, navigate location direction, search location etc. We
can also customize Google map according to our requirement.
There are four different types of Google maps, as well as an optional to no map at
all. Each of them gives different view on map. These maps are as follow:
1. Normal: This type of map displays typical road map, natural features like
river and some features build by humans.
2. Hybrid: This type of map displays satellite photograph data with typical
road maps. It also displays road and feature labels.
3. Satellite: Satellite type displays satellite photograph data, but doesn't display
road and feature labels.
4. Terrain: This type displays photographic data. This includes colors, contour
lines and labels and perspective shading.
5. None: This type displays an empty grid with no tiles loaded.
Methods Description
map.
animation.
location.
update.
progress.
@Override
public void onLocationChanged(Location location) { }
. GoogleApiClient.ConnectionCallbacks: This interface provide callbacks
methods onConnected(Bundle) and onConnectionSuspended(int) which are called
when the device is to connected and disconnected.
. GoogleApiClient.OnConnectionFailedListener: This interface provide
callbacks method onConnectionFailed(ConnectionResult) which is called when
there was an error in connecting the device to the service.
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
Activity_maps.xml
Add the following fragment code in ActivityMain.xml for adding Google map to
your activity
By default, the XML file (activity_maps.xml) that defines the app's layout is at
res/layout/ contains the following code.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tutlane.googlemapexample.MapsActivity" />
SupportMapFragment
A Map component in an app. This fragment is the simplest way to place a map in
an application. It's a wrapper around a view of a map to automatically handle the
necessary life cycle needs. Being a fragment, this component can be added to an
activity's layout file simply with the XML below.
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Syntax:
getMapAsync(OnMapReadyCallback callback)
Sets a callback object which will be triggered when the GoogleMap instance is
ready to be used.
2 float getAccuracy()
Get the estimated accuracy of this location, in meters.
3 double getAltitude()
Get the altitude if available, in meters above sea level.
4 float getBearing()
Get the bearing, in degrees.
5 double getLatitude()
Get the latitude, in degrees.
6 double getLongitude()
Get the longitude, in degrees.
7 float getSpeed()
Get the speed if it is available, in meters/second over ground.
8 boolean hasAccuracy()
True if this location has an accuracy.
9 boolean hasAltitude()
True if this location has an altitude.
10 boolean hasBearing()
True if this location has a bearing.
11 boolean hasSpeed()
True if this location has a speed.
12 void reset()
Clears the contents of the location.
14
void setAltitude(double altitude)
Set the altitude, in meters above sea level.
19 String toString()
Returns a string containing a concise, human-readable description of this object.
To get the current location, create a location client which is LocationClient object,
connect it to Location Services using connect() method, and then call
its getLastLocation() method. This method returns the most recent location in the
form of Location object that contains latitude and longitude coordinates and other
information as explained above. To have location based functionality in your
activity, you will have to implement two interfaces −
GooglePlayServicesClient.ConnectionCallbacks
GooglePlayServicesClient.OnConnectionFailedListener
These interfaces provide following important callback methods, which you need to
implement in your activity class −
Sr.No. Callback Methods & Description
You should create the location client in onCreate() method of your activity class,
then connect it in onStart(), so that Location Services maintains the current
location while your activity is fully visible. You should disconnect the client
in onStop() method, so that when your app is not visible, Location Services is not
maintaining the current location. This helps in saving battery power up-to a large
extent.
Android device having Android 6.0 (Marshmallow) or later are required some
permission at runtime to access device functionality.
1. <uses-
permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2. <uses-
permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name=”android.permission.ACCESS_FINE_LOCATION” />
In case the app needs to access the user’s location while the app is running in
the background, we need to add the following permission along with the above
ones:
<uses-permission
android:name=”android.permission.ACCESS_BACKGROUND_LOCATION” />
We need to add all these permissions in the AndroidManifest.xml. To access this
file, select your project view as Android and click on:
app->manifests->AndroidManifest.xml.
AndroidManifest.xml file looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.getuserlocation">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.GetUserLocation">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Add a marker
Markers identify locations on the map.It indicate single locations on the map.We
can place a maker with some text over it displaying your location on map.It can be
done by addMarker() method
The following example demonstrates how to add a marker to a map. The marker is
created at coordinates -33.852,151.211 (Sydney, Australia), and displays the string
'Marker in Sydney' in an info window when clicked.
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions()
.position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
Searching location in Google Map API is done through Geocoder class. Geocoder
class is used to handle geocoding and reverse geocoding.
java.lang.Object
↳ android.location.Geocoder
Public constructors
Geocoder(Context context)
Syntax-
Public methods
List<Addre getFromLocation(double latitude, double longitude, int maxResults)
ss>
This method was deprecated in API level 33. Use getFromLocation(double, double, int,
android.location.Geocoder.GeocodeListener) instead to avoid blocking a thread
waiting for results.
void getFromLocation(double latitude, double longitude, int
maxResults, Geocoder.GeocodeListener listener)
Returns an array of Addresses that attempt to describe the named location, which may
be a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre
Parkway, Mountain View, CA", an airport code such as "SFO", and so forth.
void getFromLocationName(String locationName, int
maxResults, Geocoder.GeocodeListener listener)
Provides an array of Addresses that attempt to describe the named location, which may
be a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre
Parkway, Mountain View, CA", an airport code such as "SFO", and so forth.
List<Addre getFromLocationName(String locationName, int maxResults)
ss>
This method was deprecated in API level 33.
Use getFromLocationName(java.lang.String, int,
android.location.Geocoder.GeocodeListener) instead to avoid blocking a thread
waiting for results.
static isPresent()
boolean
Returns true if there is a geocoder implementation present that may return results.
Let's see the code which convert location name into coordinate.
Enables or disables the my-location button. The my-location button causes the
camera to move such that the user's location is in the center of the map. If the
button is enabled, it is only shown when the my-location layer is enabled.
By default, the my-location button is enabled (and hence shown when the my-
location layer is enabled).
Parameters
enabled true to enable the my-location button; false to disable the my-location button.
public void setAllGesturesEnabled (boolean enabled)
Sets the preference for whether all gestures should be enabled or disabled. If
enabled, all gestures are available; otherwise, all gestures are disabled. This doesn't
restrict users from tapping any on screen buttons to move the camera (e.g.,
compass or zoom controls), nor does it restrict programmatic movements and
animation.
Parameters
true to enable all gestures; false to disable all gestures.
enabled
Enables or disables the compass. The compass is an icon on the map that indicates
the direction of north on the map. If enabled, it is only shown when the camera is
tilted or rotated away from its default orientation (tilt of 0 and a bearing of 0).
When a user clicks the compass, the camera orients itself to its default orientation
and fades away shortly after. If disabled, the compass will never be displayed.
By default, the compass is enabled (and hence shown when the camera is not in the
default orientation).
Parameters
enabled true to enable the compass; false to disable the compass.
package com.javapapers.android.geolocationfinder;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" +
location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
<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" >
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
Android Output
Que – Write a program to draw a route between two locations.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:layout_margin="20dp">
<EditText
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_source"
android:hint="Enter Source Location"
android:padding="13dp"
android:background="@drawable/input"/>
<EditText
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_destination"
android:hint="Enter Destination Location"
android:padding="13dp"
android:background="@drawable/input"/>
<Button
android:layout_marginTop="40dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/track"
android:text="Draw Route"/>
</LinearLayout>
MainActivity.java
package co6i.micro.project.shantanu.practical32;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText source, destination;
Button track;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
source = findViewById(R.id.et_source);
destination = findViewById(R.id.et_destination);
track = findViewById(R.id.track);
track.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String sSource = source.getText().toString();
String sDestination = destination.getText().toString();
if(sSource.equals("") && sDestination.equals("")){
Toast.makeText(MainActivity.this,"Enter Both
Location",Toast.LENGTH_SHORT).show();
}
else{
DisplayTrack(sSource,sDestination);
}
}
});
}
private void DisplayTrack(String sSource, String sDestination) {
try {
Uri uri =
Uri.parse("https://www.google.co.in/maps/dir/"+sSource+"/"+sDestination);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
intent.setPackage("com.google.android.apps.maps");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// This Flag Only Starts an Activity in a new Task If it's not previously started
startActivity(intent);
}
catch (ActivityNotFoundException e){
Uri uri =
Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps
.maps");
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
OUTPUT
Android Security Model
Normal permissions grant access to data and resources outside of the application
sandbox which have very little risk to compromise user’s data or other applications
on the system. Normal permissions declared in the application’s manifest are
automatically granted upon installing the application on the device. Users do not
need to grant these permissions and cannot revoke them.
The android.permission.INTERNET permission, allowing the application to access
the internet, is an example of normal permission.
App sandbox
App signing
App signing allows developers to identify the author of the app and to update their
app without creating complicated interfaces and permissions. Every app that runs
on the Android platform must be signed by the developer.
Authentication
On devices with a fingerprint sensor, users can enroll one or more fingerprints and
use those fingerprints to unlock the device and perform other tasks. The Gatekeeper
subsystem performs device pattern/password authentication in a Trusted Execution
Environment (TEE).
Android 9 and higher includes Protected Confirmation, which gives users a way to
formally confirm critical transactions, such as payments.
Biometrics
Android 9 and higher includes a BiometricPrompt API that app developers can use
to integrate biometric authentication into their apps in a device- and modality-
agnostic fashion. Only strong biometrics can integrate with BiometricPrompt.
Encryption
Keystore
Security-Enhanced Linux
Verified Boot
Verified Boot strives to ensure all executed code comes from a trusted source
(usually device OEMs), rather than from an attacker or corruption. It establishes a
full chain of trust, starting from a hardware-protected root of trust to the bootloader,
to the boot partition and other verified partitions.
Permissions to be granted at install time in
Android 5.1.1 and older
Permissions to be granted at runtime in Android
6.0 and above
Types of Permissions
1. Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the
permission is requested at the installation time at the Google Play Store.
If the user Accepts the permissions, the app is installed. Else the app installation
is canceled.
1. Run-Time Permissions: If the Android 6 (API 23) or higher, the
permission is requested at the run time during the running of the app.
If the user Accepts the permissions, then that feature of the app can be used. Else
to use the feature, the app requests permission again.
So, now the permissions are requested at runtime. In this article, we will discuss
how to request permissions in an Android Application at run time.
Application Deployment
Application Signing
Application signing allows developers to identify the author of the application and
to update their application without creating complicated interfaces and
permissions. Every application that is run on the Android platform must be signed
by the developer. Applications that attempt to install without being signed will be
rejected by either Google Play or the package installer on the Android device.
Step 1: Go to Build -> Generate Signed Bundle or APK, a pop up will arise.
Choose APK in the pop-up and click on Next.
Step 2: After completing step 1, if you already have a key, make sure you just
refer to that and you can release the version of that app but in case if it is the first
time it is recommended to create a new key. After creating a new key click
on OK and then click on Next.
Step 3: After clicking Next in the next pop-up make sure to
choose release as Build Variants and check the two Signature Versions as well.
Then click on Finish.
Step 4: After successfully completed these steps you can locate your signed apk
at app -> release -> app-release as your apk file.
Publish your app
Android application publishing is a process that makes your Android applications
available to users. Infect, publishing is the last phase of the Android application
development process
1. Purchase your Google Developer account from Google Developers (cost $25)
2. Be ready with your Apk file and make sure it is compatible with all devices and
Google Play Store policies as well.
3. After the successful purchase of your account, go here Google Play Developer
Console
4. On the right side, you can see an option like "Add new Application".
5. Upload the Apk file, fill the forms and add the screenshots.
6. Finally click Publish App
7. The team will review your application and make it live within 24 hours time.
Developer Console
The Google Play Console is the back-end interface that Android developers
and publishers can use to upload new apps, manage existing ones, and
monitor performance.
Some of the things you can do from the Google Play Console include:
Google Play Developer Console is the platform that Google provides for Google
Play and Android developers to publish – and of particular interest to ASO teams –
to monitor their app’s performance in the Google Play store. As Google explains,
by using the platform it’s possible to: “Publish your apps and games with the
Google Play Console and grow your business on Google Play. Benefit from
features that help you improve your app’s quality, engage your audience, earn
revenue, and more.”
The Google Play console allows app developers and marketers to better understand
how their apps are performing in terms of growth, technical performance such as
crashes or display issues, and financials. The console offers acquisition reports and
detailed analysis which can help app devs / marketers find out how well an app is
really performing.