SlideShare a Scribd company logo
Hello Android World
By Vitaliy Ishchuk, Android dev
eleks.com
Agenda
● Introduction to Android
● Application Fundamentals
● Application Components
● Application Resources
● User Interface
Introduction to Android
Android is a mobile operating system (OS) currently
developed by Google, based on the Linux kernel and
designed primarily for touchscreen mobile devices such as
smartphones and tablets. It has been the best-selling OS on
tablets and on smartphones since 2013, and has the largest
installed base.[wiki]
2003 - was found Android, Inc by 4 guys.
2005 - Google acquired Android Inc. for at least $50 million
2008 - Android 1.0
Android is built on the Linux kernel, but Android is not a Linux.
Linux kernel it`s a component which is responsible for device drivers, power
management, memory management, device management and resource access.
Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime
library (libc) etc.
Android Runtime, there are core libraries and DVM (Dalvik Virtual Machine) which
is responsible to run android application. DVM is like JVM but it is optimized for
mobile devices. It consumes less memory and provides fast performance.
App Framework - Android framework includes Android API's
Applications - All applications
Android is not Linux
Android - Architecture
Application Fundamentals
Android apps are written in the Java
programming language. The Android SDK
tools compile your code — along with any
data and resource files — into an APK: an
Android package, which is an archive file
with an .apk suffix. One APK file contains all
the contents of an Android app and is the file
that Android-powered devices use to install
the app.
Each Android app lives in its own security sandbox
● The Android operating system is a multi-user Linux system in which
each app is a different user.
● By default, the system assigns each app a unique Linux user ID. The
system sets permissions for all the files in an app so that only the user
ID assigned to that app can access them.
● Each process has its own virtual machine (VM), so an app's code
runs in isolation from other apps.
● By default, every app runs in its own Linux process. Android starts
the process when any of the app's components need to be executed,
then shuts down the process when it's no longer needed or when the
system must recover memory for other apps.
● Each app has own lifecycle
App Components
Here are the four types of app components:
Activities - An activity represents a single screen with a user interface.
Services - A service is a component that runs in the background to perform long-
running operations or to perform work for remote processes. A service does not
provide a user interface.
Content providers - A content provider manages a shared set of app data.
Broadcast receivers - A broadcast receiver is an Android component which allows
to register for system or application events.
App Manifest
Every application must have an AndroidManifest.xml file (with precisely that name) in its root
directory. The manifest file presents essential information about your app to the Android
system, information the system must have before it can run any of the app's code.
● It names the Java package for the application. The package name serves as a unique
identifier for the application.
● It describes the components of the application — the activities, services, broadcast
receivers, and content providers that the application is composed of.
● It determines which processes will host application components.
● It declares which permissions the application must have in order to access protected
parts of the API and interact with other applications.
● It also declares the permissions that others are required to have in order to interact with
the application's components.
● It lists the Instrumentation classes that provide profiling and other information as the
application is running.
● It declares the minimum level of the Android API that the application requires.
● It lists the libraries that the application must be linked against.
App Manifest
<manifest>
<uses-permission />
<uses-sdk />
<application>
<activity>
<intent-filter>
<action />
<category />
<data />
</intent-filter>
<meta-data />
</activity>
<service>
<intent-filter> . . . </intent-filter>
<meta-data/>
</service>
</application>
</manifest>
Application Components
● Intent, Intent Filters
● Broadcast Receivers
● Activities
● Services
● Content Providers
● Processes and Threads
Intent and Intent Filters
An Intent is a messaging object you can use to request an action from another app
component. Although intents facilitate communication between components in
several ways.
● start Activity
● start Service
● deliver Broadcast
There are two types of intents:
● Explicit intents specify the component to start by name
● Implicit intents declare a general action to perform, which allows a component
from another app to handle it
An Intent object carries information that the Android system uses to determine
which component to start (such as the exact component name or component
category that should receive the intent), plus information that the recipient
component uses in order to properly perform the action (such as the action to take
and the data to act upon).
The primary information contained in an Intent is the following:
● Component name - The name of the component to start.
● Action - The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN,
etc.
● Data - The data to operate on, such as a person record in the contacts database, expressed as a Uri.
● Category - Gives additional information about the action to execute.
● Type - Specifies an explicit type (a MIME type) of the intent data.
● Extras - This is a Bundle of any additional information.
Building an Intent
Example of explicit intent
public void startUserDetailsActivity(long userId) {
Intent userDetailsIntent = new Intent(this, UserDetailsActivity.class);
userDetailsIntent.putExtra(USER_ID, userId);
startActivity(userDetailsIntent);
}
Example of implicit intent
public void sendMessageIntent(String textMessage) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
Intent Filters
An Intent Filter is an expression in an app's manifest file that specifies the type of
intents that the component would like to receive.
Example of launching main Activity:
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name="MainActivity">
<!-- This activity is the main entry, should appear in app launcher -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
...
</application>
Example of Sharing activity:
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name="ShareActivity">
<!-- This activity handles "SEND" actions with text data -->
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
<!-- This activity also handles "SEND" and "SEND_MULTIPLE" with media data -->
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<action android:name="android.intent.action.SEND_MULTIPLE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="application/vnd.google.panorama360+jpg"/>
<data android:mimeType="image/*"/>
<data android:mimeType="video/*"/>
</intent-filter>
</activity>
</application>
BroadcastReceiver
A Broadcast Receiver is an Android component which allows you to register for
system or application events. All registered receivers for an event are notified by
the Android runtime once this event happens.
How to create a Receiver
1. Create class and which extends the BroadcastReceiver class.
2. Register your receiver
A receiver can be registered via the AndroidManifest.xml file.
Or, you can also register a receiver dynamically via the
Context.registerReceiver() method.
If the event for which the broadcast receiver has registered happens, the
onReceive() method of the receiver is called by the Android system.
Create Local BroadcastReceiver
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) { ... }
};
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
private void sendMessage() {
Intent intent = new Intent("my-event").putExtra("message", "data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Create BroadcastReceiver
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
1. Create a class which extends BroadcastReceiver
2. Declare this class as broadcast receiver in the Android manifest file.
Activities
An Activity is an application component that provides a screen with which users
can interact. Activity = Window
How to create an Activity
1. Create a layout for your screen
<LinearLayout ... >
<EditText ... />
<EditText ... />
<Button ... />
</LinearLayout>
How to create an Activity
2. Create class which extends class Activity and override onCreate()
method
3. Declare your activity in the manifest file<activity
android:name=".LoginActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
}
Activity Lifecycle
When an activity transitions into
and out of the different states it
is notified through various
callback methods.
Complete Android Fragment &
Activity Lifecycle
A Fragment represents a behavior or a portion of user interface in an Activity.
A Fragment must always be embedded in an activity and the fragment's lifecycle is
directly affected by the host activity's lifecycle.
Fragments
Android introduced
fragments in Android 3.0 (API
level 11), primarily to support
more dynamic and flexible UI
designs on large screens,
such as tablets.
Create a Fragment Class
How to add a Fragment into app
public class OrderSpinnerFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_orders_spinner, container, false);
}
}
Adding a fragment to an activity
● Declare the fragment inside the activity's layout file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout ...>
<fragment android:name="com.example.news.ArticleListFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
● Or, programmatically add the fragment to an existing ViewGroup.
private void addUserInfoFragment(){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
UserInfoFragment fragment = new UserInfoFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
Services
A Service is an application component that can perform long-running operations in
the background and does not provide a user interface.
A Service can essentially take two forms: Started, Bound.
Like activities (and other components), you must declare all services in your
application's manifest file
<service android:enabled=["true" | "false"]
android:exported=["true" | "false"]
android:icon="drawable resource"
android:label="string resource"
android:name="string">
...
</service>
Running a Service
Bound Service
A bound service is an implementation of the Service class that allows other
applications to bind to it and interact with it.
// Bind to Service
Intent intent = new Intent(activity, SyncService.class);
activity.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
// Unbind to Service
activity.unbindService(serviceConnection);
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {}
@Override
public void onServiceDisconnected(ComponentName name) {}
};
Running a Service
Started Service
A service is "started" when an application component (such as an activity) starts it
by calling startService().
Caution: A service runs in the same process as the application in which it is
declared and in the main thread of that application, by default.
Service - This is the base class for all services
IntentService - This is a subclass of Service that uses a worker thread to handle all
start requests, one at a time.
Intent intent = new Intent(activity,
SyncService.class);
context.startService(intent);
Service Lifecycle
onCreate() - The service is being created
onStartCommand() - The service is starting,
due to a call to startService()
onBind() - A client is binding to the
service with bindService()
onUnbind() - All clients have unbound with
unbindService()
onRebind() - A client is binding to the
service with bindService(), after
onUnbind() has already been called
onDestroy() - The service is no longer used
and is being destroyed
Content Providers
Content providers manage access to a structured set of data. They encapsulate
the data, and provide mechanisms for defining data security. Content providers are
the standard interface that connects data in one process with code running in
another process. They encapsulate data and provide it to applications through the
single ContentResolver interface.
The ContentResolver methods provide the basic "CRUD" (create, retrieve, update,
and delete) functions of persistent storage.
context.getContentResolver().query(
Contacts.CONTENT_URI, // The
content URI of the words table
new String[]{Data._ID,Data.DISPLAY_NAME_PRIMARY},// The columns to return for each row
null, // Selection criteria
null, // Selection criteria
Data.DISPLAY_NAME_PRIMARY + " ASC"); // The sort order for the
returned rows
Create Custom Content Provider
1. Extend abstract class ContentProvider, implement next methods:
● onCreate() which is called to initialize the provider
● query(Uri, String[], String, String[], String) which returns data to the caller
● insert(Uri, ContentValues) which inserts new data into the content provider
● update(Uri, ContentValues, String, String[]) which updates existing data in the content provider
● delete(Uri, String, String[]) which deletes data from the content provider
● getType(Uri) which returns the MIME type of data in the content provider
2. Declare this class as content provider in the Android manifest file.
3. Declare URI to get access to your data.
<provider
android:authorities="com.example.android.contentprovider"
android:name=".contentprovider.MyContentProvider" >
</provider>
<prefix>://<authority>/<data_type>/<id>
Processes and Threads
When an application component starts and the application does not have any other
components running, the Android system starts a new Linux process for the
application with a single thread of execution. By default, all components of the
same application run in the same process and thread (called the "main" thread).
If an application component starts and there already exists a process for that
application (because another component from the application exists), then the
component is started within that process and uses the same thread of execution.
Additionally, the Andoid UI toolkit is not thread-safe. Thus, there are simply two
rules to Android's single thread model:
● Do not block the UI thread
● Do not access the Android UI toolkit from outside the UI thread
Application Resources
You should always externalize resources such
as images and strings from your application
code, so that you can maintain them
independently. Externalizing your resources
also allows you to provide alternative resources
that support specific device configurations such
as different languages or screen sizes, which
becomes increasingly important as more
Android-powered devices become available
with different configurations.
MyProject/
src/
MyActivity.java
res/
drawable/
graphic.png
layout/
main.xml
info.xml
mipmap/
icon.png
values/
strings.xml
Resource directories supported inside project res/
directory.
Directory Resource Type
animator/
anim/
XML files that define property animations and tween animations.
color/ XML files that define a state list of colors.
drawable/ Bitmap files (.png, .9.png, .jpg, .gif) or XML files.
layout/ XML files that define a user interface layout.
menu/ XML files that define application menus, such as an Options Menu, Context
Menu, or Sub Menu.
values/ XML files that contain simple values, such as strings, integers, and colors.
Providing Alternative Resources
Almost every application should provide
alternative resources to support specific
device configurations. For instance, you
should include alternative drawable
resources for different screen densities and
alternative string resources for different
languages. At runtime, Android detects the
current device configuration and loads the
appropriate resources for your application.
User Interface
All user interface elements in an Android app are built using View and
ViewGroup objects. A View is an object that draws something on the screen
that the user can interact with. A ViewGroup is an object that holds other View
(and ViewGroup) objects in order to define the layout of the interface.
Layouts
A layout defines the visual structure for a user interface, such as the UI for
an activity or app widget. You can declare a layout in two ways:
● Declare UI elements in XML.
● Instantiate layout elements at runtime.
<LinearLayout ... >
<EditText ... />
<EditText ... />
<Button ... />
</LinearLayout>
public class LoginActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
}
Layouts
LinearLayout is a view group that
aligns all children in a single direction,
vertically or horizontally.
RelativeLayout is a view group that
displays child views in relative
positions.
Layouts
TableLayout is a view that groups
views into rows and columns.
FrameLayout is a placeholder on
screen that you can use to display a
single view.
Layouts
ListView is a view group that
displays a list of scrollable
items.
GridView is a ViewGroup
that displays items in a two-
dimensional, scrollable grid.
Widgets
Dialogs and Toasts
A Dialog is a small window that prompts the user to make a decision or enter
additional information. A dialog does not fill the screen and is normally used for
modal events that require users to take an action before they can proceed.
A Toast provides simple feedback about an
operation in a small popup.
That's all.
Quick start in android
development.
Ad

More Related Content

What's hot (17)

Basic of Android App Development
Basic of Android App DevelopmentBasic of Android App Development
Basic of Android App Development
Abhijeet Gupta
 
A Framework for Providing Selective Permissions to Android Applications
A Framework for Providing Selective Permissions to Android ApplicationsA Framework for Providing Selective Permissions to Android Applications
A Framework for Providing Selective Permissions to Android Applications
IOSR Journals
 
Android Basics
Android BasicsAndroid Basics
Android Basics
Arvind Sahu
 
Android programming basics
Android programming basicsAndroid programming basics
Android programming basics
Egerton University
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
master760
 
Lecture 05. UI programming for Mobile Apps
Lecture 05. UI programming for Mobile AppsLecture 05. UI programming for Mobile Apps
Lecture 05. UI programming for Mobile Apps
Maksym Davydov
 
Get an Android tutorial for beginners
Get an Android tutorial for beginnersGet an Android tutorial for beginners
Get an Android tutorial for beginners
JavaTpoint.Com
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and Activity
Nikmesoft Ltd
 
Android Development Tutorial
Android Development TutorialAndroid Development Tutorial
Android Development Tutorial
Germán Bringas
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
Azfar Siddiqui
 
Android basics
Android basicsAndroid basics
Android basics
Akhil Kumar
 
Android studio
Android studioAndroid studio
Android studio
Andri Yabu
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
Utkarsh Mankad
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akka
Webdesign Factory
 
Android Froyo
Android FroyoAndroid Froyo
Android Froyo
Robert Cooper
 
Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!
Massimo Bonanni
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
Igor Moochnick
 
Basic of Android App Development
Basic of Android App DevelopmentBasic of Android App Development
Basic of Android App Development
Abhijeet Gupta
 
A Framework for Providing Selective Permissions to Android Applications
A Framework for Providing Selective Permissions to Android ApplicationsA Framework for Providing Selective Permissions to Android Applications
A Framework for Providing Selective Permissions to Android Applications
IOSR Journals
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
master760
 
Lecture 05. UI programming for Mobile Apps
Lecture 05. UI programming for Mobile AppsLecture 05. UI programming for Mobile Apps
Lecture 05. UI programming for Mobile Apps
Maksym Davydov
 
Get an Android tutorial for beginners
Get an Android tutorial for beginnersGet an Android tutorial for beginners
Get an Android tutorial for beginners
JavaTpoint.Com
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and Activity
Nikmesoft Ltd
 
Android Development Tutorial
Android Development TutorialAndroid Development Tutorial
Android Development Tutorial
Germán Bringas
 
Android Application Development
Android Application DevelopmentAndroid Application Development
Android Application Development
Azfar Siddiqui
 
Android studio
Android studioAndroid studio
Android studio
Andri Yabu
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
Utkarsh Mankad
 
Reactive programming with akka
Reactive programming with akkaReactive programming with akka
Reactive programming with akka
Webdesign Factory
 
Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!Durable Functions vs Logic App : la guerra dei workflow!!
Durable Functions vs Logic App : la guerra dei workflow!!
Massimo Bonanni
 
Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)Ado.Net Data Services (Astoria)
Ado.Net Data Services (Astoria)
Igor Moochnick
 

Similar to Hello android world (20)

Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
Aly Abdelkareem
 
Android Basic- CMC
Android Basic- CMCAndroid Basic- CMC
Android Basic- CMC
Pragati Singh
 
Android beginners David
Android beginners DavidAndroid beginners David
Android beginners David
Arun David Johnson R
 
introductiontoandroiddevelopment (2).ppt
introductiontoandroiddevelopment (2).pptintroductiontoandroiddevelopment (2).ppt
introductiontoandroiddevelopment (2).ppt
NagarajKalligudd1
 
Android Development Basics
Android Development BasicsAndroid Development Basics
Android Development Basics
Prajakta Dharmpurikar
 
Android Security
Android SecurityAndroid Security
Android Security
Suminda Gunawardhana
 
Android development-tutorial
Android development-tutorialAndroid development-tutorial
Android development-tutorial
nirajsimulanis
 
UNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptx
UNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptxUNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptx
UNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptx
LeeroyMugadza
 
Mobile application development
Mobile application developmentMobile application development
Mobile application development
umesh patil
 
Android session 2
Android session 2Android session 2
Android session 2
Ahesanali Suthar
 
Android basics
Android basicsAndroid basics
Android basics
Syed Luqman Quadri
 
Unit2
Unit2Unit2
Unit2
DevaKumari Vijay
 
Getting started with android programming
Getting started with android programmingGetting started with android programming
Getting started with android programming
PERKYTORIALS
 
Aptech Apps
Aptech Apps Aptech Apps
Aptech Apps
RasikaShinde6
 
Android Penetration Testing - Day 1
Android Penetration Testing - Day 1Android Penetration Testing - Day 1
Android Penetration Testing - Day 1
Mohammed Adam
 
Mobile testing android
Mobile testing   androidMobile testing   android
Mobile testing android
Basant Dewangan
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answers
kavinilavuG
 
Android app fundamentals
Android app fundamentalsAndroid app fundamentals
Android app fundamentals
Amr Salman
 
04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)
TECOS
 
Android Components & Manifest
Android Components & ManifestAndroid Components & Manifest
Android Components & Manifest
ma-polimi
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
Aly Abdelkareem
 
introductiontoandroiddevelopment (2).ppt
introductiontoandroiddevelopment (2).pptintroductiontoandroiddevelopment (2).ppt
introductiontoandroiddevelopment (2).ppt
NagarajKalligudd1
 
Android development-tutorial
Android development-tutorialAndroid development-tutorial
Android development-tutorial
nirajsimulanis
 
UNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptx
UNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptxUNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptx
UNIT5newpart1pptx__2024_11_13_09_51_59 (1).pptx
LeeroyMugadza
 
Mobile application development
Mobile application developmentMobile application development
Mobile application development
umesh patil
 
Getting started with android programming
Getting started with android programmingGetting started with android programming
Getting started with android programming
PERKYTORIALS
 
Android Penetration Testing - Day 1
Android Penetration Testing - Day 1Android Penetration Testing - Day 1
Android Penetration Testing - Day 1
Mohammed Adam
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answers
kavinilavuG
 
Android app fundamentals
Android app fundamentalsAndroid app fundamentals
Android app fundamentals
Amr Salman
 
04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)04 programmation mobile - android - (db, receivers, services...)
04 programmation mobile - android - (db, receivers, services...)
TECOS
 
Android Components & Manifest
Android Components & ManifestAndroid Components & Manifest
Android Components & Manifest
ma-polimi
 
Ad

More from eleksdev (20)

Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
eleksdev
 
Angular. presentation
Angular. presentationAngular. presentation
Angular. presentation
eleksdev
 
Lecture java basics
Lecture   java basicsLecture   java basics
Lecture java basics
eleksdev
 
Frontend basics
Frontend basicsFrontend basics
Frontend basics
eleksdev
 
Advanced styles
Advanced stylesAdvanced styles
Advanced styles
eleksdev
 
Css animation, html5 api
Css animation, html5 apiCss animation, html5 api
Css animation, html5 api
eleksdev
 
Improving rpc bkp
Improving rpc bkpImproving rpc bkp
Improving rpc bkp
eleksdev
 
G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2
eleksdev
 
G rpc lection1
G rpc lection1G rpc lection1
G rpc lection1
eleksdev
 
Windows service
Windows serviceWindows service
Windows service
eleksdev
 
Rpc
RpcRpc
Rpc
eleksdev
 
DAL
DALDAL
DAL
eleksdev
 
Aspnet core
Aspnet coreAspnet core
Aspnet core
eleksdev
 
Web service lecture
Web service lectureWeb service lecture
Web service lecture
eleksdev
 
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
eleksdev
 
SDLC. QA Role
SDLC. QA RoleSDLC. QA Role
SDLC. QA Role
eleksdev
 
SDLC. UX Role
SDLC. UX RoleSDLC. UX Role
SDLC. UX Role
eleksdev
 
SDLC. PM Role
SDLC. PM RoleSDLC. PM Role
SDLC. PM Role
eleksdev
 
SDLC. BA Role
SDLC. BA RoleSDLC. BA Role
SDLC. BA Role
eleksdev
 
Version control
Version controlVersion control
Version control
eleksdev
 
Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
eleksdev
 
Angular. presentation
Angular. presentationAngular. presentation
Angular. presentation
eleksdev
 
Lecture java basics
Lecture   java basicsLecture   java basics
Lecture java basics
eleksdev
 
Frontend basics
Frontend basicsFrontend basics
Frontend basics
eleksdev
 
Advanced styles
Advanced stylesAdvanced styles
Advanced styles
eleksdev
 
Css animation, html5 api
Css animation, html5 apiCss animation, html5 api
Css animation, html5 api
eleksdev
 
Improving rpc bkp
Improving rpc bkpImproving rpc bkp
Improving rpc bkp
eleksdev
 
G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2G rpc lection1_theory_bkp2
G rpc lection1_theory_bkp2
eleksdev
 
G rpc lection1
G rpc lection1G rpc lection1
G rpc lection1
eleksdev
 
Windows service
Windows serviceWindows service
Windows service
eleksdev
 
Aspnet core
Aspnet coreAspnet core
Aspnet core
eleksdev
 
Web service lecture
Web service lectureWeb service lecture
Web service lecture
eleksdev
 
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
Continuous Delivery concept overview. Continuous Integration Systems. DevOps ...
eleksdev
 
SDLC. QA Role
SDLC. QA RoleSDLC. QA Role
SDLC. QA Role
eleksdev
 
SDLC. UX Role
SDLC. UX RoleSDLC. UX Role
SDLC. UX Role
eleksdev
 
SDLC. PM Role
SDLC. PM RoleSDLC. PM Role
SDLC. PM Role
eleksdev
 
SDLC. BA Role
SDLC. BA RoleSDLC. BA Role
SDLC. BA Role
eleksdev
 
Version control
Version controlVersion control
Version control
eleksdev
 
Ad

Recently uploaded (20)

Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 

Hello android world

  • 1. Hello Android World By Vitaliy Ishchuk, Android dev eleks.com
  • 2. Agenda ● Introduction to Android ● Application Fundamentals ● Application Components ● Application Resources ● User Interface
  • 3. Introduction to Android Android is a mobile operating system (OS) currently developed by Google, based on the Linux kernel and designed primarily for touchscreen mobile devices such as smartphones and tablets. It has been the best-selling OS on tablets and on smartphones since 2013, and has the largest installed base.[wiki] 2003 - was found Android, Inc by 4 guys. 2005 - Google acquired Android Inc. for at least $50 million 2008 - Android 1.0
  • 4. Android is built on the Linux kernel, but Android is not a Linux. Linux kernel it`s a component which is responsible for device drivers, power management, memory management, device management and resource access. Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc. Android Runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run android application. DVM is like JVM but it is optimized for mobile devices. It consumes less memory and provides fast performance. App Framework - Android framework includes Android API's Applications - All applications Android is not Linux
  • 6. Application Fundamentals Android apps are written in the Java programming language. The Android SDK tools compile your code — along with any data and resource files — into an APK: an Android package, which is an archive file with an .apk suffix. One APK file contains all the contents of an Android app and is the file that Android-powered devices use to install the app.
  • 7. Each Android app lives in its own security sandbox ● The Android operating system is a multi-user Linux system in which each app is a different user. ● By default, the system assigns each app a unique Linux user ID. The system sets permissions for all the files in an app so that only the user ID assigned to that app can access them. ● Each process has its own virtual machine (VM), so an app's code runs in isolation from other apps. ● By default, every app runs in its own Linux process. Android starts the process when any of the app's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other apps. ● Each app has own lifecycle
  • 8. App Components Here are the four types of app components: Activities - An activity represents a single screen with a user interface. Services - A service is a component that runs in the background to perform long- running operations or to perform work for remote processes. A service does not provide a user interface. Content providers - A content provider manages a shared set of app data. Broadcast receivers - A broadcast receiver is an Android component which allows to register for system or application events.
  • 9. App Manifest Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code. ● It names the Java package for the application. The package name serves as a unique identifier for the application. ● It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of. ● It determines which processes will host application components. ● It declares which permissions the application must have in order to access protected parts of the API and interact with other applications. ● It also declares the permissions that others are required to have in order to interact with the application's components. ● It lists the Instrumentation classes that provide profiling and other information as the application is running. ● It declares the minimum level of the Android API that the application requires. ● It lists the libraries that the application must be linked against.
  • 10. App Manifest <manifest> <uses-permission /> <uses-sdk /> <application> <activity> <intent-filter> <action /> <category /> <data /> </intent-filter> <meta-data /> </activity> <service> <intent-filter> . . . </intent-filter> <meta-data/> </service> </application> </manifest>
  • 11. Application Components ● Intent, Intent Filters ● Broadcast Receivers ● Activities ● Services ● Content Providers ● Processes and Threads
  • 12. Intent and Intent Filters An Intent is a messaging object you can use to request an action from another app component. Although intents facilitate communication between components in several ways. ● start Activity ● start Service ● deliver Broadcast There are two types of intents: ● Explicit intents specify the component to start by name ● Implicit intents declare a general action to perform, which allows a component from another app to handle it
  • 13. An Intent object carries information that the Android system uses to determine which component to start (such as the exact component name or component category that should receive the intent), plus information that the recipient component uses in order to properly perform the action (such as the action to take and the data to act upon). The primary information contained in an Intent is the following: ● Component name - The name of the component to start. ● Action - The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc. ● Data - The data to operate on, such as a person record in the contacts database, expressed as a Uri. ● Category - Gives additional information about the action to execute. ● Type - Specifies an explicit type (a MIME type) of the intent data. ● Extras - This is a Bundle of any additional information. Building an Intent
  • 14. Example of explicit intent public void startUserDetailsActivity(long userId) { Intent userDetailsIntent = new Intent(this, UserDetailsActivity.class); userDetailsIntent.putExtra(USER_ID, userId); startActivity(userDetailsIntent); } Example of implicit intent public void sendMessageIntent(String textMessage) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage); sendIntent.setType("text/plain"); startActivity(sendIntent); }
  • 15. Intent Filters An Intent Filter is an expression in an app's manifest file that specifies the type of intents that the component would like to receive. Example of launching main Activity: <application android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name="MainActivity"> <!-- This activity is the main entry, should appear in app launcher --> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ... </application>
  • 16. Example of Sharing activity: <application android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name="ShareActivity"> <!-- This activity handles "SEND" actions with text data --> <intent-filter> <action android:name="android.intent.action.SEND"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/> </intent-filter> <!-- This activity also handles "SEND" and "SEND_MULTIPLE" with media data --> <intent-filter> <action android:name="android.intent.action.SEND"/> <action android:name="android.intent.action.SEND_MULTIPLE"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="application/vnd.google.panorama360+jpg"/> <data android:mimeType="image/*"/> <data android:mimeType="video/*"/> </intent-filter> </activity> </application>
  • 17. BroadcastReceiver A Broadcast Receiver is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens. How to create a Receiver 1. Create class and which extends the BroadcastReceiver class. 2. Register your receiver A receiver can be registered via the AndroidManifest.xml file. Or, you can also register a receiver dynamically via the Context.registerReceiver() method. If the event for which the broadcast receiver has registered happens, the onReceive() method of the receiver is called by the Android system.
  • 18. Create Local BroadcastReceiver private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ... } }; @Override public void onResume() { super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("my-event")); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); } private void sendMessage() { Intent intent = new Intent("my-event").putExtra("message", "data"); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); }
  • 19. Create BroadcastReceiver <receiver android:name="MyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"> </action> </intent-filter> </receiver> public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { } } 1. Create a class which extends BroadcastReceiver 2. Declare this class as broadcast receiver in the Android manifest file.
  • 20. Activities An Activity is an application component that provides a screen with which users can interact. Activity = Window How to create an Activity 1. Create a layout for your screen <LinearLayout ... > <EditText ... /> <EditText ... /> <Button ... /> </LinearLayout>
  • 21. How to create an Activity 2. Create class which extends class Activity and override onCreate() method 3. Declare your activity in the manifest file<activity android:name=".LoginActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> public class LoginActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); } }
  • 22. Activity Lifecycle When an activity transitions into and out of the different states it is notified through various callback methods. Complete Android Fragment & Activity Lifecycle
  • 23. A Fragment represents a behavior or a portion of user interface in an Activity. A Fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. Fragments Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets.
  • 24. Create a Fragment Class How to add a Fragment into app public class OrderSpinnerFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_orders_spinner, container, false); } }
  • 25. Adding a fragment to an activity ● Declare the fragment inside the activity's layout file. <?xml version="1.0" encoding="utf-8"?> <LinearLayout ...> <fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout> ● Or, programmatically add the fragment to an existing ViewGroup. private void addUserInfoFragment(){ FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); UserInfoFragment fragment = new UserInfoFragment(); fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit(); }
  • 26. Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. A Service can essentially take two forms: Started, Bound. Like activities (and other components), you must declare all services in your application's manifest file <service android:enabled=["true" | "false"] android:exported=["true" | "false"] android:icon="drawable resource" android:label="string resource" android:name="string"> ... </service>
  • 27. Running a Service Bound Service A bound service is an implementation of the Service class that allows other applications to bind to it and interact with it. // Bind to Service Intent intent = new Intent(activity, SyncService.class); activity.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); // Unbind to Service activity.unbindService(serviceConnection); private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) {} @Override public void onServiceDisconnected(ComponentName name) {} };
  • 28. Running a Service Started Service A service is "started" when an application component (such as an activity) starts it by calling startService(). Caution: A service runs in the same process as the application in which it is declared and in the main thread of that application, by default. Service - This is the base class for all services IntentService - This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. Intent intent = new Intent(activity, SyncService.class); context.startService(intent);
  • 29. Service Lifecycle onCreate() - The service is being created onStartCommand() - The service is starting, due to a call to startService() onBind() - A client is binding to the service with bindService() onUnbind() - All clients have unbound with unbindService() onRebind() - A client is binding to the service with bindService(), after onUnbind() has already been called onDestroy() - The service is no longer used and is being destroyed
  • 30. Content Providers Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process. They encapsulate data and provide it to applications through the single ContentResolver interface. The ContentResolver methods provide the basic "CRUD" (create, retrieve, update, and delete) functions of persistent storage. context.getContentResolver().query( Contacts.CONTENT_URI, // The content URI of the words table new String[]{Data._ID,Data.DISPLAY_NAME_PRIMARY},// The columns to return for each row null, // Selection criteria null, // Selection criteria Data.DISPLAY_NAME_PRIMARY + " ASC"); // The sort order for the returned rows
  • 31. Create Custom Content Provider 1. Extend abstract class ContentProvider, implement next methods: ● onCreate() which is called to initialize the provider ● query(Uri, String[], String, String[], String) which returns data to the caller ● insert(Uri, ContentValues) which inserts new data into the content provider ● update(Uri, ContentValues, String, String[]) which updates existing data in the content provider ● delete(Uri, String, String[]) which deletes data from the content provider ● getType(Uri) which returns the MIME type of data in the content provider 2. Declare this class as content provider in the Android manifest file. 3. Declare URI to get access to your data. <provider android:authorities="com.example.android.contentprovider" android:name=".contentprovider.MyContentProvider" > </provider> <prefix>://<authority>/<data_type>/<id>
  • 32. Processes and Threads When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread). If an application component starts and there already exists a process for that application (because another component from the application exists), then the component is started within that process and uses the same thread of execution. Additionally, the Andoid UI toolkit is not thread-safe. Thus, there are simply two rules to Android's single thread model: ● Do not block the UI thread ● Do not access the Android UI toolkit from outside the UI thread
  • 33. Application Resources You should always externalize resources such as images and strings from your application code, so that you can maintain them independently. Externalizing your resources also allows you to provide alternative resources that support specific device configurations such as different languages or screen sizes, which becomes increasingly important as more Android-powered devices become available with different configurations. MyProject/ src/ MyActivity.java res/ drawable/ graphic.png layout/ main.xml info.xml mipmap/ icon.png values/ strings.xml
  • 34. Resource directories supported inside project res/ directory. Directory Resource Type animator/ anim/ XML files that define property animations and tween animations. color/ XML files that define a state list of colors. drawable/ Bitmap files (.png, .9.png, .jpg, .gif) or XML files. layout/ XML files that define a user interface layout. menu/ XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu. values/ XML files that contain simple values, such as strings, integers, and colors.
  • 35. Providing Alternative Resources Almost every application should provide alternative resources to support specific device configurations. For instance, you should include alternative drawable resources for different screen densities and alternative string resources for different languages. At runtime, Android detects the current device configuration and loads the appropriate resources for your application.
  • 36. User Interface All user interface elements in an Android app are built using View and ViewGroup objects. A View is an object that draws something on the screen that the user can interact with. A ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the layout of the interface.
  • 37. Layouts A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways: ● Declare UI elements in XML. ● Instantiate layout elements at runtime. <LinearLayout ... > <EditText ... /> <EditText ... /> <Button ... /> </LinearLayout> public class LoginActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); } }
  • 38. Layouts LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. RelativeLayout is a view group that displays child views in relative positions.
  • 39. Layouts TableLayout is a view that groups views into rows and columns. FrameLayout is a placeholder on screen that you can use to display a single view.
  • 40. Layouts ListView is a view group that displays a list of scrollable items. GridView is a ViewGroup that displays items in a two- dimensional, scrollable grid.
  • 42. Dialogs and Toasts A Dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed. A Toast provides simple feedback about an operation in a small popup.
  • 43. That's all. Quick start in android development.

Editor's Notes

  • #24: Росказати історію Фрагментів. Для чого. Головна мета. Два види сервісів! Інтент Сервіс!
  • #25: Росказати історію Фрагментів. Для чого. Головна мета. Два види сервісів! Інтент Сервіс!
  • #26: Росказати історію Фрагментів. Для чого. Головна мета.