Mad Chapter - 6 Notes
Mad Chapter - 6 Notes
SMS Telephony
In android, we can send SMS from our android application in two ways either by using
SMSManager API or Intents based on our requirements.
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 a built-in SMS app to send SMS
from our application.
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
Apart from the above method, there are few other important functions available in SmsManager
class. These methods are listed below −
2
static SmsManager getDefault()
This method is used to get the default instance of the SmsManager
3
void sendDataMessage(String destinationAddress, String scAddress, short
destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent)
This method is used to send a data based SMS to a specific application port.
4
void sendMultipartTextMessage(String destinationAddress, String scAddress,
ArrayList<String> parts, ArrayList<PendingIntent> sentIntents,
ArrayList<PendingIntent> deliveryIntents)
Send a multi-part text based SMS.
5
void sendTextMessage(String destinationAddress, String scAddress, String text,
PendingIntent sentIntent, PendingIntent deliveryIntent)
Send a text based SMS.
Sending Email
Email is messages distributed by electronic means from one system user to one or more
recipients via a network.
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.
Here is an example showing you how to assign extra data to your intent −
emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]
{"Recipient"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT , "Message Body");
The out-put of above code is as below shown an image
package com.example.tutorialspoint;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes
here");
try {
startActivity(Intent.createChooser(emailIntent, "Send
mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There is no email
client installed.", Toast.LENGTH_SHORT).show();
}
}
}
activity_main.xml −
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sending Mail Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:id="@+id/sendEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/compose_email"/>
</LinearLayout>
strings.xml −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="compose_email">Compose Email</string>
</resources>
AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.Tutorialspoint" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.tutorialspoint.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I assume you have connected your actual Android Mobile device with your computer. To run
the app from Android Studio, open one of your project's activity files and click Run icon from
the toolbar. Before starting your application, Android studio installer will display following
window to select an option where you want to run your Android application.Select your mobile
device as an option and then check your mobile device which will display following screen −
Now use Compose Email button to list down all the installed email clients. From the list, you
can choose one of email clients to send your email. I'm going to use Gmail client to send my
email which will have all the provided defaults fields available as shown below. Here From: will
be default email ID you have registered for your Android device.
You can modify either of the given default fields and finally use send email button to send your
email to the mentioned recipients.
1
float distanceTo(Location dest)
Returns the approximate distance in meters between this location and the given location.
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.
13
void setAccuracy(float accuracy)
Set the estimated accuracy of this location, meters.
14
void setAltitude(double altitude)
Set the altitude, in meters above sea level.
15
void setBearing(float bearing)
Set the bearing, in degrees.
16
void setLatitude(double latitude)
Set the latitude, in degrees.
17
void setLongitude(double longitude)
Set the longitude, in degrees.
18
void setSpeed(float speed)
Set the speed, in meters/second over ground.
19
String toString()
Returns a string containing a concise, human-readable description of this object.
GooglePlayServicesClient.ConnectionCallbacks
GooglePlayServicesClient.OnConnectionFailedListener
These interfaces provide following important callback methods, which you need to implement in
your activity class −
1
abstract void onConnected(Bundle connectionHint)
This callback method is called when location service is connected to the location client
successfully. You will use connect() method to connect to the location client.
2
abstract void onDisconnected()
This callback method is called when the client is disconnected. You will
use disconnect() method to disconnect from the location client.
3
abstract void onConnectionFailed(ConnectionResult result)
This callback method is called when there was an error connecting the client to the service.
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.
1
abstract void onLocationChanged(Location location)
This callback method is used for receiving notifications from the LocationClient when the
location has changed.
1
setExpirationDuration(long millis)
Set the duration of this request, in milliseconds.
2
setExpirationTime(long millis)
Set the request expiration time, in millisecond since boot.
3
setFastestInterval(long millis)
Explicitly set the fastest interval for location updates, in milliseconds.
4
setInterval(long millis)
Set the desired interval for active location updates, in milliseconds.
5
setNumUpdates(int numUpdates)
Set the number of location updates.
6
setPriority(int priority)
Set the priority of the request.
Now for example, if your application wants high accuracy location it should create a location
request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5
seconds. You can also use bigger interval and/or other priorities like
PRIORITY_LOW_POWER for to request "city" level accuracy or
PRIORITY_BALANCED_POWER_ACCURACY for "block" level accuracy.
Activities should strongly consider removing all location request when entering the background
(for example at onPause()), or at least swap the request to a larger interval and lower quality to
save power consumption.
Example
Following example shows you in practical how to to use Location Services in your app to get the
current location and its equivalent addresses etc.
To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.
Create Android Application
Step Description
1 You will use Android studio IDE to create an Android application and name it as under a
package com.example.tutorialspoint7.myapplication.
3 Modify src/MainActivity.java file and add required code as shown below to take care of getting
current location and its equivalent address.
4 Modify layout XML file res/layout/activity_main.xml to add all GUI components which include
three buttons and two text views to show location/address.
import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.test.mock.MockPackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
Button btnShowLocation;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
// GPSTracker class
GPSTracker gps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (ActivityCompat.checkSelfPermission(this,
mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {
@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);
}
});
}
}
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
</LinearLayout>
<category android:name =
"android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume that, you have connected your actual Android Mobile
device with your computer. To run the app from Android Studio, open one of your project's
activity files and click Run icon from the toolbar. Before starting your application, Android
studio installer will display following window to select an option where you want to run your
Android application.
Now to see location select Get Location Button which will display location information as
follows −
Google Maps
Android allows us to integrate google maps in our application. You can show any location on
the map , or can show different routes on the map e.t.c. You can also customize the map
according to your choices.
Google Map - Layout file
Now you have to add the map fragment into xml layout file. Its syntax is given below −
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.
READ_GSERVICES" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />
Enable/Disable zoom
You can also enable or disable the zoom gestures in the map by calling
the setZoomControlsEnabled(boolean) method. Its syntax is given below −
googleMap.getUiSettings().setZoomGesturesEnabled(true);
Apart from these customization, there are other methods available in the GoogleMap class , that
helps you more customize the map. They are listed below −
1 addCircle(CircleOptions options)
This method add a circle to the map
2 addPolygon(PolygonOptions options)
This method add a polygon to the map
3 addTileOverlay(TileOverlayOptions options)
This method add tile overlay to the map
4 animateCamera(CameraUpdate update)
This method Moves the map according to the update with an animation
5 clear()
This method removes everything from the map.
6 getMyLocation()
This method returns the currently displayed user location.
7 moveCamera(CameraUpdate update)
This method repositions the camera according to the instructions defined in the update
8 setTrafficEnabled(boolean enabled)
This method Toggles the traffic layer on or off.
9 snapshot(GoogleMap.SnapshotReadyCallback callback)
This method Takes a snapshot of the map
10 stopAnimation()
This method stops the camera animation if there is one in progress
Example
Here is an example demonstrating the use of GoogleMap class. It creates a basic M application
that allows you to navigate through the map.
To experiment with this example , you can run this on an actual device or in an emulator.
Create a project with google maps activity as shown below −
It will open the following screen and copy the console url for API Key as shown below −
Copy this and paste it to your browser. It will give the following screen −
Click on continue and click on Create API Key then it will show the following screen
tools:context="com.example.tutorialspoint7.myapplication.MapsActi
vity" />
package com.example.tutorialspoint7.myapplication;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the
map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be
used.
* This is where we can add markers or lines, add listeners
or move the camera.
* In this case, we just add a marker near Sydney,
Australia.
* If Google Play services is not installed on the device.
* This method will only be triggered once the user has
installed
Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng TutorialsPoint = new LatLng(21, 57);
mMap.addMarker(new
MarkerOptions().position(TutorialsPoint).title("Tutorialspoint.co
m"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(TutorialsPoint));
}
}
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not
required to use
Google Maps Android API v2, but you must specify either
coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a
string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key
used to sign the APK.
You need a different API key for each encryption key,
including the release key
that is used to sign the APK for publishing.
You can define the keys for the debug and
release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAXhBdyKxUo_cb-EkSgWJQTdqR0QjLcqes"
/>
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android application has been signed with a certificate with a private key Know the owner of the
application is unique. This allows the author of The application will be identified if needed. When
an application is installed in The phone is assigned a user ID, thus avoiding it from affecting it
Other applications by creating a sandbox for it. This user ID is permanent on which devices and
applications with the same user ID are allowed to run in a single process. This is a way to ensure
that a malicious application has Cannot access / compromise the data of the genuine application.
It is mandatory for an application to list all the resources it will Access during installation. Terms
are required of an application, in The installation process should be user-based or interactive
Check with the signature of the application.
The purpose of a permission is to protect the privacy of an Android user. Android apps must
request permission to access sensitive user data (such as contacts and SMS), as well as certain
system features (such as camera and internet). Depending on the feature, the system might grant
the permission automatically or might prompt the user to approve the request.
Permissions are divided into several protection levels. The protection level affects whether
runtime permission requests are required. There are three protection levels that affect third-party
apps: normal, signature, and dangerous permissions.
Normal permissions cover areas where your app needs to access data or resources outside the
app’s sandbox, but where there’s very little risk to the user’s privacy or the operation of other
apps. For example, permission to set the time zone is a normal permission. If an app declares in
its manifest that it needs a normal permission, the system automatically grants the app that
permission at install time. The system doesn’t prompt the user to grant normal permissions, and
users cannot revoke these permissions.
Signature permissions: The system grants these app permissions at install time, but only when the
app that attempts to use a permission is signed by the same certificate as the app that defines the
permission.
Dangerous permissions cover areas where the app wants data or resources that involve the user’s
private information, or could potentially affect the user’s stored data or the operation of other
apps. For example, the ability to read the user’s contacts is a dangerous permission. If an app
declares that it needs a dangerous permission, the user has to explicitly grant the permission to the
app. Until the user approves the permission, your app cannot provide functionality that depends
on that permission. To use a dangerous permission, your app must prompt the user to grant
permission at runtime. For more details about how the user is prompted, see Request prompt for
dangerous permission.
Android threat
However, the Android operating system also revealed some of its faults for the user may be
attacked and stolen personal information.
Some security vulnerabilities on Android:
– Leaking Information to Logs: Android provides centralized logging via the Log API, which can
displayed with the “logcat” command. While logcat is a debugging tool, applications with the
READ_LOGS permission can read these log messages. The Android documentation for this
permission indicates that “the logs can contain slightly private information about what is
happening on the device, but should never contain the user’s private information.”
– SDcard Use: Any application that has access to read or write data on the SDcard can read or
write any other application’s data on the SDcard.
– Unprotected Broadcast Receivers: Applications use broadcast receiver components to receive
intent messages. Broadcast receivers define “intent filters” to subscribe to specific event types are
public. If the receiver is not protected by a permission, a malicious application can forge
messages.
– Intent Injection Attacks: Intent messages are also used to start activity and service components.
An intent injection attack occurs if the in-tent address is derived from untrusted input.
– Wifi Sniffing: This may disrupt the data being transmitted from A device like many web sites
and applications does not have security measures strict security. The application does not encrypt
the data and therefore it can be Blocked by a listener on unsafe lines.
Security issues for smartphones running on the system Android operating system is the user does
not have the knowledge or careless installation of the software Malicious or other attacks such as
phishing. Important security issues The second is that some legitimate applications that have
vulnerabilities can be exploited.
This page describes how to use the Android Support Library to check for and request
permissions. The Android framework provides similar methods as of Android 6.0 but using the
support library makes it easier to provide compatibility with older versions of Android.
Add permissions to the manifest
On all versions of Android, to declare that your app needs a permission, put a <uses-
permission> element in your app manifest, as a child of the top-level <manifest> element.
For example, an app that needs to access the internet would have this line in the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">
<uses-permission android:name="android.permission.INTERNET"/>
<!-- other permissions go here -->
<application ...>
...
</application>
</manifest>
The system's behavior after you declare a permission depends on how sensitive the permission is.
Some permissions are considered "normal" so the system immediately grants them upon
installation. Other permissions are considered "dangerous" so the user must explicitly grant your
app access. For more information about the different kinds of permissions, see Protection
levels.
JAVA
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_CALENDAR)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
}
If the app has the permission, the method returns PERMISSION_GRANTED, and the app can
proceed with the operation. If the app does not have the permission, the method
returns PERMISSION_DENIED, and the app has to explicitly ask the user for permission.
Declaring and using permissions
Request permissions
When your app receives PERMISSION_DENIED from checkSelfPermission(), you need
to prompt the user for that permission. Android provides several methods you can use to request a
permission, such as requestPermissions(), as shown in the code snippet below. Calling
these methods brings up a standard Android dialog, which you cannot customize.
How this is displayed to the user depends on the device Android version as well as the target
version of your application.
One approach you might use is to provide an explanation only if the user has already denied that
permission request. Android provides a utility
method, shouldShowRequestPermissionRationale(), that returns true if the user has
previously denied the request, and returns false if a user has denied a permission and selected
the Don't ask again option in the permission request dialog, or if a device policy prohibits the
permission.
If a user keeps trying to use functionality that requires a permission, but keeps denying the
permission request, that probably means the user doesn't understand why the app needs the
permission to provide that functionality. In a situation like that, it's probably a good idea to show
an explanation.
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
// Permission has already been granted
}
The prompt shown by the system describes the permission group your app needs access to, not
the specific permission.
Note: When your app calls requestPermissions(), the system shows a standard dialog box to
the user. Your app cannot configure or alter that dialog box. If you need to provide any
information or explanation to the user, you should do that before you
call requestPermissions(), as described in Explain why the app needs permissions.
The dialog box shown by the system describes the permission group your app needs access to;
it does not list the specific permission. For example, if you request
the READ_CONTACTS permission, the system dialog box just says your app needs access to the
device's contacts. The user only needs to grant permission once for each permission group. If
your app requests any other permissions in that group (that are listed in your app manifest), the
system automatically grants them. When you request the permission, the system calls
your onRequestPermissionsResult() callback method and
passes PERMISSION_GRANTED, the same way it would if the user had explicitly granted your
request through the system dialog box.
Note: Your app still needs to explicitly request every permission it needs, even if the user has
already granted another permission in the same group. In addition, the grouping of permissions
into groups may change in future Android releases. Your code should not rely on the assumption
that particular permissions are or are not in the same group.
For example, suppose you list both READ_CONTACTS and WRITE_CONTACTS in your app
manifest. If you request READ_CONTACTS and the user grants the permission, and you then
request WRITE_CONTACTS, the system immediately grants you that permission without
interacting with the user.
If the user denies a permission request, your app should take appropriate action. For example,
your app might show a dialog explaining why it could not perform the user's requested action that
needs that permission.
When the system asks the user to grant a permission, the user has the option of telling the system
not to ask for that permission again. In that case, any time an app
uses requestPermissions() to ask for that permission again, the system immediately denies
the request. The system calls your onRequestPermissionsResult() callback method and
passes PERMISSION_DENIED, the same way it would if the user had explicitly rejected your
request again. The method also returns false if a device policy prohibits the app from having that
permission. This means that when you call requestPermissions(), you cannot assume that
any direct interaction with the user has taken place.
When using either of these tags, you can set the maxSdkVersion attribute to specify that, on
devices running a higher version, a particular permission isn't needed.
Custom permissions
Define a Custom App Permission
This document describes how app developers can use the security features provided by Android
to define their own permissions. By defining custom permissions, an app can share its resources
and capabilities with other apps.
Background
Android is a privilege-separated operating system, in which each app runs with a distinct system
identity (Linux user ID and group ID). Parts of the system are also separated into distinct
identities. Linux thereby isolates apps from each other and from the system.
Apps can expose their functionality to other apps by defining permissions which those other apps
can request. They can also define permissions which are automatically made available to any
other apps which are signed with the same certificate.
App signing
All APKs must be signed with a certificate whose private key is held by their developer. This
certificate identifies the author of the app. The certificate does not need to be signed by a
certificate authority; it is perfectly allowable, and typical, for Android apps to use self-signed
certificates. The purpose of certificates in Android is to distinguish app authors. This allows the
system to grant or deny apps access to signature-level permissions and to grant or deny an
app's request to be given the same Linux identity as another app.
Because security enforcement happens at the process level, the code of any two packages cannot
normally run in the same process, since they need to run as different Linux users. You can use
the sharedUserId attribute in the AndroidManifest.xml's manifest tag of each package
to have them assigned the same user ID. By doing this, for purposes of security the two packages
are then treated as being the same app, with the same user ID and file permissions. Note that in
order to retain security, only two apps signed with the same signature (and requesting the same
sharedUserId) will be given the same user ID.
Any data stored by an app will be assigned that app's user ID, and not normally accessible to
other packages.
For example, an app that wants to control who can start one of its activities could declare a
permission for this operation as follows:
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
<permission
android:name="com.example.myapp.permission.DEADLY_ACTIVITY"
android:label="@string/permlab_deadlyActivity"
android:description="@string/permdesc_deadlyActivity"
android:permissionGroup="android.permission-group.COST_MONEY"
android:protectionLevel="dangerous" />
...
</manifest>
Note: The system does not allow multiple packages to declare a permission with the same
name, unless all the packages are signed with the same certificate. If a package declares a
permission, the system does not permit the user to install other packages with the same
permission name, unless those packages are signed with the same certificate as the first
package. To avoid naming collisions, we recommend using reverse-domain-style naming for
custom permissions, for example com.example.myapp.ENGAGE_HYPERSPACE.
The protectionLevel attribute is required, telling the system how the user is to be informed
of apps requiring the permission, or who is allowed to hold that permission, as described in the
linked documentation.
The android:permissionGroup attribute is optional, and only used to help the system
display permissions to the user. In most cases you should set this to a standard system group
(listed in android.Manifest.permission_group), although you can define a group
yourself. It is preferable to use an existing group, as this simplifies the permission UI shown to
the user.
You need to supply both a label and description for the permission. These are string resources
that the user can see when they are viewing a list of permissions (android:label) or details
on a single permission (android:description). The label should be short; a few words
describing the key piece of functionality the permission is protecting. The description should be a
couple of sentences describing what the permission allows a holder to do. Our convention is a
two-sentence description: the first sentence describes the permission, and the second sentence
warns the user of the type of things that can go wrong if an app is granted the permission.
You can place a permission in the group by assigning the group name to
the <permission> element's permissionGroup attribute.
The <permission-tree> element declares a namespace for a group of permissions that are
defined in code.
If you are designing a suite of apps that expose functionality to one another, try to design the apps
so that each permission is defined only once. You must do this if the apps are not all signed with
the same certificate. Even if the apps are all signed with the same certificate, it's a best practice to
define each permission once only.
If the functionality is only available to apps signed with the same signature as the providing app,
you may be able to avoid defining custom permissions by using signature checks. When one of
your apps makes a request of another of your apps, the second app can verify that both apps are
signed with the same certificate before complying with the request.
Application Deployment
Publish your app
Publishing is the general process that makes your Android applications available to users. When
you publish an Android application you perform two main tasks:
At a minimum you need to remove Log calls and remove the android:debuggable attribute
from your manifest file. You should also provide values for
the android:versionCode and android:versionName attributes, which are located in
the <manifest> element. You may also have to configure several other settings to meet Google
Play requirements or accommodate whatever method you're using to release your application.
If you are using Gradle build files, you can use the release build type to set your build settings for
the published version of your app.
Building and signing a release version of your application.
You can use the Gradle build files with the release build type to build and sign a release version
of your application.
Testing the release version of your application.
Before you distribute your application, you should thoroughly test the release version on at least
one target handset device and one target tablet device.
Updating application resources for release.
You need to be sure that all application resources such as multimedia files and graphics are
updated and included with your application or staged on the proper production servers.
Preparing remote servers and services that your application depends on.
If your application depends on external servers or services, you need to be sure they are secure
and production ready.
You may have to perform several other tasks as part of the preparation process. For example, you
will need to get a private key for signing your application. You will also need to create an icon
for your application, and you may want to prepare an End User License Agreement (EULA) to
protect your person, organization, and intellectual property.
When you are finished preparing your application for release you will have a signed .apk file that
you can distribute to users.
Releasing your application on Google Play is a simple process that involves three basic steps:
To fully leverage the marketing and publicity capabilities of Google Play, you need to create
promotional materials for your application, such as screenshots, videos, graphics, and
promotional text.
Google Play lets you target your application to a worldwide pool of users and devices. By
configuring various Google Play settings, you can choose the countries you want to reach, the
listing languages you want to use, and the price you want to charge in each country. You can also
configure listing details such as the application type, category, and content rating. When you are
done configuring options you can upload your promotional materials and your application as a
draft (unpublished) application.
Publishing the release version of your application.
If you are satisfied that your publishing settings are correctly configured and your uploaded
application is ready to be released to the public, you can simply click Publish in the Play Console
and within minutes your application will be live .andavailable for download around the world.
When users browse to the download link from their Android-powered devices, the file is downloaded
and Android system automatically starts installing it on the device. However, the installation process
will start automatically only if the user has configured their Settings to allow the installation of apps
from unknown sources.
Although it is relatively easy to release your application on your own website, it can be inefficient.
For example, if you want to monetize your application you will have to process and track all financial
transactions yourself and you will not be able to use Google Play's In-app Billing service to sell in-
app products. In addition, you will not be able to use the Licensing service to help prevent
unauthorized installation and use of your application.
Once you developed and fully tested your Android Application, you can start selling or
distributing free using Google Play (A famous Android marketplace). You can also release your
applications by sending them directly to users or by letting users download them from your own
website.
You can check a detailed publishing process at Android official website, but this tutorial will
take you through simple steps to launch your application on Google Play. Here is a simplified
check list which will help you in launching your Android application −
Ste Activity
p
1 Regression Testing Before you publish your application, you need to make sure that its
meeting the basic quality expectations for all Android apps, on all of the devices that you are
targeting. So perform all the required testing on different devices including phone and tablets.
2 Application Rating When you will publish your application at Google Play, you will have to
specify a content rating for your app, which informs Google Play users of its maturity level.
Currently available ratings are (a) Everyone (b) Low maturity (c) Medium maturity (d) High
maturity.
3 Targeted Regions Google Play lets you control what countries and territories where your
application will be sold. Accordingly you must take care of setting up time zone, localization or
any other specific requirement as per the targeted region.
4 Application Size Currently, the maximum size for an APK published on Google Play is 50 MB.
If your app exceeds that size, or if you want to offer a secondary download, you can use APK
Expansion Files, which Google Play will host for free on its server infrastructure and
automatically handle the download to devices.
5 SDK and Screen Compatibility It is important to make sure that your app is designed to run
properly on the Android platform versions and device screen sizes that you want to target.
6 Application Pricing Deciding whether you app will be free or paid is important because, on
Google Play, free app's must remain free. If you want to sell your application then you will have
to specify its price in different currencies.
8 Build and Upload release-ready APK The release-ready APK is what you you will upload to
the Developer Console and distribute to users. You can check complete detail on how to create
a release-ready version of your app: Preparing for Release.
9 Finalize Application Detail Google Play gives you a variety of ways to promote your app and
engage with users on your product details page, from colourful graphics, screen shots, and
videos to localized descriptions, release details, and links to your other apps. So you can
decorate your application page and provide as much as clear crisp detail you can provide.
Next select, Generate Signed APK option as shown in the above screen shot and then click it
so that you get following screen where you will choose Create new keystore to store your
application.
Enter your key store path,key store password,key alias and key password to protect your
application and click on Next button once again. It will display following screen to let you
create an application −
Once you filled up all the information,like app destination,build type and flavours
click finish button While creating an application it will show as below
Finally, it will generate your Android Application as APK formate File which will be uploaded
at Google Play marketplace.