Mad Chapter - 5 Notes
Mad Chapter - 5 Notes
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.
Method Description
onResume called when activity will start interacting with the user.
onPause called when activity is not visible to the user.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
package example.javatpoint.com.activitylifecycle;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
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.
After a while, you will see onStop method is invoked.
Now see on the emulator. It is on the home. Now click on the center button to
launch the app again.
After a while, you will see onStop and onDestroy methods are invoked.
The onCreate() and onDestroy() methods are called only once throughout the activity
lifecycle.
Intents in Android
Have you ever wondered how a new Activity opens when we click
on some button, suppose the settings button to show the Settings
screen in any app? How does the app opens up when we click on its
notification? How do we get Low battery alert in our mobile? All
these things are possible because of Intent in Android.
It's like a message that Android listens for and then react
accordingly by identifying and invoking the app's appropriate
component (like an Activity, Service, Content Provider, etc.). It can
be within that same app or some other app as well.
1. To start an Activity
2. To start a Service
3. To deliver a Broadcast
1. Explicit Intents
2. Implicit Intents
Explicit Intents
Java file name: This represents the name of the java file of the
Activity you want to open.
startActivity(i);
String a = getIntent().getStringExtra("key1");
Doing this, stores the value stored at key1 into the string
variable a.
Implicit Intent
When you just have to tell what action you want to perform without
worrying which component will perform it, then you can use implicit
intent.
Note: You can specify your own actions for getting used
by intents within your own app (or for getting used by
other apps to invoke components in your app), but you
usually specify action constants defined by the Intent class
or other framework classes.
i.setData(Uri.parse("http://
www.google.co.in"));
startActivity(i);
URI
Uniform Resource Identifier (URI) is a string of characters used to identify a
resource. A URI identifies a resource either by location, or a name, or both. Such
identification enables interaction with representations of the resource over a network,
typically the World Wide Web, using specific protocols.
Intent Filters
You have seen how an Intent has been used to call an another activity. Android OS uses
filters to pinpoint the set of Activities, Services, and Broadcast receivers that can handle
the Intent with help of specified set of action, categories, data scheme associated with
Intent. You will use <intent-filter> element in the manifest file to list down actions,
categories and data types associated with any activity, service, or broadcast receiver.
Following is an example of a part of AndroidManifest.xml file to specify an
activity com.example.MyApplication.CustomActivity which can be invoked by either of
the two mentioned actions, one category, and one data –
<activity android:name=".CustomActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.example.My Application.LAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
Once this activity is defined along with above mentioned filters, other activities will be
able to invoke this activity using either the android.intent.action.VIEW, or using
the com.example.MyApplication.LAUNCH action provided their category
is android.intent.category.DEFAULT.
The <data> element specifies the data type expected by the activity to be called and for
above example our custom activity expects the data to start with the "http://"
There may be a situation that an intent can pass through the filters of more than one
activity or service, the user may be asked which component to activate. An exception is
raised if no target can be found.
There are following test Android checks before invoking an activity −
A filter <intent-filter> may list more than one action as shown above but this list cannot
be empty; a filter must contain at least one <action> element, otherwise it will block all
intents. If more than one actions are mentioned then Android tries to match one of the
mentioned actions before invoking the activity.
A filter <intent-filter> may list zero, one or more than one categories. if there is no
category mentioned then Android always pass this test but if more than one categories
are mentioned then for an intent to pass the category test, every category in the Intent
object must match a category in the filter.
Each <data> element can specify a URI and a data type (MIME media type). There are
separate attributes like scheme, host, port, and path for each part of the URI. An Intent
object that contains both a URI and a data type passes the data type part of the test
only if its type matches a type listed in the filter.
Broadcast Receiver
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.
Broadcast-Receiver
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action
android: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.
android.intent.action.BATTERY_LOW
2
Indicates low battery condition on the device.
android.intent.action.BATTERY_OKAY
3
Indicates the battery is now okay after being low.
android.intent.action.BOOT_COMPLETED
4
This is broadcast once, after the system has finished booting.
android.intent.action.BUG_REPORT
5
Show activity for reporting a bug.
android.intent.action.CALL
6
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.
android.intent.action.DATE_CHANGED
8
The date has changed.
android.intent.action.REBOOT
9
Have the device reboot.
Content Providers
A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. A content provider can use
different ways to store its data and the data can be stored in a database, in files, or even over a
network.
ContentProvider
Content providers let you centralize content in one place and have many different applications
access it as needed. A content provider behaves very much like a database where you can
query it, edit its content, as well as add or delete content using insert(), update(), delete(), and
query() methods. In most cases this data is stored in an SQlite database.
A content provider is implemented as a subclass of ContentProvider class and must implement
a standard set of APIs that enable other applications to perform transactions.
Content URIs
To query a content provider, you specify the query string in the form of a URI which has
following format −
<prefix>://<authority>/<data_type>/<id>
Here is the detail of various parts of the URI −
1 prefix
This is always set to content://
2
authority
This specifies the name of the content provider, for example contacts, browser etc. For third-
party content providers, this could be the fully qualified name, such
as com.tutorialspoint.statusprovider
data_type
3 This indicates the type of data that this particular provider provides. For example, if you are
getting all the contacts from the Contacts content provider, then the data path would
be people and URI would look like thiscontent://contacts/people
id
4 This specifies the specific record requested. For example, if you are looking for contact
number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.
Fragments
A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.
Types of Fragments
Basically fragments are divided as three stages as shown below.
Single frame fragments − Single frame fragments are using for hand hold devices like
mobiles, here we can show only one fragment as a view.
List fragments − fragments having special list view is called as list fragment
Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment.
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<Button
android:id = "@+id/fragment1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignParentTop = "true"
android:layout_centerHorizontal = "true"
android:layout_marginTop = "27dp"
android:text = "fragment1"/>
<Button
android:id = "@+id/fragment2"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignParentTop = "true"
android:layout_centerHorizontal = "true"
android:layout_marginTop = "27dp"
android:text = "fragment2"/>
<LinearLayout
android:id = "@+id/layout"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:orientation = "vertical">
</LinearLayout>
</LinearLayout>
In the above code, we have taken button views and linear layout to show different
fragments.
Step 3 − Add the following code to src /MainActivity.java
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.fragment1).setOnClickListener(new
View.OnClickListener() {
@Override
android.support.v4.app.FragmentManager fm =
getSupportFragmentManager();
android.support.v4.app.FragmentTransaction
fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.layout, first);
fragmentTransaction.commit();
});
findViewById(R.id.fragment2).setOnClickListener(new
View.OnClickListener() {
@Override
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fm.beginTransaction();
fragmentTransaction.replace(R.id.layout, second);
fragmentTransaction.commit();
});
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
@SuppressLint("ValidFragment")
TextView textView;
@Nullable
@Override
textView = view.findViewById(R.id.text);
textView.setText("first");
return view;
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment {
TextView textView;
@Nullable
@Override
textView = view.findViewById(R.id.text);
textView.setText("Second");
return view;
<LinearLayout
xmlns:android =
"http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
</LinearLayout>
Let's try to run your 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.
Select your mobile device as an option and then check your mobile device which
will display your default screen –
A service is a component that runs in the background to perform long-running operations without
needing to interact with the user and it works even if application is destroyed. A service can
essentially take two states –
1
Started
A service is started when an application component, such as an activity, starts it by
calling startService(). Once started, a service can run in the background indefinitely, even if
the component that started it is destroyed.
2
Bound
A service is bound when an application component binds to it by calling bindService(). A
bound service offers a client-server interface that allows components to interact with the
service, send requests, get results, and even do so across processes with interprocess
communication (IPC).
A service has life cycle callback methods that you can implement to monitor changes in the
service's state and you can perform work at the appropriate stage. The following diagram on the
left shows the life cycle when the service is created with startService() and the diagram on the
right shows the life cycle when the service is created with bindService(): (image courtesy :
android.com )
To create an service, you create a Java class that extends the Service base class or one of its
existing subclasses. The Service base class defines various callback methods and the most
important are given below. You don't need to implement all the callbacks methods. However, it's
important that you understand each one and implement those that ensure your app behaves the
way users expect.
2
onBind()
The system calls this method when another component wants to bind with the service by
calling bindService(). If you implement this method, you must provide an interface that clients
use to communicate with the service, by returning an IBinder object. You must always
implement this method, but if you don't want to allow binding, then you should return null.
3
onUnbind()
The system calls this method when all clients have disconnected from a particular interface
published by the service.
4
onRebind()
The system calls this method when new clients have connected to the service, after it had
previously been notified that all had disconnected in its onUnbind(Intent).
5
onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind(). This call is required to perform one-time set-up.
6
onDestroy()
The system calls this method when the service is no longer used and is being destroyed.
Your service should implement this to clean up any resources such as threads, registered
listeners, receivers, etc.
Discuss the need of permissions in Android. Describe the permissions to set system
functionalities like bluetooth,camera.
7. For example, an app that needs to send SMS messages would have this line in the manifest :
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">
<uses-permission android:name="android.permission.SEND_SMS"/>
<application ...>
...
</application>
</manifest>
8. app that needs to allow phone call would have this line in the manifest:
9. app that needs to allow bluetooth would have this line in the manifest:
10. app that needs to allow use of camera would have this line in the manifest:
11. app that needs to allow use of wifi would have this line in the manifest:
12. app that needs to allow use of Simple Caller Talker would have this line in the manifest:
13. app that needs to allow use of Google maps for location would have this line in the manifest:
The following classes are used to play sound and video in the Android framework:
MediaPlayer
This class is the primary API for playing sound and video.
AudioManager
Manifest declarations
Before starting development on your application using MediaPlayer, make sure your
manifest has the appropriate declarations to allow use of related features.
Internet Permission - If you are using MediaPlayer to stream network-based content, your
application must request network access.
Wake Lock Permission - If your player application needs to keep the screen from dimming or
the processor from sleeping, or uses
the MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode()
methods, you must request this permission.
Using MediaPlayer
One of the most important components of the media framework is the MediaPlayer class. An
object of this class can fetch, decode, and play both audio and video with minimal setup. It
supports several different media sources such as:
Local resources
Internal URIs, such as one you might obtain from a Content Resolver
External URLs (streaming)
For a list of media formats that Android supports, see the Supported Media Formats page.
Here is an example of how to play audio that's available as a local raw resource (saved in your
application's res/raw/ directory):
MediaPlayer mediaPlayer = MediaPlayer.create(context,
R.raw.sound_file_1);
mediaPlayer.start(); // no need to call prepare(); create() does that
for you
In this case, a "raw" resource is a file that the system does not try to parse in any particular way.
However, the content of this resource should not be raw audio. It should be a properly encoded
and formatted media file in one of the supported formats.
And here is how you might play from a URI available locally in the system (that you obtained
through a Content Resolver, for instance):
Playing from a remote URL via HTTP streaming looks like this:
The second parameter is the name of the song that you want to play. You have to make a new
folder under your project with name raw and place the music file into it.
Once you have created the Mediaplayer object you can call some methods to start or stop the
music. These methods are listed below.
mediaPlayer.start();
mediaPlayer.pause();
On call to start() method, the music will start playing from the beginning. If this method is called
again after the pause() method, the music would start playing from where it is left and not from
the beginning.
In order to start music from the beginning, you have to call reset() method. Its syntax is given
below.
mediaPlayer.reset();
Apart from the start and pause method, there are other methods provided by this class for better
dealing with audio/video files. These methods are listed below −
1
isPlaying()
This method just returns true/false indicating the song is playing or not
2
seekTo(position)
This method takes an integer, and move song to that particular position millisecond
3
getCurrentPosition()
This method returns the current position of song in milliseconds
4
getDuration()
This method returns the total time duration of song in milliseconds
5
reset()
This method resets the media player
6
release()
This method releases any resource attached with MediaPlayer object
7
setVolume(float leftVolume, float rightVolume)
This method sets the up down volume for this player
8
setDataSource(FileDescriptor fd)
This method sets the data source of audio/video file
9
selectTrack(int index)
This method takes an integer, and select the track from the list on that particular index
10
getTrackInfo()
This method returns an array of track information
activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:text="Audio Controller" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="48dp"
android:text="start" />
<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="pause" />
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button2"
android:layout_toRightOf="@+id/button2"
android:text="stop" />
</RelativeLayout>
MainActivity.java
package com.example.audioplay;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
start=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);
stop=(Button)findViewById(R.id.button3);
//creating media player
final MediaPlayer mp=new MediaPlayer();
try{
//you can change the path, here path is external directory(e.g. sdcard)
/Music/maine.mp3
mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/
maine.mp3");
mp.prepare();
}catch(Exception e){e.printStackTrace();}
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
}
});
}
}
Output:
MediaController class
VideoView class
The android.widget.VideoView class provides methods to play and control the video player. The
commonly used methods of VideoView class are as follows:
Method Description
public void setVideoURI (Uri uri) sets the URI of the video file.
activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<VideoView
android:id="@+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
</RelativeLayout>
MainActivity.java
package com.example.video1;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating MediaController
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
TextToSpeech
Android allows you convert your text into voice. Not only you can convert it but it also allows you
to speak text in variety of different languages.
Android provides TextToSpeech class for this purpose. In order to use this class, you need to
instantiate an object of this class and also specify the initListener. Its syntax is given below −
In this listener, you have to specify the properties for TextToSpeech object , such as its language
,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given below −
ttobj.setLanguage(Locale.UK);
The method setLanguage takes an Locale object as parameter. The list of some of the locales
available are given below −
Sr.No Locale
1 US
2 CANADA_FRENCH
3 GERMANY
4 ITALY
5 JAPAN
6 CHINA
Once you have set the language, you can call speak method of the class to speak the text. Its
syntax is given below −
Sensors
Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device.
Android provides sensor api to work with different types of sensors.
Types of Sensors
Android supports three types of sensors:
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
2) Position Sensors
These are used to measure the physical position of device.
3) Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity etc.
activity_main.xml
activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="114dp"
android:text="TextView" />
</RelativeLayout>
Activity class
Let's write the code that prints values of x axis, y axis and z axis.
MainActivity.java
package com.example.sensorsimple;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.SensorManager;
import android.hardware.SensorEventListener;
import android.hardware.SensorEvent;
import android.hardware.Sensor;
import java.util.List;
public class MainActivity extends Activity {
SensorManager sm = null;
TextView textView1 = null;
List list;
textView1 = (TextView)findViewById(R.id.textView1);
list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(list.size()>0){
sm.registerListener(sel, (Sensor) list.get(0), SensorManager.SENSOR_DELAY_N
ORMAL);
}else{
Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENGTH_
LONG).show();
}
}
@Override
protected void onStop() {
if(list.size()>0){
sm.unregisterListener(sel);
}
super.onStop();
}
}
Output:
Android Camera
These are the following two ways, in which you can use camera in your application
Using existing android camera application in our application
Directly using Camera API provided by android in our application
Apart from the above, there are other available Intents provided by MediaStore. They are listed
as follows
1 ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured
2
ACTION_VIDEO_CAPTURE
It calls the existing video application in android to capture video
EXTRA_SCREEN_ORIENTATION
3
It is used to set the orientation of the screen to vertical or landscape
EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage
INTENT_ACTION_VIDEO_CAMERA
5
This intent is used to launch the camera in the video mode
EXTRA_SIZE_LIMIT
6
It is used to specify the size limit of video or image capture size
Now you will use the function startActivityForResult() to launch this activity and wait for its
result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity. There
are methods defined in the activity class that does the same job , but used when you are not
calling from the activity but from somewhere else. They are listed below
Bluetooth
Bluetooth is a way to send or receive data between two different devices. Android platform
includes support for the Bluetooth framework that allows a device to wirelessly exchange data
with other Bluetooth devices.
Android provides Bluetooth API to perform these different operations.
Scan for other Bluetooth devices
Get a list of paired devices
Connect to other devices through service discovery
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of
this calling by calling the static method getDefaultAdapter(). Its syntax is given below.
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth
constant ACTION_REQUEST_ENABLE. Its syntax is.
Intent turnOn = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Apart from this constant, there are other constants provided the API , that supports different
tasks. They are listed below.
1 ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth
ACTION_STATE_CHANGED
2
This constant will notify that Bluetooth state has been changed
ACTION_FOUND
3
This constant is used for receiving information about each device that is discovered
Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Apart form the parried Devices , there are other methods in the API that gives more control over
Blueetooth. They are listed below.
1 enable()
This method enables the adapter if not enabled
isEnabled()
2
This method returns true if adapter is enabled
disable()
3
This method disables the adapter
getName()
4
This method returns the name of the Bluetooth adapter
setName(String name)
5
This method changes the Bluetooth name
getState()
6
This method returns the current state of the Bluetooth Adapter.
startDiscovery()
7
This method starts the discovery process of the Bluetooth for 120 seconds.
SQLite Database
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes
in with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't
need to establish any kind of connections for it like JDBC,ODBC e.t.c
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
Android AsyncTask
Android AsyncTask going to do background operation on background thread and
update on main thread. In android we cannot directly touch background thread to
main thread in android development. asynctask help us to make communication
between background thread to main thread.
Methods of AsyncTask
onPreExecute() − Before doing background operation we should show
something on screen like progressbar or any animation to user. we can
directly comminicate background operation using on doInBackground() but for
the best practice, we should call all asyncTask methods .
doInBackground(Params) − In this method we have to do background
operation on background thread. Operations in this method should not touch
on any mainthread activities or fragments.
onProgressUpdate(Progress…) − While doing background operation, if you
want to update some information on UI, we can use this method.
onPostExecute(Result) − In this method we can update ui of background
operation result.
<LinearLayout xmlns:android =
"http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:id = "@+id/rootview"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
android:background = "#c1c1c1"
android:gravity = "center_horizontal"
tools:context = ".MainActivity">
<Button
android:id = "@+id/asyncTask"
android:text = "Download"
android:layout_width = "wrap_content"
<ImageView
android:id = "@+id/image"
android:layout_width = "300dp"
</LinearLayout>
In the above xml we have created a button, when user click on the button it going to
download image and append image to imageview.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
InputStream is = null;
ProgressDialog p;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.asyncTask);
imageView=findViewById(R.id.image);
button.setOnClickListener(new View.OnClickListener() {
@Override
asyncTask.execute("https://www.tutorialspoint.com/images/tp-logo-
diamond.png");
});
@Override
super.onPreExecute();
p = new ProgressDialog(MainActivity.this);
p.setIndeterminate(false);
p.setCancelable(false);
p.show();
@Override
try {
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
} catch (IOException e) {
e.printStackTrace();
return bmImg;
@Override
super.onPostExecute(bitmap);
if(imageView!=null) {
p.hide();
imageView.setImageBitmap(bitmap);
}else {
p.show();
In the above code we are downloading image using asyncTask and appending
image to imageview.
Step 4 − Add the following code to manifest.xml
<manifest xmlns:android =
"http://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
<uses-permission android:name =
"android.permission.INTERNET"/>
<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">
<intent-filter>
<category android:name =
"android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>