191CS53 Mobile Application Development NOTES
191CS53 Mobile Application Development NOTES
ENGINEERING COLLEGE
(An Autonomous Institution, Affiliated to Anna University, Chennai)
Sevalpatti (P.O), Sivakasi - 626140.
Virudhunagar Dt.
LECTURE NOTES
SEMSTER :V
DEPARTMENT
OF
PREPARED BY
Dr.C. NATARAJAN
ASP/CSE
L T P C
191CS53 MOBILE APPLICATION DEVELOPMENT
3 0 0 3
Programme: B.E. Computer Science and Engineering Sem: 5 Category: PC
Prerequisites: 191CS42 – Object Oriented Programming
Aim: To provide students with the tools and knowledge necessary to create mobile
applications that can run on mobile devices.
Course Outcomes: The Students will be able to
CO1: Classify the various Android Applications using layout and menus.
CO2: Demonstrate the audio, video and animation application.
CO3: Explain the fundamentals concepts of web database application.
CO4: Develop various types of sensors in Android.
CO5: Interpret applications to hand-held devices.
CO6: Design and Develop the mobile application (Mini Project).
ANDROID OVERVIEW 9
Overview of Android platform- Android SDK features - setting up the mobile app development
environment along with an emulator- Android Application Development Architecture - creating an
applications and activities -Application manifest
INTERFACE TOOLS 9
Creating user interface - Views - creating views - Layouts - Drawable resources - resolution and
density independence - Menus - Intents - Adapters - Using Internet resources - Dialogs.
FILES AND DATABASES 9
Saving Simple Application Data - creating and saving preferences - preferences activity -saving
activity state - loading files - file management tools-sending emails through application - Introducing
Android databases -SQLite - Web Database- Firebase, MySQL-PHP
SMALL COMPUTING TECNOLOGY AND SENSORS 9
Audio, Video Using the Camera - Telephony And SMS - Bluetooth Networks - Managing network
connectivity - WI-FI - Sensors-Sensors and the Sensor Manager - Interpreting sensor values-Using
the compass, Accelerometer and Orientation sensor.
ADVANCED TECHNOLOGY 9
Paranoid Android - Using Wake Locks - AIDL to Support IPC for Services -General API’s- Payment-
gateway, Android jetpack-Technology II-IOS-Introduction to Objective C-IOS features.
Total Periods: 45
Text Book:
1. Jeff Mc Wherter and Scott Gowell, “ Professional Mobile Application Development” Wrox,2012
2. David Mark, Jack Nutting, Jeff LaMarche and Frederic Olsson “Beginning ios 6 Development:
Exploring the iOS SDK”, Apress, 2013
3. “Teach Yourself Android Application Development in 24 Hours”, SAMS publication, 3/e, 2013
References:
1. Anubhav Pradhan, Anil V. Deshpande, “Composing Mobile Apps: Learn. Explore. Apply. Using
Android”, Wiley publication, 2014.
2. Barry Burd, “Android Application Development All in one for Dummies”, John Wiley & Sons
publication,2011.
3. http://developer.android.com/develop/index.htm
4. https://www.tutorialspoint.com/android
5. http://www.androidhive.info/
6. https://www.codeschool.com/learn/ios
Program
Course Program Outcomes
Specific
Outcomes (POs)
Outcomes
(PSOs)
PO1 PO PO PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PS PSO PSO3 PSO
2 3 O1 2 4
CO1 3 2 2 3 3 3 3
CO2 3 2 3 2 1
CO3 3 2 3 2
CO4 3 2 3 3 3 3
CO5 3 2 3 2 1
CO6 3 2 3 3 3 3
PREPARED BY APPROVED BY
ANDROID OVERVIEW
Overview of Android platform- Android SDK features - setting up the mobile app
development environment along with an emulator- Android Application Development
Architecture - creating an applications and activities -Application manifest
Android
Android is a software package and linux based operating system for mobile devices such as
tablet computers and smartphones.
It is developed by Google and later the OHA (Open Handset Alliance). Java language is
mainly used to write the android code even though other languages can be used.
The goal of android project is to create a successful real-world product that improves the
mobile experience for end users.
There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream
Sandwich, Froyo, Ecliar, Donut etc which is covered in next page.
Android Open Source Project so we can customize the OS based on our requirements.
Android supports different types of connectivity for GSM, CDMA, Wi-Fi, Bluetooth,
etc. for telephonic conversation or data transfer.
Using wifi technology we can pair with other devices while playing games or using
other applications.
It contains multiple APIs to support location-tracking services such as GPS.
We can manage all data storage-related activities by using the file manager.
It contains a wide range of media supports like AVI, MKV, FLV, MPEG4, etc. to play
or record a variety of audio/video.
It also supports different image formats like JPEG, PNG, GIF, BMP, MP3, etc.
It supports multimedia hardware control to perform playback or recording using a
camera and microphone.
Android has an integrated open-source WebKit layout-based web browser to support
User Interfaces like HTML5, and CSS3.
Android supports multi-tasking means we can run multiple applications at a time and
can switch between them.
It provides support for virtual reality or 2D/3D Graphics.
Applications –
Applications is the top layer of android architecture. The pre-installed applications like
home, contacts, camera, gallery etc and third party applications downloaded from the play
store like chat applications, games etc. will be installed on this layer only.
It runs within the Android run time with the help of the classes and services provided by the
application framework.
Application framework –
Application Framework provides several important classes which are used to create an
Android application. It provides a generic abstraction for hardware access and also helps in
managing the user interface with application resources. Generally, it provides the services
with the help of which we can create a particular class and make that class helpful for the
Applications creation.
It includes different types of services activity manager, notification manager, view system,
package manager etc. which are helpful for the development of our application according to
the prerequisite.
Activity Manger:
gives information about, and interacts with, activities, services, and the containing process.
Windows Manager:
The interface that apps use to talk to the window manager. Each window manager instance
is bound to a Display.
Notification Manager
Android allows to put notification into the titlebar of your application. The user can expand
the notification bar and by selecting the notification the user can trigger another activity.
Package Manager
Package Manager is a highly powerful application to manage apps, both system and user,
installed on an android device.
Content Provider
Content Provider is a part of an android application and it will act like more like a
relational database to store the app data. We can perform multiple operations like insert,
update, delete and edit on the data stored in content provider
using insert(), update(), delete() and query() methods.
View sytems:
View system’s is a basic building block of UI (User Interface) in android. A view is a small
rectangular box that responds to user inputs. Eg: EditText, Button, CheckBox, etc.
Application runtime –
Android Runtime environment is one of the most important part of Android. It contains
components like core libraries and the Dalvik virtual machine(DVM). Mainly, it provides
the base for the application framework and powers our application with the help of the core
libraries.
Like Java Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-based
virtual machine and specially designed and optimized for android to ensure that a device
can run multiple instances efficiently. It depends on the layer Linux kernel for threading
and low-level memory management. The core libraries enable us to implement android
applications using the standard JAVA or Kotlin programming languages.
Platform libraries –
The Platform Libraries includes various C/C++ core libraries and Java based libraries such
as Media, Graphics, Surface Manager, OpenGL etc. to provide a support for android
development.
Media library provides support to play and record an audio and video formats.
Surface manager responsible for managing access to the display subsystem.
SGL and OpenGL both cross-language, cross-platform application program interface
(API) are used for 2D and 3D computer graphics.
SQLite provides database support and FreeType provides font support.
Web-Kit This open source web browser engine provides all the functionality to display
web content and to simplify page loading.
SSL (Secure Sockets Layer) is security technology to establish an encrypted link
between a web server and a web browser.
Linux Kernel –
Linux Kernel is heart of the android architecture. It manages all the available drivers such
as display drivers, camera drivers, Bluetooth drivers, audio drivers, memory drivers, etc.
which are required during the runtime.
The Linux Kernel will provide an abstraction layer between the device hardware and the
other components of android architecture. It is responsible for management of memory,
power, devices etc.
The features of Linux kernel are:
Security: The Linux kernel handles the security between the application and the system.
Memory Management: It efficiently handles the memory management thereby
providing the freedom to develop our apps.
Process Management: It manages the process well, allocates resources to processes
whenever they need them.
Network Stack: It effectively handles the network communication.
Driver Model: It ensures that the application works properly on the device and hardware
manufacturers responsible for building their drivers into the Linux build.
Topic 3:
Start-> My computer -> local disk(c:) -> Program Files ->Android -> AndroidStudio -
> bin -> studio64
Dalvik Virtual Machine | DVM
As we know the modern JVM is high performance and provides excellent memory
management. But it needs to be optimized for low-powered handheld devices as well.
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.
Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM.
Multiple class files are converted into one dex file.
Let's see the compiling and packaging process from the source file:
The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file. It is a
platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.
DVM uses its own byte code and runs the JVM uses java byte code and
2 “.Dex” file. From Android 2.2 SDK runs “.class” file having JIT
Dalvik has got a Just in Time compiler (Just In Time).
Android application:
Bound by an application manifest-that describes each component and how they all interact, as
well as application metadata including its hardware and platform requirements
The following six components provides the building block for your applications
Activities
Services
Content Providers
Intents
Broadcast receivers
Widgets
Activity
An activity is the single screen in android. It is like window or frame of Java.By the help of
activity, you can place all your UI components or widgets in a single screen.The 7 lifecycle
method of Activity describes how activity will behave at different states.Android Activity
Lifecycle methods
Method Description
onResume called when activity will start interacting with the user.
File: activity_main.xml
It provides the details about the invocation of life cycle methods of activity. In this example,
we are displaying the content on the logcat.
File: MainActivity.java
package example.javatpoint.com.activitylifecycle;
1. import android.app.Activity;
2. import android.os.Bundle;
3. import android.util.Log;
4.
5. public class MainActivity extends Activity {
6.
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. Log.d("lifecycle","onCreate invoked");
12. }
13. @Override
14. protected void onStart() {
15. super.onStart();
16. Log.d("lifecycle","onStart invoked");
17. }
18. @Override
19. protected void onResume() {
20. super.onResume();
21. Log.d("lifecycle","onResume invoked");
22. }
23. @Override
24. protected void onPause() {
25. super.onPause();
26. Log.d("lifecycle","onPause invoked");
27. }
28. @Override
29. protected void onStop() {
30. super.onStop();
31. Log.d("lifecycle","onStop invoked");
32. }
33. @Override
34. protected void onRestart() {
35. super.onRestart();
36. Log.d("lifecycle","onRestart invoked");
37. }
38. @Override
39. protected void onDestroy() {
40. super.onDestroy();
41. Log.d("lifecycle","onDestroy invoked");
42. }
43. }
Output:
You will not see any output on the emulator or device. You need to open logcat.
Now see on the logcat: onCreate, onStart and onResume methods are invoked.
Now click on the HOME Button. You will see onPause method is invoked.
Android service is a component that is used to perform operations on the background such as
playing music, handle network transactions, interacting content providers etc. It doesn't has
any UI (user interface).
Moreover, service can be bounded by a component to perform interactivity and inter process
communication (IPC).
There can be two forms of a service.The lifecycle of service can follow two different paths:
started or bound.
1. Started
2. Bound
1) Started Service
A service is started when component (like activity) calls startService() method, now it runs in
the background indefinitely. It is stopped by stopService() method. The service can stop itself
by calling the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method. The
client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.
Suppose, I want to play music in the background, so call startService() method. But I want to
get information of the current song being played, I will bind the service that provides
information about the current song.
Let's see the example of service in android that plays an audio in the background. Audio will
not be stopped even if you switch to another activity. To stop the audio, you need to stop the
service.
activity_main.xml
Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:
File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.androidservice.MainActivity">
8.
9.
10. <Button
11. android:id="@+id/buttonStart"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignParentTop="true"
15. android:layout_centerHorizontal="true"
16. android:layout_marginTop="74dp"
17. android:text="Start Service" />
18.
19. <Button
20. android:id="@+id/buttonStop"
21. android:layout_width="wrap_content"
22. android:layout_height="wrap_content"
23. android:layout_centerHorizontal="true"
24. android:layout_centerVertical="true"
25. android:text="Stop Service" />
26.
27. <Button
28. android:id="@+id/buttonNext"
29. android:layout_width="wrap_content"
30. android:layout_height="wrap_content"
31. android:layout_alignParentBottom="true"
32. android:layout_centerHorizontal="true"
33. android:layout_marginBottom="63dp"
34. android:text="Next Page" />
35. </RelativeLayout>
activity_next.xml
File: activity_next.xml
Service class
Now create the service implemenation class by inheriting the Service class and overridding
its callback methods.
MyService.java
1. package example.javatpoint.com.androidservice;
2.
3. import android.app.Service;
4. import android.content.Intent;
5. import android.media.MediaPlayer;
6. import android.os.IBinder;
7. import android.support.annotation.Nullable;
8. import android.widget.Toast;
9.
10. public class MyService extends Service {
11. MediaPlayer myPlayer;
12. @Nullable
13. @Override
14. public IBinder onBind(Intent intent) {
15. return null;
16. }
17. @Override
18. public void onCreate() {
19. Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
20.
21. myPlayer = MediaPlayer.create(this, R.raw.sun);
22. myPlayer.setLooping(false); // Set looping
23. }
24. @Override
25. public void onStart(Intent intent, int startid) {
26. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
27. myPlayer.start();
28. }
29. @Override
30. public void onDestroy() {
31. Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
32. myPlayer.stop();
33. }
34. }
Activity class
Now create the MainActivity class to perform event handling. Here, we are writing the code
to start and stop service. Additionally, calling the second activity on buttonNext.
File: MainActivity.java
1. package example.javatpoint.com.androidservice;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity implements View.OnClickListener{
10. Button buttonStart, buttonStop,buttonNext;
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. buttonStart = findViewById(R.id.buttonStart);
17. buttonStop = findViewById(R.id.buttonStop);
18. buttonNext = findViewById(R.id.buttonNext);
19.
20. buttonStart.setOnClickListener(this);
21. buttonStop.setOnClickListener(this);
22. buttonNext.setOnClickListener(this);
23.
24.
25. }
26. public void onClick(View src) {
27. switch (src.getId()) {
28. case R.id.buttonStart:
29.
30. startService(new Intent(this, MyService.class));
31. break;
32. case R.id.buttonStop:
33. stopService(new Intent(this, MyService.class));
34. break;
35. case R.id.buttonNext:
36. Intent intent=new Intent(this,NextPage.class);
37. startActivity(intent);
38. break;
39. }
40. }
41. }
NextPage class
File: NextPage.java
1. package example.javatpoint.com.androidservice;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class NextPage extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_next);
12. }
13. }
File: AndroidManifest.xml
https://data-flair.training/blogs/content-provider-in-android/
Content Providers in Android
Content Providers are an important component of Android. They handle the access to the
central repository and supply data from one application to another on request. This task of
handling is done by methods of ContentResolver class. So, content providers can store data in
various ways such as files, database or over the internet.
Many a time we need to share our data with applications and that’s where it becomes useful.
The following diagram depicts how the content provider helps in sharing data with
applications from data stores.
As can be seen, the content provider lets us collect the data centrally and provide them to
applications as shown in the above diagram. Content providers act the same as database and
also we can query it to add, delete, insert or update the data.
It can be understood that a content provider hides the database details and also, it lets an
application share data among other applications. Content providers are not limited to texts,
but also contains images and videos as well.
CRUD Operations
Content providers provide the following four basic operations. These are also known as
CRUD operations, where
C – Create
R – Read
U – Update
D – Delete
The above are the four operations of content providers :
We need to use the ContentResolver object in our application, in order to communicate with
the content providers for data access. Now to enable communication between the user
interface and ContentResolver, we use another object, CursorLoader to run query
asynchronously. This CursorLoader will be called using Activity/Fragment of the application.
Then, the content provider receives the query from the client and executes and returns the
result.
onCreate() – This method in Android initializes the provider as soon as the receiver is
created.
query() – It receives a request in the form of a query from the user and responds with a
cursor in Android.
insert() – This method is used to insert the data into our content provider.
update() – This method is used to update existing data in a row and return the updated
row data.
delete() – This method deletes existing data from the content provider.
getType() – It returns the Multipurpose Internet Mail Extension type of data to the given
Content URI.
Intent
Android uses Intent for communicating between the components of an Application and also
from one application to another application.
Intent are the objects which is used in android for passing the information among Activities
in an Application and from one app to another also. Intent are used for communicating
between the Application components and it also provides the connectivity between two apps.
For example: Intent facilitate you to redirect your activity to another activity on occurrence of
any event. By calling, startActivity() you can perform this task.
Intentintent=newIntent(getApplicationContext(),SecondActivity.class);
startActivity(intent);
In the above example, foreground activity is getting redirected to another activity i.e.
SecondActivity.java. getApplicationContext() returns the context for your foreground
activity.
Types of Intents:
Intent are of two types: Explicit Intent and Implicit Intent
Explicit Intent:
Explicit Intent work internally within an application to perform navigation and data transfer.
The below given code snippet will help you understand the concept of Explicit Intents
Intentintent=newIntent(getApplicationContext(),SecondActivity.class);
startActivity(intent);
Here SecondActivity is the JAVA class name where the activity will now be navigated.
Example with code in the end of this post will make it more clear.
Implicit Intent:
In Implicit Intents we do need to specify the name of the component. We just specify
the Action which has to be performed and further this action is handled by the
component of another application.
The basic example of implicit Intent is to open any web page
Let’s take an example to understand Implicit Intents more clearly. We have to open a website
using intent in your application. See the code snippet given below
IntentintentObj=newIntent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.abhiandroid.com"));
startActivity(intentObj);
Unlike Explicit Intent you do not use any class name to pass through Intent(). In this example
we have just specified an action. Now when we will run this code then Android will
automatically start your web browser and it will open AbhiAndroid home page.
Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system itself. These messages are sometime called events or intents. For example,
applications can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this is broadcast receiver
who will intercept this communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
Creating the Broadcast Receiver.
Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents then you
will have to create and broadcast those intents.
Creating the Broadcast Receiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding
the onReceive() method where each message is received as a Intent object parameter.
publicclassMyReceiverextendsBroadcastReceiver{
@Override
publicvoidonReceive(Context context,Intent intent){
Toast.makeText(context,"Intent Detected.",Toast.LENGTH_LONG).show();
}
}
Registering Broadcast Receiver
An application listens for specific broadcast intents by registering a broadcast receiver
in AndroidManifest.xml file. Consider we are going to register MyReceiver for system
generated event ACTION_BOOT_COMPLETED which is fired by the system once the
Android system has completed the boot process.
Broadcast-Receiver
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<receiverandroid:name="MyReceiver">
<intent-filter>
<actionandroid:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
Now whenever your Android device gets booted, it will be intercepted by
BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be executed.
There are several system generated events defined as final static fields in the Intent class. The
following table lists a few important system events.
android.intent.action.BATTERY_CHANGED
1
Sticky broadcast containing the charging state, level, and other information
about the battery.
2 android.intent.action.BATTERY_LOW
Indicates low battery condition on the device.
3 android.intent.action.BATTERY_OKAY
Indicates the battery is now okay after being low.
4 android.intent.action.BOOT_COMPLETED
This is broadcast once, after the system has finished booting.
5 android.intent.action.BUG_REPORT
Show activity for reporting a bug.
6 android.intent.action.CALL
Perform a call to someone specified by the data.
android.intent.action.CALL_BUTTON
7
The user pressed the "call" button to go to the dialer or other appropriate UI for
placing a call.
8 android.intent.action.DATE_CHANGED
The date has changed.
9 android.intent.action.REBOOT
Have the device reboot.
Android Widgets
There are given a lot of android widgets with simplified examples such as Button, EditText,
AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.
Android widgets are easy to learn. The widely used android widgets with examples are given
below:
Android Button
Android Toast
Custom Toast
We are able to customize the toast, such as we can display image on the toast
ToggleButton
CheckBox
Let's see the application of simple food ordering.
AlertDialog
AlertDialog displays a alert dialog containing the message with OK and Cancel buttons.
Spinner
Spinner displays the multiple options, but only one can be selected at a time.
AutoCompleteTextView
RatingBar
DatePicker
Datepicker displays the datepicker dialog that can be used to pick the date.
TimePicker
TimePicker displays the timepicker dialog that can be used to pick the time.
ProgressBar
As we know that every android project that we make, need to have an Android Manifest file
within. This file is present in the root of the project source set. The reason why it is a must to
have it is that it describes all the important information of the application to the Android build
tools.
The manifest file in Android is generally created automatically as soon as the app is built in
Android Studio.
Structure of a Manifest file in Android is:
<manifest>
<application>
<activity android:name="com.example.applicationname.MainActivity">
</activity>
</application>
</manifest>
The information that is stored in the Manifest file is as follows:
The name of the application’s package, it is generally the code’s namespace. This
information is used to determine the location of the code while building the project.
Another component is the one, that includes all the activities, services, receivers, and
content providers.
The permissions that are required by the application to access the protected parts of the
system and other apps.
The features required by the app, that affect which devices can install the app from
Google Play. These features include both hardware and software features.
It also specifies the application metadata, which includes the icon, version number,
themes, etc.
The android manifest.xml file generally looks like the following:
1. <manifest>
It is the root element of this element. It consists of a package attribute package that tells the
activity’s package name.
2. <application>
It is the subelement of the manifest file that includes the declaration of the namespace. It
contains certain attributes. These attributes declare the application components, and these
attributes include:
icon
allowBackup
label
theme
3. <activity>
Activity is a subelement of application. It has the declaration of the activity that must be there
in the manifest file. It also has certain attributes like name, label, theme, etc.
4. <intent-filter>
It is an element in the activity, it describes the type of intent in which the Android
components can respond.
5. <action>
This element provides an action for the intent filter. Each intent filter must have at least one
action element in it.
6. <category>
This element adds the category name in an intent-filter.
7. <service>
This element contains the operations that are provided by libraries or APIs.
Manifest File Application Property Elements
1. <uses-permission>: This element specifies the Android Manifest permissions that are
requested for the purpose of security.
2. <permission>: This element sets permission to provide access to control for some
components of the app.
3. <permission-groups>: This element sets permission to provide access to control for a set
of components of the app.
4. <permission-tree>: This element refers to a specific component that is the owner of the
set of components.
5. <instrumentation>: This element tells the interaction between the app and the system.
6. <uses-sdk>: This one specifies the compatibility of the app.
7. <uses-configuration>: This element specifies the permissions that are requested for the
purpose of security.
8. <uses-feature>: This element specifies one hardware or software feature that is required
by the Application.
9. <supports-screen, compatible-screen>: These elements tell the screen size and
configuration.
How to set Manifest File Permissions in Android?
Now in this part of the tutorial, we’ll see how to set permission in a Manifest file.
An android application must get some permissions to get access to other apps or the Internet.
While we build our app, the manifest file gets automatically generated as manifest.xml. This
manifest file contains permissions that are configured by us. A few permissions are applied
by default if there is no permission provided by us.
<manifest >
<uses-permission .../>
...
<manifest >
The permission mentioned in the manifest file can be either granted or rejected by the users.
Once the user grants permission to the app, the app can use the protected features. If the user
denies permission the app doesn’t get permission to access the protected features.
INTERNET
ACCESS_NETWORK_STATE
READ_PHONE_STATE
There are many permissions that are set to FALSE by default but can be set to TRUE as per
requirements. A few of these permissions are as follows:
INTERFACE TOOLS
Creating user interface - Views - creating views - Layouts - Drawable resources - resolution and
density independence - Menus - Intents - Adapters - Using Internet resources - Dialogs.
In android, Layout is used to define the user interface for an app or activity and it will hold the UI
elements that will appear to the user.
The user interface in an android app is made with a collection of View and ViewGroup objects.
Generally, the android apps will contain one or more activities and each activity is a one screen of
app. The activities will contain a multiple UI components and those UI components are the instances
of View and ViewGroup subclasses.
The user interface in an android app is made with a collection of View and ViewGroup objects.
Generally, the android apps will contain one or more activities and each activity is a one screen of the
app. The activities will contain multiple UI components and those UI components are the instances
of View and ViewGroup subclasses.
Android View
The View is a base class for all UI components in android. For example, the EditText class is
used to accept the input from users in android apps, which is a subclass of View.
Following are the some of common View subclasses that will be used in android applications.
TextView
EditText
Button
CheckBox
RadioButton
ImageButton
Progress Bar
Spinner
There are different types of buttons in android such as RadioButton, ToggleButton, CompoundButton
etc.
We can perform action on button using different types such as calling listener on button or adding
onClick property of button in activity's xml file.
1. button.setOnClickListener(new View.OnClickListener() {
2. @Override
3. public void onClick(View view) {
4. //code
5. }
6. });
1. <Button
2. android:onClick="methodName"
3. />
File: activity_main.xml
Activity class
Now write the code to display the sum of two numbers.
File: MainActivity.java
1. package example.javatpoint.com.sumoftwonumber;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.EditText;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. private EditText edittext1, edittext2;
12. private Button buttonSum;
13.
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. addListenerOnButton();
20. }
21.
22. public void addListenerOnButton() {
23. edittext1 = (EditText) findViewById(R.id.editText1);
24. edittext2 = (EditText) findViewById(R.id.editText2);
25. buttonSum = (Button) findViewById(R.id.button);
26.
27. buttonSum.setOnClickListener(new View.OnClickListener() {
28. @Override
29. public void onClick(View view) {
30. String value1=edittext1.getText().toString();
31. String value2=edittext2.getText().toString();
32. int a=Integer.parseInt(value1);
33. int b=Integer.parseInt(value2);
34. int sum=a+b;
35. Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.LENGTH_LONG).sh
ow();
36. }
37. });
38. }
39. }
Ouput:
Android Toast Example
Andorid Toast can be used to display information for the short period of time. A toast contains
message to be displayed quickly and disappears after sometime.
You can also create custom toast as well for example toast displaying image. You can visit next page
to see the code for custom toast.
Toast class
Toast class is used to show notification for a particular interval of time. After sometime it disappears.
It doesn't block the user interaction.
There are only 2 constants of Toast class which are given below.
Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.
public static final int LENGTH_SHORT displays view for the short duration of time.
1. Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT)
.show();
Another code:
Output:
Android ToggleButton Example
Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.
It is beneficial if user have to change the setting between two states. It can be used to On/Off Sound,
Wifi, Bluetooth etc.
Since Android 4.0, there is another type of toggle button called switch that provides slider control.
Android ToggleButton and Switch both are the subclasses of CompoundButton class.
Method Description
CharSequence getTextOff() Returns the text when button is not in the checked state.
CharSequence getTextOn() Returns the text for when button is in the checked state.
activity_main.xml
Drag two toggle button and one button for the layout. Now the activity_main.xml file will look like
this:
File: activity_main.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.togglebutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.Toast;
8. import android.widget.ToggleButton;
9.
10. public class MainActivity extends AppCompatActivity {
11. private ToggleButton toggleButton1, toggleButton2;
12. private Button buttonSubmit;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. addListenerOnButtonClick();
19. }
20.
21. public void addListenerOnButtonClick(){
22. //Getting the ToggleButton and Button instance from the layout xml file
23. toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
24. toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
25. buttonSubmit=(Button)findViewById(R.id.button);
26.
27. //Performing action on button click
28. buttonSubmit.setOnClickListener(new View.OnClickListener(){
29.
30. @Override
31. public void onClick(View view) {
32. StringBuilder result = new StringBuilder();
33. result.append("ToggleButton1 : ").append(toggleButton1.getText());
34. result.append("\nToggleButton2 : ").append(toggleButton2.getText());
35. //Displaying the message in toast
36. Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG).show()
;
37. }
38.
39. });
40.
41. }
42. }
Output:
There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
Some of them are as follows:
Method Description
Drag the three checkboxes and one button for the layout. Now the activity_main.xml file will look
like this:
File: activity_main.xml
Android ViewGroup
The ViewGroup is a subclass of View and it will act as a base class for layouts and layouts parameters.
The ViewGroup will provide an invisible containers to hold other Views or ViewGroups and to define the layout
properties.
For example, Linear Layout is the ViewGroup that contains a UI controls like button, textview, etc. and other layouts
also.
Linear Layout
Relative Layout
Table Layout
Frame Layout
Web View
List View
Grid View
Both View and ViewGroup subclasses together will play a key role to create a layouts in android applications.
Android LinearLayout with Examples
In android, LinearLayout is a ViewGroup subclass which is used to render all child View instances one by one
either in Horizontal direction or Vertical direction based on the orientation property.
In android, we can specify the linear layout orientation using android:orientation attribute.
In LinearLayout, the child View instances arranged one by one, so the horizontal list will have only one row of
multiple columns and vertical list will have one column of multiple rows.
Create a new android application using android studio and give names as LinearLayout. In case if you are not aware
of creating an app in android studio check this article Android Hello World App.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<EditText
android:id="@+id/txtTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"/>
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"/>
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Message"/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send"/>
</LinearLayout>
Once we are done with creation of layout, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.linearlayout path and write the code like as shown below.
MainActivity.java
package com.tutlane.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework
to get the required layout for an activity.
Following are the some of most useful layout properties available to views in RelativeLayout.
Attribute Description
layout_alignParentTop If it specified “true”, the top edge of view will match the top edge of the parent.
layout_alignParentBottom If it specified “true”, the bottom edge of view will match the bottom edge of parent.
layout_alignParentLeft If it specified “true”, the left edge of view will match the left edge of parent.
layout_alignParentRight If it specified “true”, the right edge of view will match the right edge of the parent.
layout_centerInParent If it specified “true”, the view will be aligned to the centre of parent.
layout_centerHorizontal If it specified “true”, the view will be horizontally centre aligned within its parent.
layout_centerVertical If it specified “true”, the view will be vertically centre aligned within its parent.
layout_above It accepts another sibling view id and places the view above the specified view id.
layout_below It accepts another sibling view id and places the view below the specified view id.
layout_toLeftOf It accepts another sibling view id and places the view left of the specified view id.
layout_toRightOf It accepts another sibling view id and places the view right of the specified view id.
layout_toStartOf It accepts another sibling view id and places the view to start of the specified view id.
Attribute Description
layout_toEndOf It accepts another sibling view id and places the view to the end of the specified view id.
Create a new android application using android studio and give names as RelativeLayout. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Button2" />
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Button3" />
<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Button4" />
<Button
android:id="@+id/btn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btn2"
android:layout_centerHorizontal="true"
android:text="Button5" />
<Button
android:id="@+id/btn6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btn4"
android:layout_centerHorizontal="true"
android:text="Button6" />
<Button
android:id="@+id/btn7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/btn1"
android:layout_toRightOf="@+id/btn1"
android:layout_alignParentRight="true"
android:text="Button7" />
</RelativeLayout>
Once we are done with creation of layout, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.relativelayout path and write the code like as shown
below.
MainActivity.java
package com.tutlane.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
Generally, during the launch of our activity, onCreate() callback method will be called by the android
framework to get the required layout for an activity.
This is how we can use RelativeLayout in android applications based on our requirements.
The TableLayout in android will work same as the HTML table and the table will have as many columns
as the row with the most cells. The TableLayout can be explained as <table> and TableRow is
like <tr> element.
Create a new android application using android studio and give names as TableLayout. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="100dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TableRow android:background="#0079D6" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="UserId" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Location" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Suresh Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hyderabad" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rohini Alavala" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
<TableRow android:background="#DAE8FC" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Trishika Dasari" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Guntur" />
</TableRow>
</TableLayout>
Once we are done with creation of layout, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.tablelayout path and write the code like as shown below.
MainActivity.java
package com.tutlane.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
Generally, during the launch of our activity, onCreate() callback method will be called by android
framework to get the required layout for an activity.
In simple manner, we can say FrameLayout is designed to block out an area on the screen to display a single item.
In FrameLayout, the child views are added in a stack and the most recently added child will show on the top. We can
add multiple children views to FrameLayout and control their position by using gravity attributes in FrameLayout.
Create a new android application using android studio and give names as FrameLayout. In case if you are not aware
of creating an app in android studio check this article Android Hello World App.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imgvw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/flimg" />
<TextView
android:id="@+id/txtvw1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="#4C374A"
android:padding="10dp"
android:text="Grand Palace, Bangkok"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TextView
android:id="@+id/txtvw2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:text="21/Aug/2017"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</FrameLayout>
If you observe above code we used ImageView to show the image (flimg) from drawable folder in framelayout. So
add your image to drawable folder and replace @drawable/flimg path with your image path.
Once we are done with the creation of layout, we need to load the XML layout resource from
our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.framelayout path and write the code like as shown below.
MainActivity.java
package com.tutlane.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework
to get the required layout for an activity.
Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can
be used to interrupt and ask the user about his/her choice to continue or discontinue.
Android AlertDialog is composed of three regions: title, content area and action buttons.
Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can
be used to interrupt and ask the user about his/her choice to continue or discontinue.
Android AlertDialog is composed of three regions: title, content area and action buttons.
Method Description
public AlertDialog.Builder setIcon(int) This method is used to set the icon over
AlertDialog.
activity_main.xml
You can have multiple components, here we are having only a textview.
File: activity_main.xml
strings.xml
Optionally, you can store the dialog message and title in the strings.xml file.
File: strings.xml
1. <resources>
2. <string name="app_name">AlertDialog</string>
3. <string name="dialog_message">Welcome to Alert Dialog</string>
4. <string name="dialog_title">Javatpoint Alert Dialog</string>
5. </resources>
Activity class
File: MainActivity.java
1. package example.javatpoint.com.alertdialog;
2.
3. import android.content.DialogInterface;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8. import android.app.AlertDialog;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button closeButton;
13. AlertDialog.Builder builder;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. closeButton = (Button) findViewById(R.id.button);
20. builder = new AlertDialog.Builder(this);
21. closeButton.setOnClickListener(new View.OnClickListener() {
22. @Override
23. public void onClick(View v) {
24.
25. //Uncomment the below code to Set the message and title from the strings.xml file
35. Toast.LENGTH_SHORT).show();
36. }
37. })
38. .setNegativeButton("No", new DialogInterface.OnClickListener() {
39. public void onClick(DialogInterface dialog, int id) {
40. // Action for 'NO' Button
41. dialog.cancel();
42. Toast.makeText(getApplicationContext(),"you choose no action for alertbox",
43. Toast.LENGTH_SHORT).show();
44. }
45. });
46. //Creating dialog box
47. AlertDialog alert = builder.create();
48. //Setting the title manually
49. alert.setTitle("AlertDialogExample");
50. alert.show();
51. }
52. });
53. }
54. }
Output:
Adapter
Adapter is a bridge between UI component and data source that helps us to fill data in UI
component. It holds the data and send the data to an Adapter view then view can takes the data
from the adapter view and shows the data on different views like
as ListView, GridView, Spinner etc. For more customization in Views we uses the base adapter or
custom adapters.
To fill data in a list or a grid we need to implement Adapter. Adapters acts like a bridge between
UI component and data source. Here data source is the source from where we get the data and
UI components are list or grid items in which we want to display that data.
Adapters In Android:
There are the some commonly used Adapter in Android used to fill the data in the UI
components.
This handler will be triggered whenever an Activity completes its Active life cycle, but only when it’s not
being explicitly fi nished. As a result, it’s used to ensure a consistent Activity state between active life
cycles of a single user session.
The saved Bundle is passed in to the onRestoreInstanceState and onCreate methods if the application is
forced to restart during a session. The following snippet shows how to extract values from the Bundle and
use them to update the Activity instance state:
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView myTextView = (TextView)findViewById(R.id.myTextView);
String text = “”;
if (icicle != null && icicle.containsKey(TEXTVIEW_STATE_KEY))
text = icicle.getString(TEXTVIEW_STATE_KEY);
myTextView.setText(text);
}
It’s important to remember that onSaveInstanceState is called only when an Activity becomes inactive,
but not when it is being closed by a call to fi nish or by the user pressing the Back button.
Loading File
Android provides many kinds of storage for applications to store their data. These storage places
are
shared preferences
internal and external storage
SQLite storage
storage via network connection(on Cloud)
Android Internal storage is the storage of the private data on the device memory. By default,
saving and loading files to the internal storage are private to the application and other
applications will not have access to these files. When the user uninstalls the applications the
internal stored files associated with the application are also removed. However, note that some
users root their Android phones, gaining superuser access. These users will be able to read and
write whatever files they wish.
Android offers openFileInput and openFileOutput from the Java I/O classes to modify reading
and writing streams from and to local files.
openFileOutput(): This method is used to create and save a file. Its syntax is given below:
The method openFileOutput() returns an instance of FileOutputStream. After that we can call
write method to write data on the file. Its syntax is given below:
fOut.write(str.getBytes());
fOut.close();
openFileInput(): This method is used to open a file and read it. It returns an instance of
FileInputStream. Its syntax is given below:
After that, we call read method to read one character at a time from the file and then print it. Its
syntax is given below:
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
fin.close();
In the above code, string temp contains all the data of the file.
Note that these methods do not accept file paths (e.g. path/to/file.txt), they just take simple file
names.
Android Internal Storage Project Structure
The xml layout contains an EditText to write data to the file and a Write Button and Read
Button. Note that the onClick methods are defined in the xml file only as shown
below: activity_main.xml
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:padding="5dp"
android:text="Android Read and Write Text from/to a File"
android:textStyle="bold"
android:textSize="28sp" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="22dp"
android:minLines="5"
android:layout_margin="5dp">
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Write Text into File"
android:onClick="WriteBtn"
android:layout_alignTop="@+id/button2"
android:layout_alignRight="@+id/editText1"
android:layout_alignEnd="@+id/editText1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read Text From file"
android:onClick="ReadBtn"
android:layout_centerVertical="true"
android:layout_alignLeft="@+id/editText1"
android:layout_alignStart="@+id/editText1" />
</RelativeLayout>
The MainActivity contains the implementation of the reading and writing to files as it was
explained above.
package com.journaldev.internalstorage;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here, a toast is displayed when data is successfully written into the internal storage and the data
is displayed in the EditText itself on reading the data from the file. The image shown below is
the output of the project. The image depicts text being written to the internal storage and on
clicking Read it displays back the text in the same EditText.
To actually view the file open the Android Device Monitor from Tools->Android->Android
Device Monitor. The file is present in the folder data->data->{package name}->files as shown in
the
images below: The file “mytextfile.txt” is found in the package name of the project
i.e. com.journaldev.internalstorage as shown below:
Android External Storage Example
Like internal storage, we are able to save or read data from the device external memory such as sdcard.
The FileInputStream and FileOutputStream classes are used to read and write data into the file.
activity_main.xml
Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the activity_main.xml file will like
this:
File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.externalstorage.MainActivity">
8.
9. <EditText
10. android:id="@+id/editText1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_alignParentRight="true"
14. android:layout_alignParentTop="true"
15. android:layout_marginRight="20dp"
16. android:layout_marginTop="24dp"
17. android:ems="10" >
18.
19. <requestFocus />
20. </EditText>
21.
22. <EditText
23. android:id="@+id/editText2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_alignRight="@+id/editText1"
27. android:layout_below="@+id/editText1"
28. android:layout_marginTop="24dp"
29. android:ems="10" />
30.
31. <TextView
32. android:id="@+id/textView1"
33. android:layout_width="wrap_content"
34. android:layout_height="wrap_content"
35. android:layout_alignBaseline="@+id/editText1"
36. android:layout_alignBottom="@+id/editText1"
37. android:layout_alignParentLeft="true"
38. android:text="File Name:" />
39.
40. <TextView
41. android:id="@+id/textView2"
42. android:layout_width="wrap_content"
43. android:layout_height="wrap_content"
44. android:layout_alignBaseline="@+id/editText2"
45. android:layout_alignBottom="@+id/editText2"
46. android:layout_alignParentLeft="true"
47. android:text="Data:" />
48.
49. <Button
50. android:id="@+id/button1"
51. android:layout_width="wrap_content"
52. android:layout_height="wrap_content"
53. android:layout_alignLeft="@+id/editText2"
54. android:layout_below="@+id/editText2"
55. android:layout_marginLeft="70dp"
56. android:layout_marginTop="16dp"
57. android:text="save" />
58.
59. <Button
60. android:id="@+id/button2"
61. android:layout_width="wrap_content"
62. android:layout_height="wrap_content"
63. android:layout_alignBaseline="@+id/button1"
64. android:layout_alignBottom="@+id/button1"
65. android:layout_toRightOf="@+id/button1"
66. android:text="read" />
67. </RelativeLayout>
1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File: Activity_Manifest.xml
Activity class
Let's write the code to write and read data from the android external storage.
File: MainActivity.java
1. package example.javatpoint.com.externalstorage;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.EditText;
8. import android.widget.Toast;
9.
10. import java.io.BufferedReader;
11. import java.io.File;
12. import java.io.FileInputStream;
13. import java.io.FileNotFoundException;
14. import java.io.FileOutputStream;
15. import java.io.IOException;
16. import java.io.InputStreamReader;
17. import java.io.OutputStreamWriter;
18.
19. public class MainActivity extends AppCompatActivity {
20. EditText editTextFileName,editTextData;
21. Button saveButton,readButton;
22. @Override
23. protected void onCreate(Bundle savedInstanceState) {
24. super.onCreate(savedInstanceState);
25. setContentView(R.layout.activity_main);
26.
27. editTextFileName=findViewById(R.id.editText1);
28. editTextData=findViewById(R.id.editText2);
29. saveButton=findViewById(R.id.button1);
30. readButton=findViewById(R.id.button2);
31.
32. //Performing action on save button
33. saveButton.setOnClickListener(new View.OnClickListener(){
34.
35. @Override
36. public void onClick(View arg0) {
37. String filename=editTextFileName.getText().toString();
38. String data=editTextData.getText().toString();
39.
40. FileOutputStream fos;
41. try {
42. File myFile = new File("/sdcard/"+filename);
43. myFile.createNewFile();
44. FileOutputStream fOut = new FileOutputStream(myFile);
45. OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
46. myOutWriter.append(data);
47. myOutWriter.close();
48. fOut.close();
49. Toast.makeText(getApplicationContext(),filename + "saved",Toast.LENGTH_LONG).show(
);
50. } catch (FileNotFoundException e) {e.printStackTrace();}
51. catch (IOException e) {e.printStackTrace();}
52. }
53. });
54.
55. //Performing action on Read Button
56. readButton.setOnClickListener(new View.OnClickListener(){
57. @Override
58. public void onClick(View arg0) {
59. String filename=editTextFileName.getText().toString();
60. StringBuffer stringBuffer = new StringBuffer();
61. String aDataRow = "";
62. String aBuffer = "";
63. try {
64. File myFile = new File("/sdcard/"+filename);
65. FileInputStream fIn = new FileInputStream(myFile);
66. BufferedReader myReader = new BufferedReader(
67. new InputStreamReader(fIn));
68. while ((aDataRow = myReader.readLine()) != null) {
69. aBuffer += aDataRow + "\n";
70. }
71. myReader.close();
72. } catch (IOException e) {
73. e.printStackTrace();
74. }
75. Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
76. }
77. });
78. }
79. }
Android allows every user to access their device's file system using a file manager. They can
access Android files and transfer them between a computer and a smartphone or tablet. This is
performed by simply plug in a USB cable in an Android device and fire up your desktop file
manager. Android's file manager app reacts as an important part of the software on a device. It
provides facility to browse files, manage storage space, downloads, move files around, and a lot
of other activities. However, several Android device manufacturers provide a pre-install Android
file manager app on their devices. The pre-install file manager contains fewer features as
compared to other third-party file managers.
1. Files Go (free)
2. Mixplorer Silver ($4.79)
3. Astro Cloud & File Manager (free)
4. Solid Explorer ($1.99 after free trial)
5. DiskUsage (free)
6. File Commander (free, in-app purchase)
Files Go
Files Go file manager is a product of Google, which behaves less like a file manager app and
more as a device assistant. This file manager helps you to manage your device's storage space by
deleting rarely used applications, files, documents, large size media, and folders. It also
facilitates a cache clearing functionality and allows you to view files based on their categories.
The Files Go supports local encrypted file sharing and backup features that provide a facility to
send files to the cloud.
MiXplorer Silver
MiXplorer Silver has a strong file manager in this era now, but it is now recently placed in the
Google Play store in a premium version. This version bunches together MiXplorer with several
premium add-ons like Mix archive, tagger, and metadata. It supports multiple archive formats,
including RAR and ZIP. The MiXplorer Silver contains a built-in media player and image
viewer. It supports for both networked and cloud-based storage device.
Astro Cloud & File Manager
ASTRO file manager is another important and popular choice for Android file management. This
file manager contains both cloud and local storage management components in a single package.
It offers you to manage your internal and SD card storage space. Using Astro Cloud file
manager, you can move your files and media to and from cloud services like One Drive,
Dropbox, and Google Drive. Its left side drawer contains convenient shortcuts such as cloud
service and network storage, bookmarked locations, and shortcuts to media files. Other than file
management functionality, this app also contains an app manager, quick viewer to SD card usage
space, and a task killer.
Solid Explorer
This is an attractive file manager app which provides two-pane user interface over the Android
phones and tablets. It also supports for archive files like TAR, RAR, and ZIP, and indexed search
function. Other than an impressive feature, Solid Explorer supports a wide range of plugins that
add new features such as FTP server plugin, USB OTG support, and lots more. It has two
separate explorer panes, which are combined with drag-and-drop support, which offers copying
and moving files from one location to another.
DiskUsage
DiskUsage is not a really complete file manager app; however, it is still an attractive tool that
helps you to manage your file system. This helps you to instantly find the files and folders that
occupy more storage space in the device. It performs as a separate tool to view and delete
folders.
File Commander
File Commander is an excellent file manager that provides extra features and utilities in-app
purchases. Instead of opening a file and directory view, the app's home screen gives users a
series of classified "libraries" such as document, audio, and video. This file manager also
supports remote access, file sharing, and cloud storage. It contains additions tools in-app
purchases.
sending emails through application
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.
You will use ACTION_SEND action to launch an email client installed on your Android device.
Following is simple syntax to create an intent with ACTION_SEND action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);
To send an email you need to specify mailto: as URI using setData() method and data type will
be to text/plain using setType() method as follows −
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
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
Email Example
Example
Following example shows you in practical how to use Intent object to launch Email client to send
an Email to the given recipients.
To Email experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you might get struggle with emulator which may not work properly.
Second you will need to have an Email client like GMail(By default every android version
having Gmail client App) or K9mail installed on your device.
Step Description
1 You will use Android studio to create an Android application and name it
as Tutorialspoint under a package com.example.tutorialspoint.
2 Modify src/MainActivity.java file and add required code to take care of sending
email.
6 Run the application to launch Android emulator and verify the result of the
changes done in the application.
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();
}
}
}
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo
<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" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:id="@+id/sendEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/compose_email"/>
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Tutorialspoint</string>
<string name="compose_email">Compose Email</string>
</resources>
Following is the default content of 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>
Let's try to run your tutorialspoint application. 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.
Android databases –SQLite
Database - Package
The main package is android.database.sqlite that contains the classes to manage your own
databases
Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. It returns an instance of SQLite database which you
have to receive in your own object.Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
Apart from this , there are other functions available in the database package , that does this job.
They are listed below
1
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
flags, DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode.
The common flags mode could be OPEN_READWRITE OPEN_READONLY
2
openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
flags)
It is similar to the above method as it also opens the existing database but it
does not define any handler to handle the errors of databases
3
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory
factory)
It not only opens but create the database if it not exists. This method is
equivalent to openDatabase method.
4
openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
This method is similar to above method but it takes the File object as a path
rather then a string. It is equivalent to file.getPath()
Database - Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the
same job but take some additional parameter is given below
1
execSQL(String sql, Object[] bindArgs)
This method not only insert data , but also used to update or modify already
existing data in database using bind arguments
Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a
method of this class called rawQuery and it will return a resultset with the cursor pointing to the
table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the
data. That includes
1
getColumnCount()
This method return the total number of columns of the table.
2
getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of
the column
3
getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the
column
4
getColumnNames()
This method returns the array of all the column names of the table.
5
getCount()
This method returns the total number of rows in the cursor
6
getPosition()
This method returns the current position of the cursor in the table
7
isClosed()
This method returns true if the cursor is closed and return false otherwise
For managing all the operations related to the database , an helper class has been given and is
called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its
syntax is given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}
<TextView
android:text="@string/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="12dp"
android:id="@+id/textView"
android:textSize="18sp"
android:textStyle="bold|italic"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editName"
android:textStyle="bold|italic"
android:layout_below="@+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Enter Name"
android:gravity="center_vertical|center" />
<TextView
android:text="@string/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:id="@+id/textView2"
android:textStyle="bold|italic"
android:textSize="18sp"
android:layout_below="@+id/editName"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:gravity="center"
android:hint="Enter Password" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:layout_marginTop="11dp"
android:id="@+id/editPass"
android:hint="Enter Password"
android:gravity="center_vertical|center"
android:textSize="18sp"
android:layout_below="@+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAllCaps="false"
android:textStyle="normal|bold" />
<Button
android:text="@string/add_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:textStyle="bold|italic"
android:textSize="18sp"
android:onClick="addUser"
android:layout_marginLeft="28dp"
android:layout_marginStart="28dp"
android:layout_below="@+id/editPass"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="23dp" />
</RelativeLayout>
Now open app -> java -> package -> MainActivity.java and add the below code.
package com.example.sqliteoperations;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
package com.example.sqliteoperations;
import android.content.Context;
import android.widget.Toast;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class myDbAdapter {
myDbHelper myhelper;
public myDbAdapter(Context context)
{
myhelper = new myDbHelper(context);
}
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
Message.message(context,""+e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {
Message.message(context,""+e);
}
}
}
}
package com.example.sqliteoperations;
import android.content.Context;
import android.widget.Toast;
The Firebase Realtime Database is a cloud-hosted database in which data is stored as JSON. The
data is synchronized in real-time to every connected client. All of our clients share one Realtime
Database instances and automatically receive updates with the newest data, when we build cross-
platform applications with our iOS, and JavaScript SDKs.
The Firebase Realtime Database is a NoSQL database from which we can store and sync the data
between our users in real-time. It is a big JSON object which the developers can manage in real-
time. By using a single API, the Firebase database provides the application with the current value
of the data and updates to that data. Real-time syncing makes it easy for our users to access their
data from any device, be it web or mobile.
The Realtime database helps our users collaborate with one another. It ships with mobile and
web SDKs, which allow us to build our app without the need for servers. When our users go
offline, the Real-time Database SDKs use local cache on the device for serving and storing
changes. The local data is automatically synchronized, when the device comes online.
Features of Firebase
Firebase has several features that make this platform essential. These features include unlimited
reporting, cloud messaging, authentication and hosting, etc. Let's take a look at these features to
understand how these features make Firebase essential:
The analytics dashboard is one of the best features of Firebase, which is equipped with. It is free
and can report 500 event types, each with 25 attributes. The dashboard is top-notch for observing
user behavior and measuring various user characteristics. Ultimately it helps us to understand
how people use our app so that we can better optimize it in the future.
Key features
Unlimited Reporting
It allows for reporting of 500 distinct events.
Audience Segmentation
We can identify custom audiences in the Firebase console based on device data, custom events,
or user properties. After that, we can use these audiences that we specified with other Firebase
attributes when targeting new features or notifications.
Integration with Other Services
We can integrate Firebase with other services that can utilize our business apps such as Big
Query, Firebase Notifications, Firebase Remote Configuration, Firebase CrashReporting, and
Google Tag Manager.
Authentication
Firebase has little friction with acclaimed authentication.
Test Lab
Test in the lab instead on your users.
Hosting
Firebase delivers web content faster.
Remote Configuration
It allows us to customize our app on the go.
Dynamic Links
Dynamic Links are smart URLs which dynamically change behavior for providing the best
experience across different platforms. These links allow app users to take directly to the content
of their interest after installing the app - no matter whether they are completely new or lifetime
customers.
Crash Reporting
It keeps our app stable.
Real-time Database
It can store and sync app data in real-time.
Storage
We can easily store the file in the database.
App Indexing
With app indexing, we can work on aspects like re-engaging with our app, especially by surfing
the in-app content within Google search results. It will also help in ranking our application in
Google search results.
Invites
It is a perfect tool for referrals and sharing. Get the help of our users to develop our app easily
via email or SMS, allowing their existing users to share our app or in-app content. If we use this
feature in combination with promotions, then we can also work towards acquiring new customers
and retaining our existing customers.
Notifications
We can manage information campaigns very easily, including the ability to set and schedule
messages to engage users at the right time of day. These notifications are completely free. These
are unlimited for both iOS and Android. There is only one dashboard to worry about, and if we
integrate with Firebase Analytics, we can use various user segmentation features.
Step 1:
In the first step, we will create a new Android Studio project with an empty activity and Kotlin
language and give it name FirebaseRealtimeDatabaseExample.
Step 2:
In the next step, we will connect our Android Application with the Firebase either from Firebase
Assistant or manually using console. After that, we will add all the required libraries and plugin
to our app.gradle file. And we will also add mavenLocal() as our repository and all projects.
Step 3:
In the next step, we will go to the Firebase console and look at the Real-time database. In
Developers-> Database, there will be two options, i.e., cloud Firestore and Real-time database.
Step 4:
In the next step, we will create a database by clicking on the Create database. After clicking on
Create database, a popup box is open where we actually create a database with specific rules. We
will talk about these rules later in this section. But for now, we will select start in test mode
where anybody can access our data, and later we change these rules. And last we select on
Enable.
Step 5:
After clicking on Enable, the real-time database will be enabled with a database by default. Here,
we have Data, Rules, Backups, and, Usage for data storing, security rules, backups, and usage,
respectively.
Before understanding the next steps, we will talk about the Firebase Database Rules.
The Real-time database provides a declarative rules language. It defines how our data should be
structured, how it should be indexed, and when our data can be read from and written to. By
default, read and write access to our database is restricted, so only authenticated users can read or
write data.
To get started without setting up Authentication, we can configure our rules for public access.
These rules make our database open to anyone, even people not using our app, read and write
access to our database.
1. {
2. "rules": {
3. ".read": true,
4. ".write": true
5. }
6. }
If we want to allow authenticated users for accessing read and write to our database, then we will
use the following rules:
1. {
2. "rules": {
3. ".read": "auth!=null",
4. ".write": "auth!=null"
5. }
6. }
This will make sure that user only who have been authenticated using firebase can read and write
to our database.
Step 6:
In the next step, we will go to the console and go to database rules and modify these rules to
authenticated users.
After performing the required changes in the rules, we will publish them.
Now, our database is set with specific rules, and we can use it now. In the next section, we will
learn how we perform read and write operations in a Real-time database.
Example:
package com.example.firebase_database;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.tv1);
ref= FirebaseDatabase.getInstance().getReference().child("student").child("name");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String str;
str=dataSnapshot.getValue(String.class);
//Toast.makeText(getApplicationContext(),str,Toast.LENGTH_LONG).show();
txt.setText(str);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
MySQL-PHP
mysql
MySQL is an open-source relational database management system (RDBMS). It is the most
popular database system used with PHP. MySQL is developed, distributed, and supported by
Oracle Corporation.
The data in a MySQL database are stored in tables which consists of columns and rows.
MySQL is a database system that runs on a server.
MySQL is ideal for both small and large applications.
MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
MySQL compiles on a number of platforms.
The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.
Databases are useful for storing information categorically. A company may have a database with
the following tables:
Employees
Products
Customers
Orders
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
The connection will be closed automatically when the script ends. To close the connection
before, use the following:
MySQLi Object-Oriented:
$conn->close();
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";
$conn->close();
?>
After a database and a table have been created, we can start adding data in them.
The INSERT INTO statement is used to add new records to a MySQL table:
$conn->close();
?>
UNIT-IV
Activity_Main.XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="131dp"
android:layout_marginTop="158dp"
android:layout_marginEnd="192dp"
android:layout_marginBottom="69dp"
android:text="@string/play"
app:layout_constraintBottom_toTopOf="@+id/stop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="133dp"
android:layout_marginTop="69dp"
android:layout_marginEnd="190dp"
android:layout_marginBottom="408dp"
android:text="@string/pause"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/start" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.exno_2_amutha;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer=MediaPlayer.create(this,R.raw.sound);
Button playbutton=(Button) findViewById(R.id.start);
playbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new
MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
Toast.makeText(MainActivity.this,"The Song is
Over",Toast.LENGTH_SHORT).show();
}
});
}
});
Button pausebutton=(Button) findViewById(R.id.stop);
pausebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaPlayer.pause();
}
});
Video
Step 1: Create a new project ,open an empty activity named by videoplayer , then click
finish.
Step 2: Remove text view in the code view of activity-main.xml
Step 3: Drag and drop the relative layout.
Step 4: In designview ,drag and drop the button and give a text as play , and give android:onclick
=”videoplay”, and change the id.
Step 5:Click widgets in palette , drag and drop the videoview and change the id.
Step 6:In project right click yes ,select new. Select resource->click new resource folder and click
change the folder location. src/ main/res/raw
Step 7: Download any mp4, or webm file, copy that file.
Step 8: Right click raw folder and paste it then click refactor.
Step 9: Write the code in mainactivity.java
Step 10: Run the app
Acivity_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">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:onClick="videoplay"
android:layout_height="wrap_content"
android:text="play" />
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Main_acivity.java
package com.example.exno_3_video;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity {
Button clk;
VideoView videov;
MediaController mediaC;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clk=(Button)findViewById(R.id.button);
videov=(VideoView)findViewById(R.id.videoView);
mediaC=new MediaController(this);
}
public void videoplay(View view)
{
String videopath="android.resource://com.example.exno_3_video/"+R.raw.cloud;
Uri uri=Uri.parse(videopath);
videov.setVideoURI(uri);
videov.setMediaController(mediaC);
mediaC.setAnchorView(videov);
videov.start();
}
}
Output:
Camera
Camera is a hardware device that allows capturing pictures and videos in your applications.
Follow this tutorial to easily understand how to use a camera in your own Android App.
The Android framework provides the facility of working with Camera in two ways:
1.By using existing camera application(camera intent)
2.By using Camera Api
#1 Using Camera By Using Camera Application
We can capture pictures without using the instance of Camera class. Here you will use
an intent action type of MediaStore.ACTION_IMAGE_CAPTURE to launch an existing Camera
application on your phone. In Android MediaStore is a type of DataBase which stores pictures
and videos in android.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
<uses-permission android:name="android.permission.CAMERA"/>
Camera Example in Android Studio By Using Camera Intent and storing the camera
Image in Local DataBase
In this Camera in Android example, I will show you how to capture the image from device
camera using Intent and store that camera image in the local database and display a toast when
an image is stored successfully or when some error occurred while storing an image.
activity_main.xml
Drag one imageview and one button from the pallete, now the xml file will look like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentBottom="true"
12. android:layout_centerHorizontal="true"
13. android:text="Take a Photo" >
14. </Button>
15.
16. <ImageView
17. android:id="@+id/imageView1"
18. android:layout_width="fill_parent"
19. android:layout_height="fill_parent"
20. android:layout_above="@+id/button1"
21. android:layout_alignParentTop="true"
22. android:src="@drawable/ic_launcher" >
23. </ImageView>
24. </RelativeLayout>
Activity class
Let's write the code to capture image using camera and displaying it on the image view.
File: MainActivity.java
1. package com.example.simplecamera;
2.
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.graphics.Bitmap;
6. import android.os.Bundle;
7. import android.view.Menu;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.ImageView;
11.
12. public class MainActivity extends Activity {
13. private static final int CAMERA_REQUEST = 1888;
14. ImageView imageView;
15. public void onCreate(Bundle savedInstanceState) {
16.
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. imageView = (ImageView) this.findViewById(R.id.imageView1);
21. Button photoButton = (Button) this.findViewById(R.id.button1);
22.
23. photoButton.setOnClickListener(new View.OnClickListener() {
24.
25. @Override
26. public void onClick(View v) {
27. Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAP
TURE);
28. startActivityForResult(cameraIntent, CAMERA_REQUEST);
29. }
30. });
31. }
32.
33. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
34. if (requestCode == CAMERA_REQUEST) {
35. Bitmap photo = (Bitmap) data.getExtras().get("data");
36. imageView.setImageBitmap(photo);
37. }
38. }
39.
40. @Override
41. public boolean onCreateOptionsMenu(Menu menu) {
42. // Inflate the menu; this adds items to the action bar if it is present.
43. getMenuInflater().inflate(R.menu.activity_main, menu);
44. return true;
45. }
46.
47. }
Telephony and SMS
SMSManager class manages operations like sending a text message, data message, and
multimedia messages (MMS). For sending a text message method sendTextMessage() is used
likewise for multimedia message sendMultimediaMessage() and for data
message sendDataMessage() method is used. The details of each function are:
sendTextMessage(String destinationAddress,
String scAddress, String text, PendingIntent sentIntent,
sendTextMessage() PendingIntent deliveryIntent, long messageId)
sendDataMessage(String destinationAddress,
String scAddress, short destinationPort, byte[] data,
sendDataMessage() PendingIntent sentIntent, PendingIntent deliveryIntent)
sendMultimediaMessage(Context context,
Uri contentUri, String locationUrl,
sendMultimediaMessage() Bundle configOverrides, PendingIntent sentIntent
import androidx.appcompat.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;
You can use Android Intent to send SMS by calling built-in SMS functionality of the Android.
Following section explains different parts of our Intent object required to send an SMS.
You will use ACTION_VIEW action to launch an SMS client installed on your Android device.
Following is simple syntax to create an intent with ACTION_VIEW action.
To send an SMS you need to specify smsto: as URI using setData() method and data type will be
to vnd.android-dir/mms-sms using setType() method as follows −
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
Android has built-in support to add phone number and text message to send an SMS as follows −
Example
Following example shows you in practical how to use Intent object to launch SMS client to send
an SMS to the given recipients.
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.
Step Description
You will use Android studio IDE to create an Android application and name it as tutorialspoint
1
under a package com.example.tutorialspoint.
2 Modify src/MainActivity.java file and add required code to take care of sending SMS.
Modify layout XML file res/layout/activity_main.xml add any GUI component if required. I'm
3
adding a simple button to launch SMS Client.
4 No need to define default constants.Android studio takes care of default constants.
5 Modify AndroidManifest.xml as shown below
Run the application to launch Android emulator and verify the result of the changes done in the
6
application.
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;
smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address" , new String ("01234"));
smsIntent.putExtra("sms_body" , "Test ");
try {
startActivity(smsIntent);
finish();
Log.i("Finished sending SMS...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
"SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drag and Drop Example"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point "
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:textColor="#ff14be3c" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_marginTop="48dp"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Compose SMS"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_marginTop="54dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
</RelativeLayout>
<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>
Let's try to run your tutorialspoint application. 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 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 SMS button to launch Android built-in SMS clients which is shown below −
You can modify either of the given default fields and finally use send SMS button to send your
SMS to the mentioned recipient.
Bluetooth Networks
Bluetooth is a communication network protocol, which allows devices to connect wirelessly to
exchange the data with other Bluetooth devices.
By using android Bluetooth API’s in android applications, we can perform the following
functionalities.
To transfer the data between two Bluetooth devices first, they must establish a communication
channel using the pairing process. The devices which we are going to pair must be discoverable
and should accept the incoming connection requests. Generally, the devices will find
discoverable devices using a service discovery process. Once the device accepts the pairing
request, the two devices will exchange security keys to complete the bonding process and the
devices will cache these security keys for later use.
Once the pairing and bonding process completes, the devices are ready to exchange the required
information. When the session is complete, the device that initiated the pairing request will
release the channel that linked to the discoverable device. The two devices remain bonded, so
they can reconnect automatically during a future session as long as they're in the range of each
other.
Permission Description
LOCATION We need this permission because the Bluetooth scans can be used to gather the
information about the location of user.
In case, if we want to discover the available Bluetooth devices or manipulate Bluetooth settings
from our app, we need to define BLUETOOTH_ADMIN permission.
Following is the example of defining the Bluetooth permissions in android manifest file.
By using BluetoothAdapter object, we can interact with device’s Bluetooth adapter to perform
Bluetooth related operations. In case, if device does not contain any Bluetooth adapter, then it
will return null.
Following is the code snippet to initialize BluetoothAdapter class and to know whether the
Bluetooth is supported on the device or not.
In case if getDefaultAdapter() method returns NULL, then the device does not support
Bluetooth and we can disable all Bluetooth features.
Android Enable or Disable Bluetooth
If Bluetooth is supported but disabled, then the isEnabled() method will return false and we can
request the user to enable Bluetooth without leaving our application by
using startActivityForResult() method with ACTION_REQUEST_ENABLE intent action
parameter.
if(!bAdapter.isEnabled())
{
Intent eintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(eintent, intVal);
}
If you observe above code snippet, we used startActivityForResult() method
with ACTION_REQUEST_ENABLE intent action parameter to enable a Bluetooth.
To know more about to TURN ON / OFF Bluetooth in android applications, check this Android
Bluetooth Turn ON / OFF with Examples.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btnOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn
On" android:layout_marginLeft="100dp" android:layout_marginTop="200dp" />
<Button
android:id="@+id/btnOFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btnOn"
android:layout_toRightOf="@+id/btnOn"
android:text="Turn OFF" />
</RelativeLayout>
Now open your main activity
file MainActivity.java from \java\com.tutlane.bluetoothexample path and write the code like
as shown below
MainActivity.java
package com.tutlane.bluetoothexample;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),1);
Toast.makeText(getApplicationContext(),"Bluetooth Turned
ON",Toast.LENGTH_SHORT).show();
}
}
}
});
btntOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bAdapter.disable();
Toast.makeText(getApplicationContext(),"Bluetooth Turned OFF",
Toast.LENGTH_SHORT).show();
}
});
}
}
If you observe above code, we used startActivityForResult() method with BluetoothAdapter
action parameter ACTION_REQUEST_ENABLE intent to enable or disable a Bluetooth in our
application.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.bluetoothexample">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<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>
Motion Sensors
Environmental sensors
Position sensors
Motion Sensors
These sensors track movement; they include accelerometers, gyroscopes and gravity
sensors. They provide data on forces like acceleration and rotation that act on the sensor’s
three-dimensional axes.
Environmental Sensors
Barometers and thermometers are types of sensors that access environmental metrics.
These sensors monitor environmental variables like air pressure and temperature.
Position Sensors
Magnetometer and orientation sensors help determine the physical position of a device.
Each of these categories represents many specific sensors that are available on a device.
You will go through them next.
Android Sensor API
We can collect raw sensor data by using Android Sensor API. Android sensor
API provides many classes and interfaces. Some of the important classes and
interfaces are:
1. SensorManager Class: Sensor manager is used to accessing various
sensors present in the device.
2. Sensor Class: The sensor class is used to get information about the
sensor such as sensor name, sensor type, sensor resolution, sensor type,
etc.
3. SensorEvent class: This class is used to find information about the
sensor.
4. SensorEventListener interface: This is used to perform some action
when sensor accuracy changes.
Some of the sensors are hardware based and some are software based sensors.
Whatever the sensor is, android allows us to get the raw data from these sensors and
use it in our application. For this android provides us with some classes.
Android provides SensorManager and Sensor classes to use the sensors in our
application. In order to use sensors, first thing you need to do is to instantiate the object
of SensorManager class. It can be achieved as follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
The next thing you need to do is to instantiate the object of Sensor class by calling the
getDefaultSensor() method of the SensorManager class. Its syntax is given below −
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
Once that sensor is declared , you need to register its listener and override two methods
which are onAccuracyChanged and onSensorChanged. Its syntax is as follows −
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light Sensor"
android:textSize="20sp"
android:textColor="@color/black"
android:layout_centerInParent="true" />
</RelativeLayout>
Go to the MainActivity.kt file and refer to the following code. Below is the code
for the MainActivity.kt file. Comments are added inside the code to understand
the code in more detail.
package com.mrtechy.gfg_sensor
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatDelegate
// setupSensor Called
setUpSensor()
}
ADVANCED TECHNOLOGY
Paranoid Android - Using Wake Locks - AIDL to Support IPC for
Services -General API’s- Payment-gateway, Android jetpack-
Technology II-IOS-Introduction to Objective C-IOS features.
Paranoid Android
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotSleep");
wakeLock.acquire();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wakeLock.release();
}
}
https://www.protechtraining.com/blog/post/implementing-remote-interface-using-aidl-66
Step2: implement the Step3: Expose the
stub for remote service remote service to
(IAdditionservice.stub) the local client
Step1: implement
AIDL interface
(Iadditionservice)
Defining the AIDL
Java interfaces.
Also, all other AIDL datatypes that you defined are supported.
Code:
package com.marakana;
interface IAdditionService {
Once you create your AIDL file and put it in the right place, the Eclipse+AIDL tool
will generate a file with the same name, but .java extension.
What is important is that it contains a Stub class that we'll want to implement for
our remote service.
To implement our remote service, we'll return the IBinder from onBind() method in
our service class, AdditionService. The IBinder represents the implementation of the
remote service. To implement IBinder, we subclass IAddtionService.Stub class from
the auto-generated Java code, and provide implementation for our AIDL-defined
methods, in this case add().
/src/com.marakana/AdditionService.java
/** @Override
* This class exposes the remote public IBinder onBind(Intent intent) {
service to the client
*/ return new IAdditionService.Stub() {
public class AdditionService /**
extends Service { * Implementation of the add() method
private static final String TAG = */
"AdditionService"; public int add(int value1, int value2) throws
RemoteException {
@Override Log.d(TAG,
public void onCreate() { String.format("AdditionService.add(%d,
super.onCreate(); %d)",value1, value2));
Log.d(TAG, "onCreate()"); return value1 + value2;
} }};}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
}
}
Once we have the service implement the onBind() properly, we are ready to connect to
that service from our client. In this case, we have AIDLDemo activity connecting to
that service. To establish the connection, we need to implement ServiceConnection
class. Our activity in this example provides this implementation in
AdditionServiceConnection inner class by implementing onServiceConnected() and
onServiceDiconnected() methods. Those callbacks will get the stub implementation of
the remote service upon connection. We need to cast them from stubs to our AIDL
service implementation. To do that, we use the
IAdditionService.Stub.asInterface((IBinder) boundService) helper method.
From that point on, we have a local service object that we can use to make calls against
the remote service.
/src/com.marakana/AIDLDemo.java
/**
* This class represents the actual service connection. It casts the bound
* stub implementation of the service to the AIDL interface.
*/
class AdditionServiceConnection implements ServiceConnection {
initService();
// Setup the UI
Button buttonCalc = (Button) findViewById(R.id.buttonCalc);
buttonCalc.setOnClickListener(new OnClickListener() {
TextView result = (TextView) findViewById(R.id.result);
EditText value1 = (EditText) findViewById(R.id.value1);
EditText value2 = (EditText) findViewById(R.id.value2);
public void onClick(View v) {
int v1, v2, res = -1;
v1 = Integer.parseInt(value1.getText().toString());
v2 = Integer.parseInt(value2.getText().toString());
try {
res = service.add(v1, v2);
} catch (RemoteException e) {
Log.d(AIDLDemo.TAG, "onClick failed with: " + e);
e.printStackTrace();
}
result.setText(new Integer(res).toString());
}
});
}
/res/layout/main.xml
<EditText
android:id="@+id/value1"
android:hint="Value 1"></EditText>
<TextView android:id="@+id/TextView01“
android:text="+“></TextView>
<EditText
android:id="@+id/value2"
android:hint="Value 2"></EditText>
<Button
android:id="@+id/buttonCalc"
android:text="="></Button>
<TextView android:text="result“
android:id="@+id/result"></TextView>
</LinearLayout>
Topic 4 : Payment Gateway
RAZORPAY INTEGRATION
ANDROID STUDIO
MM.DD.20XX ADD A FOOTER 38
MM.DD.20XX ADD A FOOTER 39
MM.DD.20XX ADD A FOOTER 40
MM.DD.20XX ADD A FOOTER 41
MM.DD.20XX ADD A FOOTER 42
MM.DD.20XX ADD A FOOTER 43
MM.DD.20XX ADD A FOOTER 44
MM.DD.20XX ADD A FOOTER 45
MM.DD.20XX ADD A FOOTER 46
MM.DD.20XX ADD A FOOTER 47
MM.DD.20XX ADD A FOOTER 48
MM.DD.20XX ADD A FOOTER 49
MM.DD.20XX ADD A FOOTER 50
MM.DD.20XX ADD A FOOTER 51
MM.DD.20XX ADD A FOOTER 52
https://www.geeksforgeeks.org/how-to-
integrate-razorpay-payment-gateway-in-
android/
https://dashboard.razorpay.com/app/keys
Topic 5: Android Jetpack Technology - II
https://www.metizsoft.com/blog/android-
jetpack-navigation-component
Topic 6: Introduction to IOS features and
Objective C Features
iOS (formerly iPhone OS) is a mobile operating system created and developed
by Apple Inc. exclusively for its hardware.
It is the operating system that powers many of the company's mobile devices,
including the iPhone and iPod Touch; t
he term also included the versions running on iPads until the name iPadOS was
introduced with version 13 in 2019.
It is the world's second-most widely installed mobile operating system, after
Android.
It is the basis for three other operating systems made by Apple: iPadOS, tvOS,
and watchOS.
It is proprietary software, although some parts of it are open source under the
Apple Public Source License and other licenses.
https://developer.apple.com/library/archive/navigation/
Explore the World with Apple Maps
Apple is committed to building the world’s
best map, and iOS takes Maps even further
with brand new ways to navigate and explore.
Users will experience significantly enhanced
details in cities for neighborhoods,
commercial districts, elevation, and buildings,
new road colors and labels, custom-designed
landmarks, and a new night-time mode with a
moonlit glow. This is a whole new way of
looking at the world through Maps.
New Privacy Features
iOS introduces even more privacy controls to
help protect user information. With on-device
speech recognition, audio of Siri requests is
now processed entirely on iPhone by default,
and performance improves significantly. Mail
Privacy Protection stops senders from learning
whether an email has been opened, and hides
IP addresses so senders can’t learn a user’s
location or use it to build a profile on them.
App Privacy Report offers an overview of how
apps use the access that has been granted to
location, photos, camera, microphone, and
contacts in the last seven days, and which
other domains are contacted.
Redesigned Weather and Notes Apps
Weather includes more graphical displays of
weather data, full-screen maps, and dynamic
layouts that change based on conditions.
Beautifully redesigned animated backgrounds
more accurately reflect the sun’s position and
precipitation, and notifications highlight when
rain or snow starts and stops.
iCloud+ combines everything users love about iCloud with new premium
features, including Hide My Email, expanded HomeKit Secure Video
support, and an innovative new internet privacy service, iCloud Private
Relay, at no additional cost.9 Current iCloud subscribers will be upgraded to
iCloud+ automatically this fall. All iCloud+ plans can be shared with people
in the same Family Sharing group, so everyone can enjoy the new features,
storage, and elevated experience that comes with the service.
The Health app gets a new sharing tab that lets users share
their health data with family, caregivers, or a care team,
Trends gives users a way to focus attention on meaningful
changes in personal health metrics, and Walking Steadiness
is a new metric that empowers people to proactively
manage their fall risk.
Objective-C is a general-purpose, object-oriented programming
language that adds Smalltalk-style messaging to the C
programming language.
This is the main programming language used by Apple for the
OS X and iOS operating systems and their respective APIs,
Cocoa and Cocoa Touch.
This reference will take you through simple and practical
approach while learning Objective-C Programming language.
https://www.tutorialspoint.com/objective_c/index.htm
It is primarily used in developing iOS and Mac OS X operating
systems as well as its applications.
Object-Oriented Programming
Objective-C fully supports object-oriented programming, including the
four pillars of object-oriented development −
Encapsulation
Data hiding
Inheritance
Polymorphism
https://www.tutorialspoint.com/objective_c/index.htm