hello android world

43
Hello Android World By Vitaliy Ishchuk, Android dev eleks.com

Upload: eleksdev

Post on 07-Jan-2017

1.980 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Hello android world

Hello Android World

By Vitaliy Ishchuk, Android dev

eleks.com

Page 2: Hello android world

Agenda● Introduction to Android● Application Fundamentals● Application Components● Application Resources● User Interface

Page 3: Hello android world

Introduction to AndroidAndroid 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 million2008 - Android 1.0

Page 4: Hello android world

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'sApplications - All applications

Android is not Linux

Page 5: Hello android world

Android - Architecture

Page 6: Hello android world

Application FundamentalsAndroid 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.

Page 7: Hello android world

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

Page 8: Hello android world

App ComponentsHere 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.

Page 9: Hello android world

App ManifestEvery 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.

Page 10: Hello android world

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>

Page 11: Hello android world

Application Components● Intent, Intent Filters● Broadcast Receivers● Activities● Services● Content Providers● Processes and Threads

Page 12: Hello android world

Intent and Intent FiltersAn 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

Page 13: Hello android world

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

Page 14: Hello android world

Example of explicit intentpublic void startUserDetailsActivity(long userId) { Intent userDetailsIntent = new Intent(this, UserDetailsActivity.class); userDetailsIntent.putExtra(USER_ID, userId); startActivity(userDetailsIntent);}

Example of implicit intentpublic 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);}

Page 15: Hello android world

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>

Page 16: Hello android world

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>

Page 17: Hello android world

BroadcastReceiverA 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 Receiver1. 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.

Page 18: Hello android world

Create Local BroadcastReceiverprivate BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ... }};@Overridepublic void onResume() { super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("my-event"));}@Overrideprotected 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);}

Page 19: Hello android world

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.

Page 20: Hello android world

ActivitiesAn Activity is an application component that provides a screen with which users can interact. Activity = Window

How to create an Activity1. Create a layout for your screen<LinearLayout ... >

<EditText ... />

<EditText ... />

<Button ... />

</LinearLayout>

Page 21: Hello android world

How to create an Activity2. 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); }}

Page 22: Hello android world

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

Page 23: Hello android world

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.

Page 24: Hello android world

Create a Fragment Class

How to add a Fragment into apppublic class OrderSpinnerFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_orders_spinner, container, false);

}}

Page 25: Hello android world

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();}

Page 26: Hello android world

ServicesA 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>

Page 27: Hello android world

Running a ServiceBound ServiceA bound service is an implementation of the Service class that allows other applications to bind to it and interact with it.// Bind to ServiceIntent intent = new Intent(activity, SyncService.class);activity.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

// Unbind to Serviceactivity.unbindService(serviceConnection);

private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) {}

@Override public void onServiceDisconnected(ComponentName name) {}};

Page 28: Hello android world

Running a ServiceStarted ServiceA 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 servicesIntentService - 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);

Page 29: Hello android world

Service LifecycleonCreate() - 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

Page 30: Hello android world

Content ProvidersContent 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

Page 31: Hello android world

Create Custom Content Provider1. 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>

Page 32: Hello android world

Processes and ThreadsWhen 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

Page 33: Hello android world

Application ResourcesYou 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

Page 34: Hello android world

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.

Page 35: Hello android world

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.

Page 36: Hello android world

User InterfaceAll 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.

Page 37: Hello android world

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); }}

Page 38: Hello android world

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.

Page 39: Hello android world

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.

Page 40: Hello android world

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.

Page 41: Hello android world

Widgets

Page 42: Hello android world

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.

Page 43: Hello android world

That's all.

Quick start in android development.