0% found this document useful (0 votes)
19 views

What Is Android

This document provides an overview of Android, including what Android is, different types of mobile apps that can be built for Android, why Android is a good platform, and Android components like activities, services, broadcast receivers, and content providers. It also discusses the Android development environment, building a basic "Hello World" app, and steps to create an Android activity.

Uploaded by

Ronaldo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

What Is Android

This document provides an overview of Android, including what Android is, different types of mobile apps that can be built for Android, why Android is a good platform, and Android components like activities, services, broadcast receivers, and content providers. It also discusses the Android development environment, building a basic "Hello World" app, and steps to create an Android activity.

Uploaded by

Ronaldo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Android Notes iGAP Technologies

What is Android ?

- Android is a Platform consists


- Operating System
- middleware
- key apps

Types of Mobile Apps :

- Native Apps
[ Java - Android , swift- iPhone]
- Hybrid Apps [ PhoneGap,Kony,Ionic,Titanium…]
[ HTML + CSS + Java Script = Android & iPhone &
Windows]

- low performance
- complex UI is difficult to design.
- difficult to access the device native components
[ camera , gps , bluetooth ….]
- there is no official framework for developing
Hybrid Apps.
- Support is less.
- immediately we can‟t get the latest updates.

Why Android?
Features :
- Open Source [complete source code is exposed public,
people can see the code & modify code according to their requirement ].
- Application framework is providing infrastructures for the
application developer.
e.g.: WifiManager , LocationManager, SensorManager,BTManager.
- DVM[ Dalvik Virtual Machine] is optimised for mobile
devices to work on low power, low memory & low RAM, it is a
customised JVM.
.java >> JDK >> .class >> DVM >> .dex >> DVM >> 010101
http://www.igaptechnologies.com Page 1
Android Notes iGAP Technologies

- SQLite Database is used to maintain structured data in


Android.
- Supports GPS and different media formats.
- OPEN GLES native library is used to display graphics.
- Android Studio provides rich development environment
for creating the applications.
- Android is a product from OHA [ Open Handset
Alliance] which is lead by Google.
- Android plays a keyrole in IOT [ Internet of Things].
IOT : device- device communication is called as IOT.

Android Components :
Core Android : [ 25 - sessions ]
- Activity
- Service
- Broadcast Receiver
- Content Provider

Activity :

A single screen in the application with UI components


user will interact with the device through Activity.

Service :

A long running background process with out any user


interaction is called as Service.

e.g. : Alarm Service, Wifi Service, Media Player, FM Player…

Broadcast Receiver :

Broadcast receivers are registered for system


announcements.
http://www.igaptechnologies.com Page 2
Android Notes iGAP Technologies

Eg : Headset plugin , charger connected/disconnected , Screen


ON/OFF , Making/Receiving call,
Send/Receive SMS.

Content Provider :

- Content Provider is used to share the data between


multiple applications [ In android one of the security feature is we can‟t
access the other applications data into our application directly, but if the
application is providing content provider then we can access the data
into our application, in android following builtin applications are
providing content provider.
Eg : Contacts, Callog , Media , Settings, Calendar….]

Advanced Android [ 20 sessions]

- WebServices [ SOAP & REST ]


- XML
- JSON
- GSON
- Retrofit

- GoogleMaps
- Google Places
- Google Cloud Messaging [GCM]
10,000 +
- SMS [ 16 ps = 1600 ]
- Call
- E-Mail
- Notifications [ no cost, no limit, 4kb, 4-
weeks , 10 times faster
than SMS]
- Android Material Design[ Recycler View, CardView, FAB,
SnakBar, Navigable Drawer, ToolBar…]
http://www.igaptechnologies.com Page 3
Android Notes iGAP Technologies

- Android Firebase

- Graphics Programming
- Graphics Programming with Cocos-2D

Android Environment :
- Eclipse + ADT plugin
- ADT Bundle
- Android Studio

Hello World
- app
- java
- pkg_name
- *.java
- res
- drawable >> *.png
- layout >> UI.xml
- values >> strings.xml[I18N]
- mipmap >> app icon
- raw >> *.pdf,.mp3,.mp4,.txt..
- menu >> menu.xml
- manifests
- AndroidManifest.xml
- Manifest.xml provides complete description
[ activities , services , permissions,features,
app icon, initial screen…] about the application
Android platform before installing the application
and before start the application it reads
Manifest.xml]

- R.java :
- R is termed as resource.
- R.java is a reference to the res folder.
- R.java is an abstraction between the java file
http://www.igaptechnologies.com Page 4
Android Notes iGAP Technologies

and different resources which are available


in res folder.
- for every resource in res folder it will create a
static integer field in R.java, with the help of this
integer field we can access the resource into
Activity[java],a resource may be a file in res folder
or an id for the UI component,etc..

eg : R.drawable.sample
R.layout.main
R.id.uname
R.raw.test

.apk :
- apk is termed as Android application package.
- it is a installation file in Android platform.
- .apk consists .dex,res,assets,lib and Manifest.xml
- the entire project will be convert into a single
executable file called .apk.
- gradle scripts

XML :
- XML is termed as Extensible as Extensible
Markup Language.
HTML : Hypertext Markup Language.

Markup Language :
- enclosing the data with in tags is called as
Markup Language.

Eg : <employees>
<employee>
<id>123</id>
<name>Mahesh</name>
<desig>TL</desig>
http://www.igaptechnologies.com Page 5
Android Notes iGAP Technologies

</employee>
</employees>

XML :
- XML is interoperable [ platform independent,
technology independent]
- XML is used to transfer the data between
multiple technologies.
- XML is used as textual database.
- XML is used as deployment descriptor.
[ web.xml , Manifest.xml, web-config.xml…]
- by using XML we can create user-defined tags.

Rules :
- every XML element must be properly nested.
- every XML file should have only one root
element.
- tag name shouldn‟t contain space.
- tag name shouldn‟t start with number or
special characters except (_ and $).
- use entities to represent the following values
( > - &gt; < - &lt; & - &amp; „ - &aps; )

- to define our own rules to the XML, use


DTD / XSD.

DTD : Document Type Definition.


XSD : XML Schema Definition.

UI Group :

- UI group is used to specify how to arrange the UI components.


- LinearLayout
- Table Layout
http://www.igaptechnologies.com Page 6
Android Notes iGAP Technologies

- Relative Layout

LinearLayout :
- LinearLayout is one of the UI group which is used to arrange the
UI components in a vertical | horizontal format one after another.

syntax :
<LinearLayout
xmlns:android=“xsd_location”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:orientation=“vertical|horizontal”>

// UI components

</LinearLayout>

for every UI component & UI group we have to specify width &


height following are the possible parameters to specify width & height.

- match_parent
- fill_parent
- wrap_content
- px
- dp [sp]

Steps to create an Activity :


1). - create a class with subtype of android.app.Activity[?].

Activity Life Cycle :


- there are 4 states in Activity
- Doesn‟t Exist
http://www.igaptechnologies.com Page 7
Android Notes iGAP Technologies

- Foreground
- Pause
- Background
- following are the major methods in Activity class, which will
participate in Activity life cycle.

- onCreate() - onPause() - onDestroy()


- onStart() - onStop()
- onResume() - onRestart()

- to maintain the Activity life cycle the class should be subtype of


android.app.Activity.

2). same like main() method in C/C++/Java in Android Activity


onCreate() method will be invoke first, so override the onCreate()
method.
-> Bundle : bundle is a class which is used to get the state of an
Activity.
-> super.onCreate() ? :
the parent class (android.app.Activity) onCreate() method
is having logic to implement Activity life cycle, if we override the
method in the child class the parent class onCreate() logic will not be
execute to execute the parent class onCreate() method we are writing
super.onCreate();

3). there should be a link between XML & Java, use the following
method to set the XML file to Java.

setContentView(R.layout.xml_file);

- Button is having a click event, we can configure the click event


in 2 ways.
- XML
- Java
- XML :
http://www.igaptechnologies.com Page 8
Android Notes iGAP Technologies

- to configure the click event using XML, configure the


following attribute to the UI component.

android:onClick=“method_name”

if we click the UI component it will invoke the specified method in


java if the method is not available it will throw a
MethodNotFoundException.

eg : xml >> android:onClick=“getText”

java >> public void getText(View v){

}
- to get the UI component from XML to Activity, we have to configure
an id for the UI component, use the following attribute to
specify the id.

android:id=“@+id/id_name”

- use the following code to get the UI component into Java.

findViewById(R.id.id_name);

public void getText(View v){

EditText et1=(EditText)findViewById(R.id.et1);
TextView tv1=(TextView) findViewById(R.id.tv1);

tv1.setText(et1.getText());
}

Java :
- to configure the click event using java, configure the
following listener to the UI component.
http://www.igaptechnologies.com Page 9
Android Notes iGAP Technologies

Button b1=(Button)findViewById(R.id.b1);

b1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
// logic
}
});

Intents :

- Intents is used to provide a communication between Activity -


Activity , Activity - Service , Activity - Broadcast Receiver.

- with respect to Activity there are 2 types of intents.


- - Implicit Intents
- Explicit Intents

Implicit Intents :

- Implicit Intents is used to call builtin Activities.


e.g. : camera , browser , settings, messages..
syntax :
Intent i=new Intent();
i.setAction(Intent.ACTION_NAME);
startActivity(i);

Explicit Intents :

- Explicit Intents is used to call user-defined Activities.

syntax :
Intent i=new Intent(context,Activity_name.class);
startActivity(i);
http://www.igaptechnologies.com Page 10
Android Notes iGAP Technologies

by using explicit intents we can invoke 3rd party


application
activities from our application.

Intent i=getPackageManager().

getLauchIntentForPackage(“package_name”);
startActivity(i);

following are the major methods in Intent class.

setAction() setType()
setData() putExtra()
setComponent() getExtra()

- every user defined Activity has to be configure in Manifest.xml with


the following tag inside <application> tag.

<activity android:name=“package_name.class_name”/>

- which activity you want to display the initial screen in your


application configure the following tag to that Activity.

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Auto Complete TextView :

- AutoCompleteTextView is a subtype of EditText, which is used


to provide an auto completion support to the user.
http://www.igaptechnologies.com Page 11
Android Notes iGAP Technologies

syntax :
XML : <AutoCompleteTextView

android:id=“@+id/actv1”
……………/>

Java :
AutoCompleteTextView
actv=(AutoCompleteTextView)

findViewById(R.id.actv1);

- for providing auto completion support first we have to configure


the values in XML/Java.

values configuration using XML :

- res >> values >> strings.xml

<string-array name=“array_name”>
<item> value1 </item>
<item> value2 </item>
<item> value3 </item>
<item> value4 </item>
</string-array>
- use the following method in java , to get the XML configured values
into Activity.

String[]
values=getResources().getStringArray(R.array.array_name);

values configuration using Java :


String[] values=new String[]{value1,value2…};

http://www.igaptechnologies.com Page 12
Android Notes iGAP Technologies

for presenting the configured values we have to create an adapter,


in android there are 3 types of Adapters.
- ArrayAdapter
- CustomAdapter
- Cursor Adapter

ArrayAdapter<String> adapter=new ArrayAdapter<String>

(context,xml_file,values);
actv.setAdapter(adapter);
actv.setThreshold(int);

Spinner :

- Spinner is one of the UI component in android, which is used to


present the list of configured values in a drop-down menu.

XML : <Spinner
android:id=“@+id/sp1”
…………………… />

Java :
Spinner sp1=(Spinner)findViewById(R.id.sp1);

same like ACTV for presenting the values we have to configure the
values in XML/Java.

- if the values are configured in XML, use the following attribute to set
the values.

android:entries=“@array/array_name”

- if the values are configured in Java we have to create an adapter to set


the values.

http://www.igaptechnologies.com Page 13
Android Notes iGAP Technologies

sp.setAdapter(adapter_obj);

- Spinner is having item selected event, to get this event configure the
following listener.

- sp.setOnItemSelectedListener(new OnItemSelectedListener(){
onItemSelected(){ };
doNothingSelected() { };
});

Toast :
- Toast is one of the notification method in Android which is
used to display the text on the screen for few seconds.

syntax :
Toast.makeText(context,message,duration).show();

ListView :

- ListView is one of the UI component which is used present


the list of configured values.

syntax :
XML : <ListView
android:id=“@+id/lview1”
……………/>
Java :
ListView
lview=(ListView)findViewById(R.id.lview1);

same like ACTV & Spinner for presenting the values configure the
values in XML / Java.

http://www.igaptechnologies.com Page 14
Android Notes iGAP Technologies

if the values are configured in XML use the following attribute


to set the values.
android:entries=“@array/array_name”

if the values are configured in Java, create an adapter to set the


values.

- to access the storage information add the following permission in


Manifest.xml.

<uses-permission android:name=“android.permission.

READ_EXTERNAL_STORAGE”/>

- by using ArrayAdapter we can present only String type of data if


you want to present your own UI on individual item use CustomAdapter.

Steps to create CustomAdapter :

- create a class with subtype of android.widget.BaseAdapter.


- it is an abstract class, having following abstract methods.
- getCount()
- getItem()
- getItemId()
- getView()
- from Activity use the following code to set the custom adapter to
the UI component.
ui.setAdapter(new CustomAdapterName());

LayoutInflater :
- LayoutInflater class is used to convert the Xml UI into View
object.

LayoutInflater inflater=LayoutInflater.from(context);
http://www.igaptechnologies.com Page 15
Android Notes iGAP Technologies

View v=inflater.inflate(R.layout.xml_file, view_group object);

Gallery :

Gallery is one of the UI component in Android which is used


to present the list of items in a horizontal format.

syntax :
<Gallery
android:id=“@+id/gal1”
……………… />

WebView :

WebView is one of the UI component in Android, which is


used to display webpages in Android application.

syntax :
xml : <WebView
android:id=“@+id/wview1”
……………./>

java :

WebView
wview=(WebView)findViewById(R.id.wview1);

by using web view we can perform the following operations.

- call browser
- integrate the browser in our application.
- display static .html files.
- we can provide a communication between HTML UI and
Android Activity.
http://www.igaptechnologies.com Page 16
Android Notes iGAP Technologies

-wview.loadUrl(“url_address”) method is used to display specific


webpage on WebView.

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

- set the following method to web view component to display webpages


on web view component.

wview.setWebViewClient(new WebViewClient());

- following are the major methods in WebViewClient class.


- onPageStarted();
- shouldOverrideUrlLoading();
- onPageFinished();

- by default web view will not enable Javascript and zoom controls, to
enable java script and zoom controls set the following methods to web
view component.

wview.getSettings().setJavaScriptEnable(true);
wview.getSettings().setBuiltinZoomControls(true);

- display .html files :

- to display html files place the .html file in assets folder, use the
following code to display .html files.

wview.loadUrl(“file:///android_asset/file_name.html”);

- communication between HTML UI & Android Activity :

http://www.igaptechnologies.com Page 17
Android Notes iGAP Technologies

- by using JavaScript Interface we can provide the communication


between HTML UI & Android Activity.

- wview.addJavaScriptInterface(class_object,”interface_name”);

- by using the second parameter (interface_name) we can


communicate with the specified class methods from JavaScript.

- which method you are calling from Java Script, add the following
annotation on top the method.

@JavaScriptInterface

fragments :

- fragment is one of the UI component in Android (or) fragment is a


subtype of Activity.

<fragment <FrameLayout
android:id=“@+id/frag1” (or)
android:id=“@+id/fram1”
……………….. />
………………. />

- in a single Activity we can create number of fragments, each fragment


is having its own lifecycle and its own UI.

Steps to create a Fragment :

- create a class with subtype of android.app.Fragment.


- same like Activity onCreate() method in fragments
onCreateView() method will be invoke first so provide the
implementation for onCreateView() method.

http://www.igaptechnologies.com Page 18
Android Notes iGAP Technologies

public View onCreateView(LayoutInflater inflater,ViewGroup


vgroup,Bundle b)
{
View v=inflater.inflate(R.layout.xml_file,vgroup,false);
return v;
}

- from Activity use the following code to manage fragments.


FragmentManager fManager=getFragmentManager();
FragmentTransaction tx=fManager.beginTransaction();
tx.add/replace/remove(frag_id, frag_class_obj);
tx.commit();

- fragment concept is introduced from Android 3.0 so the minimum


version to use fragments is Android 3.0.

- if the UI component is available on fragment XML, we can‟t configure


the events using XML.

- use the View object in onCreateView() method to get the UI


component from fragment XML.

Storage Methods :
- Shared Preferences
-

- by using SPF we can maintain huge amount of data, but for every
value we have to specify a unique key its difficult to assign and
remember the keys thats why SPF is preferred to maintain limited data
(e.g. Pattern lock key, Alarm time, login credentials …) , if you want to
maintain the huge amount of data Android is preferred to use
SQLiteDatabase.

http://www.igaptechnologies.com Page 19
Android Notes iGAP Technologies

SQLite Database :
- SQLiteDatabase is used to maintain structure data in
Android.
- SQLiteDatabase class is used to manage SQLiteDB,
openOrCreateDatabase(db_name,mode,cursor_factory) method is used
to get the object of SQLiteDB.

SQLiteDatabase dBase=openOrCreateDatabase(db_name,

mode,cursor_factory);

- SQLiteDB is providing builtin methods to perform CRUD


operations.

- query(); // read
- insert();
- update();
- delete();

- apart from the builtin methods we can execute the native sql
statements by using the following methods.

execSQL(sql_query); // C I U D
rawQuery(sql_query); // R

- we can explore the SQLite DB file using ADM.


ADM >> file_explorer >> data >> data >> package_name >>
database >> file_name.db

- by using SQLite browser we can explore the data from SQLite DB file.

Android Telephony :
- SMS
- Calls
- Emails
http://www.igaptechnologies.com Page 20
Android Notes iGAP Technologies

- Builtin Activity
- Java Mail API

SMS :
- android.telephony.SmsManager class is used to send text
messages in Android.

SmsManager sManager=SmsManager.getDefault();

sManager.sendTextMessage(rec_num,send_num,message,
sent_intent,
delevery_intent);

permission :
<uses-permission

android:name=“android.permission.SEND_SMS”/>

Call :

for making calls android is providing builtin activity use implicit


intents to call builtin Activity.

Intent i=new Intent();


i.setAction(Intent.ACTION_CALL);
i.setData(Uri.parse(“tel:”+number));
startActivity(i);

permission :
<uses-permission android:name=“android.permission.

CALL_PHONE” />

E-mail (builtin Activity) :

http://www.igaptechnologies.com Page 21
Android Notes iGAP Technologies

- for sending an email android is providing a builtin activity use implicit


intents to call builtin Activity.

Intent i=new Intent();


i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL,new String[]{m1,m2,m3..});
i.putExtra(Intent.EXTRA_SUBJECT,”subject_here“);
i.putExtra(Intent.EXTRA_TEXT,”text_here”);
i.putExtra(Intent.EXTRA_STREAM,uri_object);
i.setType(“message/rfc822”); // enable MIME .
startActivity(i.createChooser(intent_obj,”message here”));

permissions :
INTERNET

Attachment functionality :

- Android is providing a builtin Activity to show the


list of files, use implicit intents to call builtin Activity.

Intent i=new Intent();


i.setAction(Intent.ACTION_GET_CONTENT);
i.setType(“*/*”);
startActivityForResult(intent_obj,request_code(int));

in the above method if we specify the second


parameter
(request_code) >=0 after the next Activity is completed (after selecting a
file) it will invoke onActivityResult() method in the current activity
class.

public void onActivityResult(int req_code,int res_code,Intent i){


Uri u=i.getData();
}

http://www.igaptechnologies.com Page 22
Android Notes iGAP Technologies

by using builtin Activity we can‟t send an email in the


background, user has to select any one of the email client for sending an
email , if you want to send an email in the background with out any user
interaction use JavaMail API.

AsyncTask :

- from Android 3.0 if any logic is taking some to process the


Activity thread will not wait to complete the process.
- to execute the long operations [network calls] create a separate
thread or execute the current activity thread in the background by using
AsyncTask.

Steps to work with AsyncTask :


- create a class with subtype of android.os.AsyncTask.
- it is an abstract class having an abstract method called
doInBackground(), so provide the implementation for doInBackground()
method.
- following are the call back methods in AsyncTask.
- onPreExecute()
- doInBackground()
- onPostExecute()
- execute the AsyncTask from Activity by using the following code.
AsyncTaskName task=new AsyncTaskName();
task.execute();

Note : we can‟t communicate with Activity UI components from a


separate Thread.

- add the following statements in Activity onCreate() method to work


with AsyncTask.

http://www.igaptechnologies.com Page 23
Android Notes iGAP Technologies

StrictMode.ThreadPolicy policy=
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Java Mail API :


- to work with Java Mail API , add the following .jar files as
modules.
- activation.jar
- additional.jar
- mail.jar

- add these modules as a dependency modules.


- copy the following .java files into project src folder.
- GmailSender.java
- JSSEProvider.java
- LongOperation.java

- configure your mail credentials (from details) in LongOperation.java.

- LongOperation is an AsyncTask execute the AsyncTask from Activity.

LongOperation lop=new LongOperation(to,subject,message);


lop.execute();

Android Media :
- MediaPlayer
- VideoView
- AudioRecording
- VideoRecording
- Camera & Gallery

MediaPlayer :

http://www.igaptechnologies.com Page 24
Android Notes iGAP Technologies

- android.media.MediaPlayer class is used to play audio files in


Android.
- we can get the audio file from 3 different sources.
- apk
- storage [ internal / external ]
- network
apk : [ res >> raw >> audio_file.mp3 ..]

MediaPlayer mPlayer=

MediaPlayer.create(context,R.raw.audio_file);

storage | network :

MediaPlayer mPlayer=new MediaPlayer();


mPlayer.setDataSource(file_path | network_url );

following are the major methods in MediaPlayer class.

start() seekTo(int) setDataSource()


pause() getCurrentPosition() prepare()
stop() getDuration() reset()

Handler :

- frequently if you want to perform any operation for a


specific time interval use Handler.

android.os.Handler handler=new Handler();


handler.postDelayed(new Runnable(){
public void run() {
// logic
}
}, delay_milli_seconds);
http://www.igaptechnologies.com Page 25
Android Notes iGAP Technologies

VideoView :

VideoView is one of the UI component in Android which is used to


play video files.

xml :
<VideoView
android:id=“@+id/vview1”
……………………../>

java :
VideoView
vview=(VideoView)findViewById(R.id.vview1);
vview.setVideoPath(file_url | network_url);
vview.start();

for providing pause,forward,backward and seekbar functionality set


the following object to VideoView.

vview.setMediaController(new MediaController(this));

Audio Recording :

- android.media.MediaRecorder class is used to record audio and


video in Android.
MediaRecorder recorder=new
MediaRecorder();
- to record audio set the following properties to media recorder.
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.

AMR_NB);
http://www.igaptechnologies.com Page 26
Android Notes iGAP Technologies

recorder.setAudioEncoder(MediaRecorder.AudioEncoder.

AMR_NB);
recorder.setOutputFile(“file_loc/file_name.amr”);
recorder.prepare();
recorder.start();
permissions :
RECORD_AUDIO
WRITE_EXTERNAL_STORAGE

Note :
- android is not providing any api support to pause record
an audio , to provide pause functionality maintain the temp files and
combine all these temp files into a single file when user selects stop.

Video Recording :

- android.media.MediaRecorder class is used to record audio and


video in Android.
MediaRecorder recorder=new MediaRecorder();

- to record video set the following properties to media recorder.


recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
CamcorderProfile profile=CamcorderProfile.get

(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(profile);

recorder.setOutputFile(“file_loc/file_name.mp4”);

by using the above properties we can record video but while we are
recording video we have to show the video preview to the user to show
the video preview we use an advanced UI component called
SurfaceView.
http://www.igaptechnologies.com Page 27
Android Notes iGAP Technologies

<SurfaceView
android:id=“@+id/sview”
……………../>

directly we can‟t perform any operations on SurfaceView, to


manage SurfaceView we have to create an object for SurfaceHolder.

SurfaceHolder sHolder=sview.getHolder();
recorder.setPreviewDisplay(sHolder.getSurface());
recorder.prepare()
recorder.start();

permissions :
CAMERA
RECORD_AUDIO
WRITE_EXTERNAL_STORAGE
Camera & Gallery :

Camera :

- Camera is one of the builtin Activity in Android


use implicit intents to call builtin Activity.

Intent i=new

Intent(“android.media.action.IMAGE_CAPTURE”);
startActivityForResult(i,request_code(123));

Gallery :
- Gallery is one of the builtin Activity in Android use
implicit intents to call builtin Activity.

Intent i=new Intent();


i.setAction(Intent.ACTION_GET_CONTENT);
http://www.igaptechnologies.com Page 28
Android Notes iGAP Technologies

i.setType(“image/*”);
startActivityForResult(i,request_code(124));

in the above method (sAFR()) if we specify the second


parameter (request_code >=0) after the next activity is completed it will
invoke onActivityResult() method in the current activity class.

public void onActivityResult(int request_code,int result_code)


{
if(request_code==123){
// camera captured image
}else if(request_code==124)
{
// image from gallery
}
}

Service :

- Service is one of the component in Android.


- Service is used to used run a long background process with out any
user interaction.
- examples for service is MediaPlayer , FMPlayer , Alarm ,etc..
- we can create a new service by extending android.app.Service
class (or) we can access the builtin services.

- Steps to create a new Service :


- create a class with subtype of android.app.Service.
- it is an abstract class having an abstract method called
onBind() so provide the implementation for onBind() method.
- following are the major methods in Service class.
onCreate();
onStartCommand();
onDestroy();

http://www.igaptechnologies.com Page 29
Android Notes iGAP Technologies

- when we start a service if the service is not available it


will invoke onCreate() and onStartCommand() methods.
- when we start a service if the service is already available
it will invoke only onStartCommand() method.
- when the service is destroyed it will invoke onDestroy()
method.
- service doesn‟t contain any UI we will manage service
from Activity using the following methods.
Intent i=new Intent(context,service_name.class);
startService(i);
stopService(i);
- every service class we have to configure in the manifest.xml
with the following tag inside <application> tag.
<service android:name=“pkg_name.class_name”/>

Broadcast Receiver :
- Broadcast Receiver is registered to get the system announcements.
e.g. : charger connected/disconnected , screen on/off,
making/receiving call, headset plugin , battery
low…. etc..

Steps to work with Broadcast Receiver :

- create a class with subtype of


android.content.BroadcastReceiver.
- it is an abstract class having an abstract method called
onReceive() , so provide the implementation for onReceive() method.
- from Activity class for which events you want to get the
broadcast announcements configure the events using IntentFilter
(group of Intents is called as IntentFilter).

IntentFilter filter=new IntentFilter();


filter.addAction(Intent.ACTION_NAME);
…………..
registerReceiver(obj_of_br,filter);
http://www.igaptechnologies.com Page 30
Android Notes iGAP Technologies

- if any one of the configured event is happened it will


invoke onReceive() method in broadcast receiver.

Content Provider :

- ContentProvider is used to share the data between


multiple applications [ in Android one of the security feature is we can‟t
access the other applications data into our application but if the
application is providing content provider then we can access the data
into our application, in android following builtin applications are
providing content provider
e.g. : contacts , callog , settings , media , calendar .. ]

Steps to work with Content Provider :


- ContentResolver class is used to get the builtin content
providers into Activity, getContentResolver() method is used to get the
object of ContentResolver.
ContentResolver resolver=getContentResolver();

- resolver.query(CP_URI,…..) method is used to get the data from


content provider,return type of this method is Cursor.
Cursor c=resolver.query(CP_URI,…..);

- if the data is available in a cursor for presenting the data Android


is providing an adapter called SimpleCursorAdapter.

SimpleCursorAdapter adapter=new SimpleCursorAdapter

(context,xml_file,cursor_obj,from,to);
ui_comp.setAdapter(adapter);
- from : String[]{DB_COLUMN1 , DB_COLUMN2}
- to : int[] {R.id.ui_comp1,R.id.ui_comp2}

permissions :
http://www.igaptechnologies.com Page 31
Android Notes iGAP Technologies

<uses-permission android:name=“android.permission.

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

READ_CALLOG”/>

Builtin Services :
- Notification Service
- Location Service
- Sensor Service
- Wifi Service
- Bluetooth Service
- Vibrator

getSystemService(Context.SERVICE_NAME) method is used


to get the builtin service into Activity.

Notification Service :
- every android device is having a notification bar we can
display notifications on Notification bar using Notification Service.
- getSystemService(Context.NOTIFICATION_SERVICE)
method is used to get the builtin notification service into Activity,
application framework is providing a class called NotificationManager
to manage notification service.

NotificationManager nManager=(NotificationManager)

getSystemService(Context.NOTIFICATION_SERVICE);

NotificationCompact.Builder builder=new

NotificationCompact.Builder();

http://www.igaptechnologies.com Page 32
Android Notes iGAP Technologies

Location Service :

- getSystemService(Context.LOCATION_SERVICE) method
is used to get the builtin location service into Activity application
framework is providing a class called LocationManager to manage
location service.

LocationManager lManager=(LocationManager)

getSystemService(Context.LOCATION_SERVICE);

- in Android we can get the location in 2 ways.


- GPS_Provider
- Network_Provider
-lManager.getLastKnownLocation(LocationManager.
GPS_PROVIDER) method is used to get the last updated location.

- configure the following listener to get the updated location.


- lManager.requestLocationUpdates(provider_name,
min_time(ms),min_dist(meters),new
LocationListener(){
onProviderDisabled() { };
onProviderEnabled(){};
onLocationChanged(Location l)
{
double
lati=l.getLatitude();
double
longi=l.getLongitude();
}
});
permissions :
ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATION

http://www.igaptechnologies.com Page 33
Android Notes iGAP Technologies

Sensor Service :

based on the device capability Android supports


different types of sensors like ACCESSOLORY ,PROXIMITY,
ORIENTATION, GYROSCOPE and GRAVITY.

getSystemService(Context.SENSOR_SERVICE)
method is used to get the builtin sensor service into Activity , application
framework is providing a class called SensorManager to manage
SensorService.

SensorManager sManager=(SensorManager)

getSystemService(Context.SENSOR_SERVICE);

- to get the sensor events configure the following listener.

sManager.registerListener(new SensorListener(){
public void onSensorChanged(float[] values){

}
public void onAccuracyChanged(int accuracy){

}
},SENSOR_TYPE);

Wifi Service :

- getSystemService(Context.WIFI_SERVICE) method is
used to get the builtin wifi service into Activity, application framework
is providing a class called WifiManager to manage wifi service.

WifiManager wManager=(WifiManager)
http://www.igaptechnologies.com Page 34
Android Notes iGAP Technologies

getSystemService(Context.WIFI_SERVICE);

- wManager.getWifiState() method is used to get the wifi state, return


type of this method is int (0-disabled , 1 - disabling , 2 - enabling , 3 -
enabled ).

- wManager.getScanResults() method is used to get the list of available


wifi devices return type of this method is List<ScanResult>.

List<ScanResult> results=wManager.getScanResults();
for(ScanResult result:results){
result.SSID ; // name
result.frequency; // signal strength
}
- wManager.getConfiguredNetworks() method is used to get the list of
connected wifi devices .

List<WifiConfiguration> list=wManager.getConfiguredNetworks();
for(WifiConfiguration config:list)
{
config.SSID; // name
config.status; // connected / not-connected
}
permissions :
ACCESS_WIFI_STATE
CHANGE_WIFI_STATE

Vibrate :

Vibrator vib=(Vibrator)getSystemService(Context.VIBRATOR_

SERVICE);
vib.vibrate(milli_seconds);

http://www.igaptechnologies.com Page 35
Android Notes iGAP Technologies

permissions :
VIBRATE

Bluetooth :
In android there are different ways to manage BluetoothService
one of the best approach is manage BT service using BluetoothAdapter.

BluetoothAdapter bAdapter=BluetoothAdapter.getDefault();

- bAdapter.isEnbaled() method is used to get the BT state, return type of


this method is boolean.

- bAdapter.enable() / bAdapter.disable() methods is used to change the


BT state.

- bAdapter.startDiscovery() method is used to start searching for BT


devices.

- to get the list of available BT devices we have to configure a Broadcast


receiver.

IntentFilter filter=new IntentFilter();


filter.addAction(BluetoothDevice.EXTRA_FOUND);
registerReceiver(object_of_BR,filter);

class MyReceiver extends BroadcastReceiver


{
onReceive(Context c,Intent data){
BluetoothDevice device=

data.getParcableExtra(BluetoothDevice.EXTRA_DEVICE);
device.getName();
device.getAddress();
}
}
http://www.igaptechnologies.com Page 36
Android Notes iGAP Technologies

permissions :
BLUETOOTH
BLUETOOTH_ADMIN

Dialogs :
- Custom Dialog
- Alert Dialog
- DatePicker
- TimePicker
- Progress Dialog [ Indeterminent /
determinent ]

android.app.Dialog class is used to display dialogs in Android.

Custom Dialog :
- by using custom dialog we can create our own UI & display
the UI on dialog.

Dialog d=new Dialog(activity_object);


d.setContentView(R.layout.xml_file);
d.show();

- if the UI component is available on Dialog XML , we can‟t


configure the events ( e.g. : onClick ) using XML.

- to get the UI component from dialog XML , use dialog object


before findViewById() method.

Button b=(Button)d.findViewById(R.id.XXXX);

AlertDialog :

- android.app.AlertDialog is a child of android.app.Dialog.

http://www.igaptechnologies.com Page 37
Android Notes iGAP Technologies

- AlertDialog is a builtin dialog with these properties ( title , icon ,


message and max we can create 3 possible buttons ).

AlertDialog.Builder builder=new AlertDialog.Builder(this);


builder.setTitle(“title_here”);
builder.setIcon(R.drawable.image_name);
builder.setMessage(“message_here”);
builder.setPositiveButton(“text”,listener);
builder.setNegativeButton(“text”,listener);
builder.setNutralButton(“text”,listener);
builder.show();

if we click any one of the above buttons it will invoke the


following listener.

DialogInterface.OnClickListener listener=
new
DialogInterface.OnClickListener(){
public void onClick(DialogInterface di,int what)
{
// what will tell the button type.
}
};

DatePickerDialog :

DatePickerDialog is a child of android.app.Dialog ,


DPD is used to get date as input from the user.

DatePickerDialog dpd=new DatePickerDialog(context,listener,


year,month,day);
dpd.show();

if we change the date it will invoke the following listener.

http://www.igaptechnologies.com Page 38
Android Notes iGAP Technologies

DatePickerDialog.OnDateSetListener listener=
new DatePickerDialog.OnDateSetListener() {
public void onDateChanged(int year,int month,int day)
{
// logic when date changed..
}
}

TimePickerDialog :
TimePickerDialog is a child of android.app.Dialog which is
used to get time as input from the user.

TimePickerDialog tpd=new TimePickerDialog(context,listener,


hour,minute,24hrs_format);
tpd.show();

if we change the time it will invoke the following listener.

TimePickerDialog.OnTimeSetListener listener=
new TimePickerDialog.OnTimeSetListener()
{
public void onTimeChanged(int hour,int minute)
{
// logic when time changed..
}
}

ProgressDialog :
There are 2 types of Progress dialogs.

- Indeterminent
- Determinant

http://www.igaptechnologies.com Page 39
Android Notes iGAP Technologies

- if you can‟t calculate the time, how much time it will take to
complete a specific task use Indeterminent progress dialog, if you can
calculate the time use determinant progress dialog.

ProgressDialog pDialog=new ProgressDialog(context);


pDialog.setTitle(“title_here”);
pDialog.setMessage(“message_here”);
pDialog.setIcon(R.XXX.XXX);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//
Indeterminent

pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//
Determinent

pDialog.show();

WebServices :

- WebServices [ SOAP / REST ]


- XML
- JSON
- GSON
- Retrofit

Google APIs :

- Google Maps
- Google Places
- Google Cloud Messaging
- Firebase
- Material Design
http://www.igaptechnologies.com Page 40
Android Notes iGAP Technologies

Graphics :
- Graphics Programming
- “ “ + Cocos - 2D

Material Design :

- RecyclerView + CardView
( ListView , Gallery , GridView )
Custom Adapter

Steps to work with Recycler View :

- add recycler view library as a dependency library.


( check in gradle scripts >> app module )
- create recycler view UI component in activity xml.
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rview1"
>

</android.support.v7.widget.RecyclerView>
- get the RecyclerView component from activity xml to java.

RecyclerView rview=(RecyclerView)findViewById(R.id.rview1);

- RecyclerView will act as a ListView , Gallery and GridView , specify


in which format you want‟s to present the data.

LinearLayoutManager lManager=new LinearLayoutManager


(context,LinearLayoutManager.VERTICAL,false); // ListView
http://www.igaptechnologies.com Page 41
Android Notes iGAP Technologies

LinearLayoutManager lManager=new LinearLayoutManager


(context,LinearLayoutManager.HORIZONTAL,false); // Gallery

GridLayoutManager gManager=new GridLayoutManager

(context,num_columns); // GridView

- rView.setLayoutManager(lManager | gManager);

- create an Xml file for individual UI.

- create a holder class by extending RecyclerView.ViewHolder class for


holding the individual xml UI components.

- get the UI components from individual XML by using Holder class


constructor view argument.

- create an adapter class for presenting the data on RecyclerView, for


creating an adapter class create a class with subtype of

RecyclerView.Adapter<ViewHolder class_obj>

- RecyclerView.Adapter is an abstract class having following abstract


methods.

onCreateViewHolder(ViewGroup parent, int viewType);


onBindViewHolder(MyHolder holder, int position);
getItemCount();

- set the Adapter to the RecyclerView UI component.

rview.setAdapter(new MyAdapter());

http://www.igaptechnologies.com Page 42
Android Notes iGAP Technologies

FloatingActionButton [FAB] :
- create a project add design library as a dependency library.
- in Activity XML, create root UI group as CoordinatorLayout.
- create a FAB in Activity XML.

<android.support.design.widget.CoordinatorLayout
android:id="@+id/crl1"
>

<android.support.design.widget.FloatingActionButton
android:id=“@+id/fab1”
/>

</android.support.design.widget.CoordinatorLayout>

- get the FAB into Activity, configure the click event.

FAB fab=(FAB)findViewById(R.id.fab);

- SnackBar :
- SnackBar is similar to Toast message to display message
on the screen for few seconds.

SnackBar s=SnackBar.make(coordinatorlayout_id,message,

SnackBar.LENGTH_LONG);
s.show();

Menu :
- for displaying the menu options configure the menu items in the
following XML.

res >> menu >> file_name.xml

http://www.igaptechnologies.com Page 43
Android Notes iGAP Technologies

<menu>
<item
android:title=“text”

android:icon=“@drawable/image_name”/>
<item
android:title=“text”

android:icon=“@drawable/image_name”/>
</menu>

- use the following methods in Activity to display menu options.

- onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.xml_file,menu);
} // used for displaying menu options.

- onOptionsItemSelected(MenuItem item){
// method will be called by selecting menu item.
}

http://www.igaptechnologies.com Page 44

You might also like