0% found this document useful (0 votes)
51 views48 pages

And Unit 6

The document discusses two methods to send SMS in Android - using the SMSManager API and using Intents. The SMSManager API allows sending SMS directly from an application by calling sendTextMessage(). An Intent can also be used to invoke the default SMS app to send an SMS by setting the action and data. Permissions are required to send SMS, with <uses-permission android:name="android.permission.SEND_SMS"/> added to the manifest. A sample program is provided to send SMS on button click using the SMSManager API, with layout XML, activity code, and manifest configuration.

Uploaded by

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

And Unit 6

The document discusses two methods to send SMS in Android - using the SMSManager API and using Intents. The SMSManager API allows sending SMS directly from an application by calling sendTextMessage(). An Intent can also be used to invoke the default SMS app to send an SMS by setting the action and data. Permissions are required to send SMS, with <uses-permission android:name="android.permission.SEND_SMS"/> added to the manifest. A sample program is provided to send SMS on button click using the SMSManager API, with layout XML, activity code, and manifest configuration.

Uploaded by

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

Unit No:06

SMS Telephony

Q.Write methods to send SMS in android

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

Android Send SMS using SMSManager API


In android, to send SMS using SMSManager API we need to write the code like as shown below.

SmsManager smgr = SmsManager.getDefault();


smgr.sendTextMessage(MobileNumber,null,Message,null,null);
SMSManager API required SEND_SMS permission in our android manifest to send SMS. Following is
the code snippet to set SEND_SMS permissions in manifest file.

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

Android Send SMS using Intent


In android, Intent is a messaging object which is used to request an action from another app component
such as activities, services, broadcast receivers, and content providers. To know more about an Intent
object in android check this Android Intents with Examples.

To send SMS using the Intent object, we need to write the code like as shown below.

Intent sInt = new Intent(Intent.ACTION_VIEW);


sInt.putExtra("address", new String[]{txtMobile.getText().toString()});
sInt.putExtra("sms_body",txtMessage.getText().toString());
sInt.setType("vnd.android-dir/mms-sms");
Even for Intent, it required a SEND_SMS permission in our android manifest to send SMS. Following is
the code snippet to set SEND_SMS permissions in manifest file.

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

1
Unit No:06 Mobile Application Development P.S.Gaidhani
Q. Write a program to send SMS
Activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="Mobile No" />
<EditText
android:id="@+id/mblTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<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>

2
Unit No:06 Mobile Application Development P.S.Gaidhani
MainActvity.java

package com.example.myapplicationsms;
import android.content.Intent;
import android.net.Uri;
import android.provider.Telephony;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText txtMobile;


private EditText txtMessage;
private Button btnSms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtMobile = (EditText)findViewById(R.id.mblTxt);
txtMessage = (EditText)findViewById(R.id.msgTxt);
btnSms = (Button)findViewById(R.id.btnSend);
btnSms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(txtMobile.getText().toString(),null,txtMessage.getText().toString(),n
ull,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();
}
}
});
}
}

3
Unit No:06 Mobile Application Development P.S.Gaidhani
Manifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package=" com.example.myapplicationsms">
<uses-permission android:name="android.permission.SEND_SMS"/>
<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/AppTheme">
<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>
Output

4
Unit No:06 Mobile Application Development P.S.Gaidhani
In case if we want to use Intents to send SMS to replace button click code like as shown below.

btnSms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("smsto:"));
i.setType("vnd.android-dir/mms-sms");
i.putExtra("address", new String(txtMobile.getText().toString()));
i.putExtra("sms_body",txtMessage.getText().toString());
startActivity(Intent.createChooser(i, "Send sms via:"));
}
catch(Exception e){
Toast.makeText(MainActivity.this, "SMS Failed to Send, Please try again", Toast.LENGTH_SH
ORT).show();
}
}
});

5
Unit No:06 Mobile Application Development P.S.Gaidhani
Q. Write a program to send mail in android

how we are going to use the Intent for sending mails through our application.
1. Action in Intent to Send an Email
The action that we will use is ACTION_SEND.
And we will use the following syntax and write it like this to add Action Send.
2. Intent myIntent = new Intent(Intent.ACTION_SEND);
Data in Intent to Send an Email
3. To send the email, we will specify the email-Id using setData in mailto: as URI data.
We will do it as follows:
myIntent.setData(Uri.parse("mailto:"));
myIntent.setType("text/plain");
putExtra() Method in Android
4. We use the method known as putExtra() to add some extra information in our Intent. It can add
the following in the information as Extra:
 EXTRA_CC – It holds string[] of email addresses that should be carbon copied.
 EXRTA_BCC – It holds string[] of email addresses that should be blind carbon copied.
 EXTRA_SUBJECT – It is a constant string that holds the subject line of a message.
 EXTRA_EMAIL – It‟s a string that holds an email to be delivered.
 EXTRA_TEXT – It is a string that associates with the Intent ACTION_SEND to supply literal data.
 EXTRA_HTML_TEXT – It is a string that associates with the Intent as an alternative to send
EXTRA_TEXT in HTML.

Program

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"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:id="@+id/tV1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"

6
Unit No:06 Mobile Application Development P.S.Gaidhani
android:layout_marginLeft="90dp"
android:layout_marginTop="60dp"

android:text="DataFlair "
android:textColor="@color/colorPrimaryDark"
android:textSize="50dp" />
<EditText
android:id="@+id/textTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Mail To" />
<EditText
android:id="@+id/textSubject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject:" />
<EditText
android:id="@+id/textMessage"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Content:" />
<Button
android:id="@+id/buttonSend"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send" />
</LinearLayout>

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplicationsms">

<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="message/rfc822"
/>
</intent-filter>
</activity>
</application>

</manifest>

package com.example.myapplicationsms;

import androidx.appcompat.app.AppCompatActivity;

7
Unit No:06 Mobile Application Development P.S.Gaidhani
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private EditText mailTo;
private EditText mailSubject;
private EditText mailContent;
private Button subbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mailTo = (EditText) findViewById(R.id.textTo);
mailSubject = (EditText) findViewById(R.id.textMessage);
mailContent = (EditText) findViewById(R.id.textMessage);
subbtn = (Button) findViewById(R.id.buttonSend);
subbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, new String[]{mailTo.getText().toString()});
it.putExtra(Intent.EXTRA_SUBJECT, mailSubject.getText().toString());
it.putExtra(Intent.EXTRA_TEXT, mailContent.getText());
it.setType("message/rfc822");
startActivity(Intent.createChooser(it, "Choose Mail App"));
}
});
}
}

8
Unit No:06 Mobile Application Development P.S.Gaidhani
Location Based Services:

Q. Explain methods to display Google Map in Android


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
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"/>

Google Map - AndroidManifest file


The next thing you need to do is to add some permissions along with the Google Map API key in the
AndroidManifest.XML file. Its syntax is given below −
<!--Permissions-->

<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" />

<!--Google MAP API key-->

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />

Customizing Google Map


You can easily customize google map from its default view , and change it according to your demand.
Adding Marker
You can place a maker with some text over it displaying your location on the map. It can be done by
via addMarker() method.
Its syntax is given below −
final LatLng Nashik = new LatLng(21 , 57);
Marker TP = googleMap.addMarker(new MarkerOptions()
.position(Nashik).title("Nashik"));

9
Unit No:06 Mobile Application Development P.S.Gaidhani
Changing Map Type
You can also change the type of the MAP. There are four different types of map and each give a
different view of the map. These types are Normal,Hybrid,Satellite and terrain. You can use them as
below
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

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);
googleMap.getUiSettings().setZoomGesturesEnabled(false);

Apart from these customization, there are other methods available in the GoogleMap class , that helps
you more customize the map. They are listed below −
Sr.No Method & description

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.

10
Unit No:06 Mobile Application Development P.S.Gaidhani
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

Q. Write a program to create Google map Activity and steps generate API Key
1. File->New->New Project->

Cl\

11
Unit No:06 Mobile Application Development P.S.Gaidhani
12
Unit No:06 Mobile Application Development P.S.Gaidhani
3. Open google_maps_api.xml File

13
Unit No:06 Mobile Application Development P.S.Gaidhani
4. Copy & Paste it on your browser

5. Login to your Gmail account

5. Click Continue

14
Unit No:06 Mobile Application Development P.S.Gaidhani
6. Click on Create API Key

15
Unit No:06 Mobile Application Development P.S.Gaidhani
7. Click on CREATE CREDENTIALS->API Key

16
Unit No:06 Mobile Application Development P.S.Gaidhani
8. Copy API Key and paste in google_maps_api.xml file as shown below in
<string name="google_maps_key" templateMergeStrategy="preserve"
translatable="false">AIzaSyDT5I1pBPfAqNeah5k9jD7OGczWGnfkMRo</string>

17
Unit No:06 Mobile Application Development P.S.Gaidhani
9. Run the Program
Activity_maps.xml
<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=".MapsActivity" />

Google_maps_api.xml
<resources>
<string name="google_maps_key" templateMergeStrategy="preserve"
translatable="false">AIzaSyDT5I1pBPfAqNeah5k9jD7OGczWGnfkMRo</string>
</resources>

Maps_activity.java
package com.example.myapplicationgooglemap;

import androidx.fragment.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;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@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);
}

public void onMapReady(GoogleMap googleMap) {


mMap = googleMap;

// Add a marker in Sydney and move the camera


LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}

18
Unit No:06 Mobile Application Development P.S.Gaidhani
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplicationgooglemap">

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

<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/AppTheme">

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />

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

Output:

19
Unit No:06 Mobile Application Development P.S.Gaidhani
20
Unit No:06 Mobile Application Development P.S.Gaidhani
Q. Display Zoom In and Zoom Out in Android

MapsActivity.java

package com.example.myapplication;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ZoomControls;
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;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

GoogleMap mMap;
ZoomControls z1;
@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);

z1=findViewById(R.id.z1);
z1.setOnZoomInClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMap.animateCamera(CameraUpdateFactory.zoomIn());
}
});

z1.setOnZoomOutClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMap.animateCamera(CameraUpdateFactory.zoomOut());
}
});

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

LatLng nashik = new LatLng(19.99, 73.78);


mMap.addMarker(new MarkerOptions().position(nashik).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(nashik));

}
}

21
Unit No:06 Mobile Application Development P.S.Gaidhani
Android_Manifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">

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

<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/AppTheme">

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />

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

Activity_maps.xml

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


<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=".MapsActivity" >

<ZoomControls
android:id="@+id/z1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

22
Unit No:06 Mobile Application Development P.S.Gaidhani
/>

</fragment>
Google_maps_api.xml
<resources>
<string name="google_maps_key" templateMergeStrategy="preserve"
translatable="false">AIzaSyDT5I1pBPfAqNeah5k9jD7OGczWGnfkMRo</string>
</resources>

Output:

23
Unit No:06 Mobile Application Development P.S.Gaidhani
Q. Write a program to find current location in android

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.currentlocation.MainActivity">

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Current Location"
android:id="@+id/getLocationBtn"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/locationText"
android:layout_below="@id/getLocationBtn"/>
</RelativeLayout>
AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.currentlocation">

<uses-permission android:name="android.permission.ACCESS_FINE_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">
<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>

24
Unit No:06 Mobile Application Development P.S.Gaidhani
MainActivity.java

package com.currentlocation;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LocationListener {


Button getLocationBtn;
TextView locationText;

LocationManager locationManager;

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

getLocationBtn = (Button)findViewById(R.id.getLocationBtn);
locationText = (TextView)findViewById(R.id.locationText);

getLocationBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getLocation();
}
});
}

void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}

@Override
public void onLocationChanged(Location location) {
locationText.setText("Current Location: " + location.getLatitude() + ", " + location.getLongitude());
}

@Override
public void onProviderDisabled(String provider) {

25
Unit No:06 Mobile Application Development P.S.Gaidhani
Toast.makeText(MainActivity.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

@Override
public void onProviderEnabled(String provider) {

}
}
Screenshot

26
Unit No:06 Mobile Application Development P.S.Gaidhani
Q.Explain Geocodng and reverse Geocoding in Android

27
Unit No:06 Mobile Application Development P.S.Gaidhani
28
Unit No:06 Mobile Application Development P.S.Gaidhani
29
Unit No:06 Mobile Application Development P.S.Gaidhani
Android Security Model

Q.Explain the android security model

The key components of the Android Security Program include:

 Design review:
 The Android security process begins early in the development lifecycle with the creation
of a rich and configurable security model and design.
 Each major feature of the platform is reviewed by engineering and security resources, with
appropriate security controls integrated into the architecture of the system.
 Penetration testing and code review:
 During the development of the platform, Android-created and open source components are
subject to vigorous security reviews.
 These reviews are performed by the Android Security Team, Google‟s Information
Security Engineering team, and independent security consultants.
 The goal of these reviews is to identify weaknesses and possible weaknesses well before
major releases, and to simulate the types of analysis that are performed by external
security experts upon release.
 Open source and community review:
 It enables broad security review by any interested party. Android also uses open source
technologies that have undergone significant external security review, such as the Linux
kernel.
 Google Play provides a forum for users and companies to provide information about
specific apps directly to users.
 Incident response:
 Even with these precautions, security issues may occur after shipping, which is why the
Android project has created a comprehensive security response process.
 Full-time Android security team members monitor the Android-specific and the general
security community for discussion of potential vulnerabilities and review security bugs
filed on the Android bug database.
 Monthly security updates:
 The Android security team provides monthly updates to Google Android devices and all
our device manufacturing partners.

30
Unit No:06 Mobile Application Development P.S.Gaidhani
Platform security architecture

Android seeks to be the most secure and usable operating system for mobile platforms by repurposing
traditional operating system security controls to:

 Protect app and user data


 Protect system resources (including the network)
 Provide app isolation from the system, other apps, and from the user

To achieve these objectives, Android provides these key security features:

 Robust security at the OS level through the Linux kernel


 Mandatory app sandbox for all apps
 Secure interprocess communication
 App signing
 App-defined and user-granted permissions

31
Unit No:06 Mobile Application Development P.S.Gaidhani
Q. What are permissions in android?

 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.
 A central design point of the Android security architecture is that no app, by default, has
permission to perform any operations that would adversely impact other apps, the operating
system, or the user. This includes reading or writing the user's private data (such as contacts or
emails), reading or writing another app's files, performing network access, keeping the device
awake, and so on.

Declaring and Using Permissions

Permission approval

An app must publicize the permissions it requires by including <uses-permission> tags in the app
manifest. For example, an app that needs to send SMS messages 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.SEND_SMS"/>

<application ...>
...
</application>
</manifest>

If your app lists normal permissions in its manifest (that is, permissions that don't pose much risk to the
user's privacy or the device's operation), the system automatically grants those permissions to your app.

If your app lists dangerous permissions in its manifest (that is, permissions that could potentially affect
the user's privacy or the device's normal operation), such as the SEND_SMS permission above, the user
must explicitly agree to grant those permissions.

Runtime requests (Android 6.0 and higher)

 If the device is running Android 6.0 (API level 23) or higher, and the SdkVersion is 23 or higher,
the user isn't notified of any app permissions at install time. Your app must ask the user to grant
the dangerous permissions at runtime.

32
Unit No:06 Mobile Application Development P.S.Gaidhani
 When your app requests permission, the user sees a system dialog (as shown in figure 1, left)
telling the user which permission group your app is trying to access. The dialog includes a Deny
and Allow button.

 If the user denies the permission request, the next time your app requests the permission, the
dialog contains a checkbox that, when checked, indicates the user doesn't want to be prompted for
the permission again (see figure 1, right).

Figure 1. Initial permission dialog (left) and secondary permission request with option to turn off further
requests (right)

If the user checks the Never ask again box and taps Deny, the system no longer prompts the user if you
later attempt to requests the same permission.

Even if the user grants your app the permission it requested you cannot always rely on having it. Users
also have the option to enable and disable permissions one-by-one in system settings. You should always
check for and request permissions at runtime to guard against runtime errors

33
Unit No:06 Mobile Application Development P.S.Gaidhani
Install-time requests (Android 5.1.1 and below)

If the device is running Android 5.1.1 (API level 22) or lower, or the app's SdkVersion is 22 or lower
while running on any version of Android, the system automatically asks the user to grant all dangerous
permissions for your app at install-time (see figure 2).

Figure 2. Install-time permission dialog

If the user clicks Accept, all permissions the app requests are granted. If the user denies the permissions
request, the system cancels the installation of the app.

If an app update includes the need for additional permissions the user is prompted to accept those new
permissions before updating the app.

Request prompts to access sensitive user information

Some apps depend on access to sensitive user information related to call logs and SMS messages. If you
want to request the permissions specific to call logs and SMS messages and publish your app to the Play

34
Unit No:06 Mobile Application Development P.S.Gaidhani
Store, you must prompt the user to set your app as the default handler for a core system function before
requesting these runtime permissions.

Q. Explain Permission Groups


Permission groups

 Permissions are organized into groups related to a device's capabilities or features.


 Under this system, permission requests are handled at the group level and a single permission
group corresponds to several permission declarations in the app manifest. For example, the SMS
group includes both the READ_SMS and the RECEIVE_SMS declarations.
 Grouping permissions in this way enables the user to make more meaningful and informed
choices, without being overcome by complex and technical permission requests.

 All dangerous Android permissions belong to permission groups. Any permission can belong to a
permission group regardless of protection level. However, a permission's group only affects the
user experience if the permission is dangerous.

35
Unit No:06 Mobile Application Development P.S.Gaidhani
Q. Explain with syntax Custom Permission

syntax:

<permission android:description="string resource"


android:icon="drawable resource"
android:label="string resource"
android:name="string"
android:permissionGroup="string"
android:protectionLevel=["normal" | "dangerous" |
"signature" | ...] />

contained in:

<manifest>

description:

Declares a security permission that can be used to limit access to specific components or features
of this or other applications.

attributes:

android:description

A user-readable description of the permission, longer and more informative than the label. It may
be displayed to explain the permission to the user — for example, when the user is asked whether
to grant the permission to another application.

This attribute must be set as a reference to a string resource; unlike the label attribute, it cannot
be a raw string.

android:icon

A reference to a drawable resource for an icon that represents the permission.

android:label

A name for the permission, one that can be displayed to users.

As a convenience, the label can be directly set as a raw string while you're developing the
application. However, when the application is ready to be published, it should be set as a
reference to a string resource, so that it can be localized like other strings in the user interface.

android:name

36
Unit No:06 Mobile Application Development P.S.Gaidhani
The name of the permission. This is the name that will be used in code to refer to the permission
— for example, in a <uses-permission> element and the permission attributes of application
components.

android:permissionGroup

Assigns this permission to a group. The value of this attribute is the name of the group, which
must be declared with the <permission-group> element in this or another application. If this
attribute is not set, the permission does not belong to a group.

android:protectionLevel

Characterizes the potential risk implied in the permission and indicates the procedure the system
should follow when determining whether or not to grant the permission to an application
requesting it.

Each protection level consists of a base permission type and zero or more flags. For example, the
"dangerous" protection level has no flags. In contrast, the protection level
"signature|privileged" is a combination of the "signature" base permission type and the
"privileged" flag.

The following table shows all base permission types. For a list of flags, see protectionLevel.

Value Meaning

"normal" The default value. A lower-risk permission that gives requesting applications
access to isolated application-level features, with minimal risk to other
applications, the system, or the user. The system automatically grants this type
of permission to a requesting application at installation, without asking for the
user's explicit approval (though the user always has the option to review these
permissions before installing).
"dangerous" A higher-risk permission that would give a requesting application access to
private user data or control over the device that can negatively impact the user.
Because this type of permission introduces potential risk, the system may not
automatically grant it to the requesting application. For example, any dangerous
permissions requested by an application may be displayed to the user and
require confirmation before proceeding, or some other approach may be taken
to avoid the user automatically allowing the use of such facilities.
"signature" A permission that the system grants only if the requesting application is signed
with the same certificate as the application that declared the permission. If the
certificates match, the system automatically grants the permission without
notifying the user or asking for the user's explicit approval.
"signatureOrSystem" Old synonym for "signature|privileged". Deprecated in API level 23.

A permission that the system grants only to applications that are in a dedicated
folder on the Android system image or that are signed with the same certificate
as the application that declared the permission. Avoid using this option, as the
37
Unit No:06 Mobile Application Development P.S.Gaidhani
signature protection level should be sufficient for most needs and works
regardless of exactly where apps are installed. The "signatureOrSystem"
permission is used for certain special situations where multiple vendors have
applications built into a system image and need to share specific features
explicitly because they are being built together.

Q. Explain the steps of signing an application or steps to generate signed APK for Android
Application

Prerequisites For Publishing Your App On The Google Play Store

Before publishing your app, you should have in mind how would other people see it in the Google
Play Store, just like you view every app that has been published before. To do this, you should build a
structure and gather all the things you need to have to present a well-made App.

1. Google Play Publisher Account: The account you‟ll be using to publish and handle all your apps and
information.

2. Signed APK of your application: Required since Android needs all the APK files you upload to the
store to be digitally signed with a certificate.

3. App Icon: the size of your icon should be on a 512 x 512 32-bit format, saved as PNG: any other
format won‟t be accepted on the App Store.

4. Feature Graphic: With a size of 1024 x 500 JPEG or 24-bit PNG without alpha.

Screenshots from your Phone or Tablet need at least two images on JPEG, or the same as with your
Feature Graphic, 24 via PNG without alpha. In case of Tablet, your screenshots should be from 7 and 10-
inch tablets if required. Keep in mind that the minimum length for any side is 320 px and a max length is
3840 px.

5. Both a short and long description for your app

38
Unit No:06 Mobile Application Development P.S.Gaidhani
Steps:

1. Create a Google Developer Account


2. Links to our Merchant Account
3. Creating an App
4. Preparing Store Listing
5. Graphic Assets
6. Languages & Translations
7. Categorization
8. Contact Details
9. Privacy Policy
10. Upload APK to release your app
11. Provide the right content rating
12. Setup pricing & distribution
13. Publishing your app

39
Unit No:06 Mobile Application Development P.S.Gaidhani
Steps to publish an Android App on Google Play

Once you have gathered all the requirements for your app, you can proceed to follow these steps and
have your app published in no time.
1. Google Developer Account
Creating your Developer account should be the first thing you‟ll have to do if you want to publish an app
on the Play Store which is a straightforward process.
The registration fee for a Google Developer Account is a single payment of $25. You can only go ahead
with the payment after reviewing and accepting their Developer Distribution Agreement. You can do it
with a debit or credit card.
After paying and filling every necessary detail on your account, which includes your name as a developer
(the one your customers will be able to see on the store), you‟ll have to wait two days before the
registration is processed. If you missed any details, you could add them later.
2. Links To Your Merchant Account
The Merchant Account is a payment center profile, something you‟ll need if you‟re looking to publish an
app that‟s paid, or planning to add the option to purchase things inside your app as a freemium
app─which are currently dominating the Google Play Store.

40
Unit No:06 Mobile Application Development P.S.Gaidhani
You‟ll have to create your Merchant Account for it, and what you have to do is:
1. Access The Google Play Console.
2. Go to “Download Reports,” specifically “Financial.”
3. Click on the tab telling you to set up your merchant account.
4. Enter all the information about your business.
After you set up your profile, your developer account will be linked to it automatically.
This Merchant Account lets you manage from app sales to payouts (monthly) on your account. In
addition to this, you‟ll be able to study your reports from sales through the Google Play Developer
Console.
3. Creating an App
Don‟t get confused here; you won‟t be making the app all over again. Once you‟ve set up the Developer
Play Console, you‟ll be able to include your app by doing the following:
1. Go to „All applications‟.
2. Hit „Create Application‟.
3. Click the default language for your app from a drop-down list.
4. Set your app‟s title.
5. Click “Create”.
The app‟s title appears Google Play only after publishing, so there‟s no need to worry about that in this
stage since you will be able to change or update the name afterward as many times as you need.

Once you have your app created, you‟ll find yourself on the entry page for the store, where you‟ll have to
provide all the info required to list your app on the store.
4. Preparing Store Listing
Once your app has been created, you should start looking for the details on the store listing.
The way your app page looks like in the Google Play Store will play a crucial role in how many users it
will react to it.
Keep in mind that you can save the draft for this step and come back to it afterward since this step isn‟t
needed to advance to the next one.
Store Listing divides itself into at least six categories, which cover product details, graphic assets,
languages and translations, categorization, contact details, and privacy policy.

41
Unit No:06 Mobile Application Development P.S.Gaidhani
5. Product Details

Here is where you‟ll describe your product; The next step is filling out three fields.
 Title. : Your app‟s name on the Google Play Store, it has a 50 characters limit, and it accepts one
localized title per language.
 Short Description: The short description will be the first text to be seen when looking at your
app‟s detail page on the Play Store app. It has a maximum limit of 80 characters.
 Full Description: Users can expand the short description to view the app‟s full description, which
will show the app‟s description on Google Play. It has a 4,000 characters limit.
Keep in mind that, if you want your app to have a high performance in the App Store, you should write
your title and description with your user‟s experience as a priority.
With the use of right keywords, you‟ll have something to catch users‟ attention, but try not to overdo it.
Your app shouldn‟t look like spam or a promotion, for it can be suspended by the Play Store!

42
Unit No:06 Mobile Application Development P.S.Gaidhani
6. Graphic Assets:

Graphic assets are all the media content you‟ll add on your app page. here, you can show everything,
from screenshots and videos to promotional graphics, that demonstrate your app‟s features and its
functionality.
There are necessary things on the graphics assets, such as images, feature graphics, or an icon with high
resolution. Everything else is optional, but having them on your app will be seen more attractive to
visitors.
Each asset will have its specific requirements, such as formatting or its dimensions, like the App icon,
which needs a size of 512 x 512 with a 32-bit PNG format, while the Feature images should have a size
of 1024 x 500 JEPG format or a 24-bit PNG without alpha.
7. Languages and Translations
Here, you can set up your languages and translations, so you can add a translation for the information
relevant to your app on the listing details, which can go in combination with screenshots in-language and
other localized images.
Google also offers its users the option to translate the information from your app automatically.

43
Unit No:06 Mobile Application Development P.S.Gaidhani
8. Categorization

Are you going to publish a health-care app? Perhaps you‟re going with a task-helper app, or maybe
you‟re trying to upload a game. If so, would it be a racing game or an adventure type of game?
The categorization tab asks you to choose category and type that belongs to your app. You can easily
click on “game” or “app” for the type of application from a drop-down menu.
For each app that‟s found in this Play Store, there are various categories for it, so be sure to pick what fits
your app the best.
Then, you can add the content rating, but if you want to give a rating for your content, you‟ll” have to
submit an APK first; feel free to skip this for now.

44
Unit No:06 Mobile Application Development P.S.Gaidhani
9. Contact Details

Here, you‟ll set your contact details as a way to offer support to your customers regarding your app.
In this section, don‟t hold yourself to one contact channel. You can add several channels for contact,
letting your customers reach you from your email address, your website, and through your phone
number.
10. Privacy Policy
Some apps tend to ask for access to user data and permissions that may be sensitive. Make sure you enter
a privacy policy that adequately explains how your app collects the data and how it uses it.
It‟s mandatory to attach a link (URL) to the privacy policy provided in the store listing to your app, to
ensure it‟s working properly.
Once you finished the store listing step, you can then click the „Save Draft‟ button for saving your
details; this way, if you skipped some steps, you‟ll be able to return to them before publishing your app.

45
Unit No:06 Mobile Application Development P.S.Gaidhani
Q. Developer console in android
The Developer Console
To publish Android Application on Google Play Store you need create Google Play Developer Account
Once you've registered and received verification by email, you can sign in to your Google Play Android
Developer Console, which will be the home for your app publishing operations and tools on Google Play.
This sections below introduce a few of the key areas you'll find in the Developer Console.
Your Developer Profile

Developer profile: Specifies your developer identity and contact information, stores your developer key,
and more.
Your developer profile identifies you to Google Play and to your customers. During registration you can
provide information for your profile, but you can go back at any time to edit the information and change
your settings.
Your developer profile contains:
 Your developer name — the name you want to show users on your product details page and elsewhere
on Google Play.
 Your developer contact information — how Google can contact you if needed (this information isn't
exposed to users.
 Merchant information, in-app billing information.
 Your developer public key for licensing and In-app Billing.

Multiple user accounts


If you are working with a team, you can set up multiple user accounts to access different parts of your
Developer Console. The first account registered is the account owner, with full access to all parts of the
46
Unit No:06 Mobile Application Development P.S.Gaidhani
Console. The owner can add user accounts and manage what parts of the Console they have access to.
For example, an owner can grant users access to publishing and app configuration, but not access to
financial reports.
Linking your Merchant Account
If you want to sell apps or in-app products, you can link your Google Checkout Merchant account to your
developer profile. Google Play uses the linked Checkout account for financial and tax identification and
monthly payouts of sales.
Your product and listing details
The Developer Console lets you set up a colorful storefront page for your app called the product details
page. Your product details page is the home for your app in Google Play — it's the page users see on
their mobile phones or on the web when they want to learn about your app and download it.
You can upload custom brand assets, screen shots, and videos to highlight what's great about your app,
and you can provide a localized description, add notes about the latest version, and more. You can update
your store listing at any time, even if you don‟t have a new version of your application.
Uploading and publishing
From the Developer Console you can quickly upload a release-ready APK and publish it when you're
ready. The app is a draft until you publish it, at which time Google Play makes your product details page
and app available to users. You can unpublish the app at any time.
Distribution Controls
In the Developer Console you can manage what countries and territories the app is distributed to and, for
some countries, you can choose what carriers you want to target.
You can also see the list of devices that your app is currently available to, based on any distribution rules
declared in its manifest file.
Selling and pricing your Products
The Developer Console gives you tools to set prices for your apps and in-app products. Your app can
either be free to download or priced (charged before download).
 If you publish your app as free, it must remain free. Free apps can be downloaded by any users in
Google Play.
 If you publish it as priced, you can change it to free, Priced apps can be purchased and downloaded
only by users who have registered a forms of payment in Google Play.
In addition, you can sell in-app products and subscriptions in your app, whether it is free or priced. You
can set prices separately for priced apps, in-app products, and subscriptions.
If you are selling a priced app or in-app products or subscriptions, the Developer Console lets you set
prices in a large number of different currencies. When users around the world visit your product details
page, they see the price of your app in their own currency. For most countries, the price you set is the
final price charged to users, inclusive of taxes.
To help you manage your prices, the Developer Console provides an autofill capability that uses recent
exchange rates to populate the prices in all supported currencies. You can change prices for apps and in-
app products at any time, just by saving changes in the Develoer Console.

In-app Billing
For details on how to implement In-app Billing, see the In-app Billing developer documentation.

47
Unit No:06 Mobile Application Development P.S.Gaidhani
In-app Billing is a Google Play service that lets you monetize your apps in more ways by selling in-app
products and subscriptions. In-app products are one-time purchases, while subscriptions are recurring
charges on an monthly or annual basis.
From the Developer Console you can create product lists for in-app products and subscriptions, set
prices, and publish.

User reviews page: Gives you access to user reviews for a specific app. You can filter reviews in a
number of ways to locate issues more easily and support your customers more effectively.
User reviews and error reports
Google Play makes it easy for users to submit reviews of your app for the benefit of other users. The
reviews are also extremely important to you, since they give you usability feedback, support requests,
and important functionality issues direct from your customers.
The Developer console also lets you see error reports, with stack trace and other data, submitted
automatically from Android devices, for debugging and improving your app.
App statistics
The Developer Console gives you detailed statistics on the install performance of your app.
You can view installations of your app measured by unique users, as well as by unique devices. For user
installations, you can view active installs, total installs, and daily installs and uninstalls. For devices, you
can see active installs as well as daily installs, uninstalls, and upgrades.
You can zoom into the installation numbers along several dimensions, including Android platform
version, device, country, language, app version, and carrier (mobile operator). You can see the
installation data for each dimension on a timeline charts.
At a glance, these charts highlight your app‟s installation peaks and longer-term trends, which you can
correlate to promotions, app improvements, or other factors. You can even focus in on data inside a
dimension by adding specific points (such as individual platform versions or languages) to the timeline.

48
Unit No:06 Mobile Application Development P.S.Gaidhani

You might also like