SlideShare une entreprise Scribd logo
1  sur  33
Android APIs: Phone, Camera,
SMS, GPS, Email
Using Permissions
●

●

●

A basic android application has no permission
associated with it by default.
To make use of the protected features of the
device we declare the <uses-permissions> in
our manifest file.
Permissions are granted by the users when
the application is installed, not while it's
running.
Using Permissions
●

Attributes:
–

android:name
●
●

The name of the permission.
android.permission.CAMERA, etc.

For more: http://bit.ly/19g9vw0
android:maxSdkVersion
●

–

●

●

The highest API level at which the permission should be
granted to your app.
Optional to declare.
Accessing in-built features
●

We always use Intent for this purpose.

●

We have separate ids for these features:
–
–

●

Intent.ACTION_VIEW
Intent.ACTION_SEND

Use of other methods, like:
–

intent.setType()

–

intent.setData()

are also seen.
Phone Call
●

Permission:
<uses-permission android:name=
“android.permission.CALL_PHONE”/>

●

Code:
Intent i = new Intent(Intent.ACTION_CALL);
i.setData(Uri.parse(“tel:980XXXXXXX”));
startActivity(i);
Phone Call
●

If you just want to direct the user to his/her
dialer:
Intent i = new Intent(Intent.ACTION_DIAL);
startActivity(i);

●

No permissions required here.
SMS
●

Code:
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("smsto:980XXXXXXX"));
startActivity(i);

●

No permissions here.
SMS
●

What if I want to send a message to a user from my
application ??
–

Use SmsManager.
●

–
●

Manages SMS operations such as sending data, text SMS
messages.

Get this object by calling the static method getDefault().

Permission:
<uses-permission android:name=
“android.permission.SEND_SMS”/>
SMS
●

private void sendSMS(String phoneNumber, String message) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";

Message and to which
toSend.putExtra("number", phoneNumber); number is it to be sent
Intent toSend = new Intent(SENT);

PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
toSend, 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, sentPI,
deliveredPI);
}

Actual work is done
SMS
●

What is PendingIntent ?
–

Because sending SMS is not our app's function,
the Intent call is forwarded to a foreign
application (to our default messaging app).

–

Using pending intents we specify an action to
take in the future using the same permissions as
your application.
sendTextMessage()
●

The parameters to provide are:
–

First parameter: Destination number/address.

–

Second parameter: Source number/address.

–

Third parameter: The message to be sent

–

Forth parameter: Pending intent/sent intent.

–

Fifth parameter: Pending intent/delivery intent
(was the message delivered?)
Email
●

Permission:
<uses-permission=
“android.permission.INTERNET”/>

●

Coding:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
startActivity(i);
Email
●

Sending the user straight to G-Mail:
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setType("text/html");
i.setData(Uri.parse("mailto:xxx@abc.com"));
startActivity(i);

●

Adding preset subject and message:
i.putExtra(Intent.EXTRA_SUBJECT, “abc”);
i.putExtra(Intent.EXTRA_TEXT, “abc”);
Email
●

Sending the user straight to G-Mail:
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setType("text/html");
i.setData(Uri.parse("mailto:xxx@abc.com"));
startActivity(i);

●

Adding preset subject and message:
i.putExtra(Intent.EXTRA_SUBJECT, “abc”);
i.putExtra(Intent.EXTRA_TEXT, “abc”);
Email
●

Sending the user straight to G-Mail (simple):
i.setClassName("com.google.android.gm",
"com.google.android.gm.ConversationListActivity");
Camera : Permissions
●

Camera Permissions*
–

Use the device

<uses-permission
android:name= “android.permission.CAMERA”/>
●

Camera Features
–

Use camera features

<uses-permission
android:name= “android.hardware.camera”/>
Camera : Permissions
●

Storage Permissions*
–

The application saves images/videos to the
device's external storage

<uses-permission
android:name=
“android.permission.WRITE_EXTERNAL_STORAGE”/>
Camera : Coding
●

Our goal here is to
display the photo
taken by the user
when the camera
was called.
Camera : Coding
●

Logic
–

Because the shot photo is to be called back into
the activity:
●
●
●

–

Set up a directory for the image.
Get the output media file from that directory.
startActivityForResult() is to be called.

Use of Bitmap to show the image captured.
Global Variables
// Activity request codes
private static final int
CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store the captured images
private static final String IMAGE_DIRECTORY_NAME =
"my_camera_app";
// file url to store image
private Uri fileUri;
Camera : Coding
●

Taking a picture:
private void captureImage() {
Intent intent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent,
CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

Instantiated using
helper methods
Activity for result
●

●

●

A method that is used when we would like to
receive something
Launch an activity and listen for results when
finished
When this activity exits, your
onActivityResult() method will be called with
the given requestCode
Activity for result
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Successfully captured the image display in imageview
previewImage();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(), "Sorry! Failed to
capture image", Toast.LENGTH_SHORT).show();
}
}
}
previewImage()
private void previewImage() {
try {
// Bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
// Downsizing image as it throws OutOfMemory exception for
larger images
options.inSampleSize = 5;
final Bitmap bitmap =
BitmapFactory.decodeFile(fileUri.getPath(), options);
photo.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
Helper method
●

Get media file:
–

Setting the external sdcard location.

–

Checking on the storage directory(if it does not exist).

–

Naming the media.

–

Returning the media.

private static File getOutputMediaFile(int type) {
...
return mediaFile;
}
Get the media file
●

Setting up the external sdcard location:
File mediaStorageDir = new
File(Environment.getExternalStoragePublicDirec
tory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);

Directory path
Directory name to store
captured image, declared as a global variable.
Get the media file
●

Checking on the storage directory, if it does not
exist:
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed
create "+ IMAGE_DIRECTORY_NAME + "
directory");
return null;
}
}
Get the media file
●

Naming the media
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new
File(mediaStorageDir.getPath() +
File.separator + "IMG_" + ".jpg");
} else {
return null;
}
Get the media file
●
●

Finally, return the mediaFile.
Because this file is referred to from an URI,
the file is to be converted to an URI.
public Uri getOutputMediaFileUri(int type) {
return
Uri.fromFile(getOutputMediaFile(type));
}
Full code: http://bit.ly/1gIVSOS
For further reference: http://bit.ly/1bSk4MH
GPS
●

Permission:
<uses-permission android:name=
“android.permission.ACCESS_FINE_LOCATION”/>

●

Coding
–

–

Objective : Check if GPS is on or not.
● Call on the GPS settings intent.
If on, show coordinates.
● Call the location manager.
Call on the GPS settings
●

Intent GPSSettingIntent = new
Intent(android.provider.Settings.ACTION_LOCATI
ON_SOURCE_SETTINGS);
LocationManager
●

●

This class provides access to the system location
services.
These services allow applications:
–

–

●

to obtain periodic updates of the device's geographical
location.
to fire an application-specified Intent when the device
enters the proximity of a given geographical
location.

We instantiate LocationManager through:
Context.getSystemService(Context.LOCATION_SERVICE)
LocationManager
●

Checking to see if the location provider is enabled or
not:
if(locationManager.isProviderEnabled(LocationMana
ger.GPS_PROVIDER))

●

Fetch the location using the getLastKnowLocation():
Location location =
locationManager.getLastKnownLocation(LocationMana
ger.GPS_PROVIDER);
double latitude = location.getLatitude();
double longitude = location.getLongitude();

Full code: http://bit.ly/1i8YyEs

Contenu connexe

Tendances

Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon Berlin
 

Tendances (20)

Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
An introduction to Angular2
An introduction to Angular2 An introduction to Angular2
An introduction to Angular2
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
React render props
React render propsReact render props
React render props
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
 
Extend sdk
Extend sdkExtend sdk
Extend sdk
 
Angular2 workshop
Angular2 workshopAngular2 workshop
Angular2 workshop
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
React outbox
React outboxReact outbox
React outbox
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0
 
React native app with type script tutorial
React native app with type script tutorialReact native app with type script tutorial
React native app with type script tutorial
 
GWT Training - Session 2/3
GWT Training - Session 2/3GWT Training - Session 2/3
GWT Training - Session 2/3
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS Introduction
 
Anton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 lightAnton Minashkin Dagger 2 light
Anton Minashkin Dagger 2 light
 
Speed up your GWT coding with gQuery
Speed up your GWT coding with gQuerySpeed up your GWT coding with gQuery
Speed up your GWT coding with gQuery
 
Speed up the site building with Drupal's Bootstrap Layout Builder
Speed up the site building with Drupal's Bootstrap Layout BuilderSpeed up the site building with Drupal's Bootstrap Layout Builder
Speed up the site building with Drupal's Bootstrap Layout Builder
 
Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2 Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2
 
F1
F1F1
F1
 
Data Flow Patterns in Angular 2 - Sebastian Müller
Data Flow Patterns in Angular 2 -  Sebastian MüllerData Flow Patterns in Angular 2 -  Sebastian Müller
Data Flow Patterns in Angular 2 - Sebastian Müller
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
 

Similaire à Day 6

Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; Share
Anuchit Chalothorn
 
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Frédéric Harper
 
04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)
TECOS
 
Mobile, web and cloud - the triple crown of modern applications
Mobile, web and cloud -  the triple crown of modern applicationsMobile, web and cloud -  the triple crown of modern applications
Mobile, web and cloud - the triple crown of modern applications
Ido Green
 
Parsing in ios to create an app
Parsing in ios to create an appParsing in ios to create an app
Parsing in ios to create an app
HeaderLabs .
 
Intents: Talking to your neighbors
Intents: Talking to your neighborsIntents: Talking to your neighbors
Intents: Talking to your neighbors
cketti
 
Third-party App Stores on Android.pptx.pdf
Third-party App Stores on Android.pptx.pdfThird-party App Stores on Android.pptx.pdf
Third-party App Stores on Android.pptx.pdf
Aayush Gupta
 
Lecture 12 - Maps, AR_VR_aaaaHardware.pptx
Lecture 12 - Maps, AR_VR_aaaaHardware.pptxLecture 12 - Maps, AR_VR_aaaaHardware.pptx
Lecture 12 - Maps, AR_VR_aaaaHardware.pptx
NgLQun
 

Similaire à Day 6 (20)

Android App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; ShareAndroid App Development 07 : Intent &amp; Share
Android App Development 07 : Intent &amp; Share
 
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
Windows 8 Pure Imagination - 2012-11-25 - Extending Your Game with Windows 8 ...
 
Android - Android Intent Types
Android - Android Intent TypesAndroid - Android Intent Types
Android - Android Intent Types
 
Android Froyo
Android FroyoAndroid Froyo
Android Froyo
 
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on AndroidMobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
 
04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)
 
Android Quiz App – Test Your IQ.pdf
Android Quiz App – Test Your IQ.pdfAndroid Quiz App – Test Your IQ.pdf
Android Quiz App – Test Your IQ.pdf
 
Mobile, web and cloud - the triple crown of modern applications
Mobile, web and cloud -  the triple crown of modern applicationsMobile, web and cloud -  the triple crown of modern applications
Mobile, web and cloud - the triple crown of modern applications
 
Hello android example.
Hello android example.Hello android example.
Hello android example.
 
Fundamental of android
Fundamental of androidFundamental of android
Fundamental of android
 
Intent, Service and BroadcastReciver (2).ppt
Intent, Service and BroadcastReciver (2).pptIntent, Service and BroadcastReciver (2).ppt
Intent, Service and BroadcastReciver (2).ppt
 
Getting Ready For Android Wear
Getting Ready For Android WearGetting Ready For Android Wear
Getting Ready For Android Wear
 
Parsing in ios to create an app
Parsing in ios to create an appParsing in ios to create an app
Parsing in ios to create an app
 
Something about Intents and URI permissions
Something about Intents and URI permissionsSomething about Intents and URI permissions
Something about Intents and URI permissions
 
Android App Development - 14 location, media and notifications
Android App Development - 14 location, media and notificationsAndroid App Development - 14 location, media and notifications
Android App Development - 14 location, media and notifications
 
The Glass Class - Tutorial 3 - Android and GDK
The Glass Class - Tutorial 3 - Android and GDKThe Glass Class - Tutorial 3 - Android and GDK
The Glass Class - Tutorial 3 - Android and GDK
 
Intents: Talking to your neighbors
Intents: Talking to your neighborsIntents: Talking to your neighbors
Intents: Talking to your neighbors
 
Third-party App Stores on Android.pptx.pdf
Third-party App Stores on Android.pptx.pdfThird-party App Stores on Android.pptx.pdf
Third-party App Stores on Android.pptx.pdf
 
ANDROID
ANDROIDANDROID
ANDROID
 
Lecture 12 - Maps, AR_VR_aaaaHardware.pptx
Lecture 12 - Maps, AR_VR_aaaaHardware.pptxLecture 12 - Maps, AR_VR_aaaaHardware.pptx
Lecture 12 - Maps, AR_VR_aaaaHardware.pptx
 

Plus de Vivek Bhusal (9)

Training Session 2 - Day 2
Training Session 2 - Day 2Training Session 2 - Day 2
Training Session 2 - Day 2
 
Training Session 2
Training Session 2 Training Session 2
Training Session 2
 
Android training day 3
Android training day 3Android training day 3
Android training day 3
 
Android training day 1
Android training day 1Android training day 1
Android training day 1
 
Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)
 
Mybudget
MybudgetMybudget
Mybudget
 
Wisevote - opendataweek @
Wisevote - opendataweek @Wisevote - opendataweek @
Wisevote - opendataweek @
 
Android training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcampAndroid training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcamp
 
My medical info
My medical infoMy medical info
My medical info
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Dernier (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

Day 6

  • 1. Android APIs: Phone, Camera, SMS, GPS, Email
  • 2. Using Permissions ● ● ● A basic android application has no permission associated with it by default. To make use of the protected features of the device we declare the <uses-permissions> in our manifest file. Permissions are granted by the users when the application is installed, not while it's running.
  • 3. Using Permissions ● Attributes: – android:name ● ● The name of the permission. android.permission.CAMERA, etc. For more: http://bit.ly/19g9vw0 android:maxSdkVersion ● – ● ● The highest API level at which the permission should be granted to your app. Optional to declare.
  • 4. Accessing in-built features ● We always use Intent for this purpose. ● We have separate ids for these features: – – ● Intent.ACTION_VIEW Intent.ACTION_SEND Use of other methods, like: – intent.setType() – intent.setData() are also seen.
  • 5. Phone Call ● Permission: <uses-permission android:name= “android.permission.CALL_PHONE”/> ● Code: Intent i = new Intent(Intent.ACTION_CALL); i.setData(Uri.parse(“tel:980XXXXXXX”)); startActivity(i);
  • 6. Phone Call ● If you just want to direct the user to his/her dialer: Intent i = new Intent(Intent.ACTION_DIAL); startActivity(i); ● No permissions required here.
  • 7. SMS ● Code: Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("smsto:980XXXXXXX")); startActivity(i); ● No permissions here.
  • 8. SMS ● What if I want to send a message to a user from my application ?? – Use SmsManager. ● – ● Manages SMS operations such as sending data, text SMS messages. Get this object by calling the static method getDefault(). Permission: <uses-permission android:name= “android.permission.SEND_SMS”/>
  • 9. SMS ● private void sendSMS(String phoneNumber, String message) { String SENT = "SMS_SENT"; String DELIVERED = "SMS_DELIVERED"; Message and to which toSend.putExtra("number", phoneNumber); number is it to be sent Intent toSend = new Intent(SENT); PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, toSend, 0); PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0); SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI); } Actual work is done
  • 10. SMS ● What is PendingIntent ? – Because sending SMS is not our app's function, the Intent call is forwarded to a foreign application (to our default messaging app). – Using pending intents we specify an action to take in the future using the same permissions as your application.
  • 11. sendTextMessage() ● The parameters to provide are: – First parameter: Destination number/address. – Second parameter: Source number/address. – Third parameter: The message to be sent – Forth parameter: Pending intent/sent intent. – Fifth parameter: Pending intent/delivery intent (was the message delivered?)
  • 12. Email ● Permission: <uses-permission= “android.permission.INTERNET”/> ● Coding: Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); startActivity(i);
  • 13. Email ● Sending the user straight to G-Mail: Intent i = new Intent(Intent.ACTION_SENDTO); i.setType("text/html"); i.setData(Uri.parse("mailto:xxx@abc.com")); startActivity(i); ● Adding preset subject and message: i.putExtra(Intent.EXTRA_SUBJECT, “abc”); i.putExtra(Intent.EXTRA_TEXT, “abc”);
  • 14. Email ● Sending the user straight to G-Mail: Intent i = new Intent(Intent.ACTION_SENDTO); i.setType("text/html"); i.setData(Uri.parse("mailto:xxx@abc.com")); startActivity(i); ● Adding preset subject and message: i.putExtra(Intent.EXTRA_SUBJECT, “abc”); i.putExtra(Intent.EXTRA_TEXT, “abc”);
  • 15. Email ● Sending the user straight to G-Mail (simple): i.setClassName("com.google.android.gm", "com.google.android.gm.ConversationListActivity");
  • 16. Camera : Permissions ● Camera Permissions* – Use the device <uses-permission android:name= “android.permission.CAMERA”/> ● Camera Features – Use camera features <uses-permission android:name= “android.hardware.camera”/>
  • 17. Camera : Permissions ● Storage Permissions* – The application saves images/videos to the device's external storage <uses-permission android:name= “android.permission.WRITE_EXTERNAL_STORAGE”/>
  • 18. Camera : Coding ● Our goal here is to display the photo taken by the user when the camera was called.
  • 19. Camera : Coding ● Logic – Because the shot photo is to be called back into the activity: ● ● ● – Set up a directory for the image. Get the output media file from that directory. startActivityForResult() is to be called. Use of Bitmap to show the image captured.
  • 20. Global Variables // Activity request codes private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100; public static final int MEDIA_TYPE_IMAGE = 1; // directory name to store the captured images private static final String IMAGE_DIRECTORY_NAME = "my_camera_app"; // file url to store image private Uri fileUri;
  • 21. Camera : Coding ● Taking a picture: private void captureImage() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // start the image capture Intent startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); } Instantiated using helper methods
  • 22. Activity for result ● ● ● A method that is used when we would like to receive something Launch an activity and listen for results when finished When this activity exits, your onActivityResult() method will be called with the given requestCode
  • 23. Activity for result protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) { if (resultCode == RESULT_OK) { // Successfully captured the image display in imageview previewImage(); } else { // failed to capture image Toast.makeText(getApplicationContext(), "Sorry! Failed to capture image", Toast.LENGTH_SHORT).show(); } } }
  • 24. previewImage() private void previewImage() { try { // Bitmap factory BitmapFactory.Options options = new BitmapFactory.Options(); // Downsizing image as it throws OutOfMemory exception for larger images options.inSampleSize = 5; final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options); photo.setImageBitmap(bitmap); } catch (NullPointerException e) { e.printStackTrace(); } }
  • 25. Helper method ● Get media file: – Setting the external sdcard location. – Checking on the storage directory(if it does not exist). – Naming the media. – Returning the media. private static File getOutputMediaFile(int type) { ... return mediaFile; }
  • 26. Get the media file ● Setting up the external sdcard location: File mediaStorageDir = new File(Environment.getExternalStoragePublicDirec tory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME); Directory path Directory name to store captured image, declared as a global variable.
  • 27. Get the media file ● Checking on the storage directory, if it does not exist: if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "+ IMAGE_DIRECTORY_NAME + " directory"); return null; } }
  • 28. Get the media file ● Naming the media File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + ".jpg"); } else { return null; }
  • 29. Get the media file ● ● Finally, return the mediaFile. Because this file is referred to from an URI, the file is to be converted to an URI. public Uri getOutputMediaFileUri(int type) { return Uri.fromFile(getOutputMediaFile(type)); } Full code: http://bit.ly/1gIVSOS For further reference: http://bit.ly/1bSk4MH
  • 30. GPS ● Permission: <uses-permission android:name= “android.permission.ACCESS_FINE_LOCATION”/> ● Coding – – Objective : Check if GPS is on or not. ● Call on the GPS settings intent. If on, show coordinates. ● Call the location manager.
  • 31. Call on the GPS settings ● Intent GPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATI ON_SOURCE_SETTINGS);
  • 32. LocationManager ● ● This class provides access to the system location services. These services allow applications: – – ● to obtain periodic updates of the device's geographical location. to fire an application-specified Intent when the device enters the proximity of a given geographical location. We instantiate LocationManager through: Context.getSystemService(Context.LOCATION_SERVICE)
  • 33. LocationManager ● Checking to see if the location provider is enabled or not: if(locationManager.isProviderEnabled(LocationMana ger.GPS_PROVIDER)) ● Fetch the location using the getLastKnowLocation(): Location location = locationManager.getLastKnownLocation(LocationMana ger.GPS_PROVIDER); double latitude = location.getLatitude(); double longitude = location.getLongitude(); Full code: http://bit.ly/1i8YyEs