Mobile Devices and Applications Android Basics PDF
Document Details
Uploaded by CharitableLogic418
ASE
Tags
Summary
This document details foundational concepts about mobile devices and Android development, specifically focusing on the characteristics and functionality of mobile devices, Android OS architecture, and APK structure. It covers various aspects, including hardware characteristics, memory types, screen technologies, and connectivity solutions, offering insight into the Android development environment
Full Transcript
Mobile Devices and Applications UNIT 1 – ANDROID BASICS Agenda Objectives Content Evaluation Resources Objectives Efficient usage of mobile technologies in the information society context. Understanding the principles of mobile devices. Learning and achieving Android development skills. Eval...
Mobile Devices and Applications UNIT 1 – ANDROID BASICS Agenda Objectives Content Evaluation Resources Objectives Efficient usage of mobile technologies in the information society context. Understanding the principles of mobile devices. Learning and achieving Android development skills. Evaluation Course activity: 50% ◦ Final quiz exam – 50% Laboratory activity: 50% ◦ 2 Partial Evaluations – 30% ◦ Ongoing evaluation – 20% Final evaluation: ◦ Min. 70% laboratory attendance ◦ Min. 2,5 / 5 points for attending the final exam All evaluation activities must be passed with a minimum of 50% from the total number of points http://pdm.ase.ro Agenda 1. Mobile devices 2. Android framework 3. Development instruments 4. Android application structure Learning path Mobile Architecture Characteristics devices Limitations Mobile Functions User interfaces OS Applications Mobile Life cycle Resources apps Components Android DEV skills Mobile devices CHARACTERISTICS AND FUNCTIONALITY Mobile devices Social networking Managing personal content (contacts, agenda, calendar) Internet browsing Entertainment & Multimedia ◦ Games ◦ Virtual Books ◦ Movies, Images and Music Communication (e-mails, messages and voice services) Navigation (GPS, localization) Financial transactions Characteristics of Mobile Devices Portability Usability Performance Communication Security Mobile devices limitations Dimensions: ◦ Screen, keyboard; Autonomy (battery life) Performance Memory (RAM and ROM) Bandwidth User Experience Form factor Fast and reach full development Prices evolution Mobile devices - trends Hardware and software performances Increased usability Mobile devices Hardware characteristics PROCESSOR MEMORY SCREEN DATA CONNECTIVITY GATHERING Smartphone Flash RAM Power System on a Chip Memory supply (SoC) GPU Screen Communication Processor CPU SIM Audio I/O devices SoC Application processor (CPU) Memory interface Graphic processor (GPU) USB controller Serial interface Bluetooth controller Wi-Fi controller Camera interface RISC architecture ARM and Intel 32/64 bits Application processor Working frequencies: around 2.7 GHz One, dual, quad or octa-core processor Low power consumption SoC Texas Samsung: S3C, Marvell: PXA Instruments: S5C, S5P OMAP Qualcomm: Freescale: iMX nVidia: Tegra MSM, QSD SoC Qualcomm ◦ Snapdragon 400 – 1.6-1.7 GHz, Dual/Quad Core (Nokia Lumia 640/XL, Asus Zenwatch 2, Moto 360 gen. 2, LG Watch Urbane) ◦ Snapdragon 800 MSM8974A (Google Nexus 5, Galaxy S4) ◦ Snapdragon 805 APQ8084 (Galaxy Note 4) ◦ Snapdragon 810 Cortex MSM8x74 (HTC One M9, LG G Flex2, Galaxy S5) ◦ Snapdragon 835 Kryo (2,45 GHz) ◦ Snapdragon 765G with Kryo 475(current Google Pixel 5 specs) (2.45 GHz) ◦ Snapdragon 8 Gen ½ - 4nm – Samsung S22, Xiaomi, Vivo, Motorola, OnePlus Samsung ◦ Exynos 5 1.9 MHz (Galaxy Note 3) ◦ Exynos 5 Octa (Galaxy Tab S, Galaxy Alpha, Galaxy A7/A9) ◦ Exynos 7 Octa (Galaxy S6/Edge, Galaxy Note 5) ◦ Exynos 2200 1octa-core Cortex CPU – Samsung Galaxy S22 (for Europe only) NVIDIA ◦ Tegra 4 – 1.7- 1.9 GHz (NVIDIA Tegra Note, Microsoft Surface 2) ◦ Tegra K1 SoC Texas Instruments ◦ OMAP 4470 (Kindle Fire HD, BN NOKK HD, BlackBerry Z10) Intel ◦ Atom Z2560 (1.6 GHz) , Z2650 (2 GHz) - (Asus, Lenovo, Dell, Samsung) ◦ Atom Z3745 1.3 – 1.7 GHz ◦ Atom C2758, 2.4 GHz ◦ Atom C5000, 2.8 GHz Apple ◦ A5 (iPhone 4S) ◦ A6 (iPhone 5, 5C) ◦ A7 (iPhone 5s) ◦ A8 (iPhone 6) ◦ A9 (iPhone 6s) ◦ A10 (iPhone 7) ◦ A12 (iPhone Xs) – 8 cores CPU, 4 cores GPU ◦ A12Z -2.65 GHz – instruction set A64 – ARM ◦ A14 Bionic – iPhone 12 ◦ A15 Bionic – iPhone 13 ◦ A16 Bionic – iPhone 14; (16 billion transistors); 6core CPU, 5nm – 3.46 GHz Texas Instruments OMAP 44xx Source: http://www.ti.com/general/docs/wtbu/wtbuproductcontent.tsp?templateId=6123&navigationId=12843&contentId=53243 NVIDIA Tegra K1 Source: http://www.bdti.com/InsideDSP/2014/04/29/NVIDIA Qualcomm Snapdragon 80x Source: https://www.qualcomm.com/products/snapdragon Memory Random Access Up to 6GB of RAM Memory – RAM Internal non- Flash NOR – faster to read than to write, code execution, expensive volatile memory NAND – cheap access to data storage External memory SD cards Screen Diagonal – 6 inches ~ 87.6 cm2 Resolution - 1080 x 2340 pixels Pixel density (ppi, dpi) ~ 432 ppi density with 19.5:9 ratio Number of colours - 16M colors Technology ◦ LCD TFT (Thin Film Transistor) ◦ LCD IPS (In Place Switching) ◦ OLED (Organic Light Emitting Diode) – Capacitive ◦ AMOLED (Active-Matrix OLED) ◦ Retina ◦ Gorilla Glass Touchscreen ◦ Resistive ◦ Capacitive Resistive / Capacitive Data Input solutions Touchscreens ◦ virtual keyboard; Numeric keyboard Mini-Joystick (D-pad) QWERTY keyboard Techniques: ◦ Swiping (gestures) ◦ Vocal commands ◦ Fingerprint ◦ Face recognition Connectivity Voice services Data connection Area coverage Extended - Wi-Fi Small – NFC / 802.11 Bluetooth a/b/g/n/ac Wireless connectivity Wireless Bandwidth Technologies network WPAN 9.6 Kbps - 3 Mbps IR, Bluetooth, NFC WLAN 1-300 Mbps 802.11 a, b, g, n WWAN 8 Kbps-300 Mbps GSM (CSD, HCSD), GPRS, EDGE, UMTS (WCDMA) cu HSPDA/HSPA+, LTE cdmaOne, CDMA2000, 5G WWAN (GSM) CSD – Circuit-Switched Data ◦ HSCSD – High Speed Circuit-Switched Data GPRS – General Packet Radio Services EDGE – Enhanced Data Rates for Global Evolution UMTS – Universal Mobile Telecommunications System ◦ HSDPA – High Speed Downlink Packet Access ◦ HSUPA – High Speed Uplink Packet Access LTE – Long Term Evolution 1G Radio signals using analog-based protocols (1980s) 2G GSM / 2.5 – GPRS, EDGE (1990s) 3G UMTS, WCDMA, HSPA (2003) 4G LTE (2009) 5G 5G 2020 WWAN Standard Bandwidth CSD 9.6 -14.4 kbps HSCSD 28.8 - 56 kbps GPRS 115 Kbps EDGE 236.8 Kbps UMTS 384 kpbs – 7.2/14/21/42 Mbps (cu HSDPA/HSPA+) LTE 300 Mbps eMBB 20 Gbps (1Gps) Resources C. Boja, C. Ciurea, M. Doinea – Android Mobile Applications: A Practical Development Guide, ASE Press, 2015, 404 pp., ISBN 978-606-34-0033-9 S. Komatineni, D. MacLean – Pro Android 4, Apress, 2012 R. Meier – Professional Android 4 Application Development, Wiley, 2012 P. Pocatilu, Programarea dispozitivelor mobile, Editura ASE, 2012 P. Pocatilu, I. Ivan ș.a. – Programarea aplicațiilor Android, Editura, ASE, 2015 http://developer.android.com Mobile Devices and Applications UNIT 1 – ANDROID BASICS Agenda Objectives Content Evaluation Resources Objectives Efficient usage of mobile technologies in the information society context. Understanding the principles of mobile devices. Learning and achieving Android development skills. Evaluation Course activity: 50% ◦ Final quiz exam – 50% Laboratory activity: 50% ◦ 2 Partial Evaluations – 30% ◦ Ongoing evaluation – 20% Final evaluation: January ???, 2023 All evaluation activities must be passed with a minimum of 50% from the total number of points http://pdm.ase.ro Agenda 1. Mobile devices 2. Android framework 3. Development instruments 4. Android application structure Learning path Mobile Architecture Characteristics devices Limitations Mobile Functions User interfaces OS Applications Mobile Life cycle Resources apps Components Android DEV skills Mobile operating systems ARCHITECTURE AND MAIN FUNCTIONS Mobile Operating Systems Manage the hardware and software resources Manage the memory Control the processes Check the I/O gates Run applications File management Check the user interface Mobile Operating Systems E-mail / Web Other PIM Messages applications User interface Basic functions / Services Telephony Kernel Drivers Hardware Mobile operating systems Android (Google) Bada (Samsung) Tizen (Tizen Association) BlackBerry OS (BlackBerry/RIM) BREW (Qualcomm) Firefox OS (Mozilla) iOS (Apple) Linux Mobile Palm OS/Garnet OS (Palm) Symbian (Nokia) – obsolete webOS (HP) Windows Phone/Windows CE/Windows Mobile (Microsoft) – obsolete Smartphone 2020 Android Bought by Google in 2005 Open Handset Alliance in 2007 Powered by Linux 2.6.x/3.x kernel Java/Kotlin based applications Phones ◦ HTC One M8, Samsung Galaxy S5, Google Nexus 5 Tablets ◦ Samsung Galaxy Tab, Google Nexus 7 Android Android legacy Free and open source software Sailfish OS, Tizen, Ubuntu Touch OS, OpenMoko Linux, Fedora, CentOS, Debian, SUSE, RedHat Android Stack 15 Android Architecture Android Architecture Dalvik Virtual Machine Androidʼs custom clean-room implementation virtual machine: Provides application portability and runtime consistency Runs optimized file format (.dex) and Dalvik bytecode Java.class /.jar files converted to.dex at build time Mobile Applications ANDROID APP STRUCTURE APK Signature Scheme 20 Android Binary Files APK extension (Android Package) An archive with the optimized Dalvik code and resources Resources can be either compiled or not Besides resources any other file can be added Components Sources (src) ◦ Java source files(java) ◦ Resources(res) ◦ res/drawable ◦ res/layout ◦ res/values ◦ res/menu ◦ res/xml ◦ res/raw Resources obtained from files (assets) Configuration file (AndroidManifest.xml) Compiling properties ◦ build.gradle Generate files (gen) ◦ R.java AndroidManifest.xml Package information (name, version) Application attributes (name, icon, theme, memory options, restrictions, permissions, etc.) Message filters used for app components Uses permissions ◦ Hardware and software requirements ◦ App’s components ◦ Activity declaration, services, content providers, message receivers ◦ The class names associated with app components ◦ Properties SDK versions (minimum, maximum, desired) ◦ Exposed in build.gradle Permission examples Scope Android permission Internet/Network access INTERNET Contact READ/WRITE READ_CONTACTS, WRITE_CONTACTS Calendar READ/WRITE READ_CALENDAR, WRITE_CALENDAR SEND/READ/WRITE SMSs SEND_SMS, READ_SMS, WRITE_SMS TELEPHONY ACCESS CALL_PHONE READ/WRITE on external storage READ_EXTERNAL_STORAGE, devices WRITE_EXTERNAL_STORAGE Determining the GPS coordinates ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION Hardware and software requirements android.hardware.camera android.hardware.camera.autofocus android.hardware.camera.flash android.hardware.nfc android.hardware.sensor.gyroscope android.hardware.Bluetooth android.software.live_wallpaper android.software.home_screen AndroidManifest.xml............ build.gradle android { compileSdkVersion 23 buildToolsVersion "22.0.1" defaultConfig { applicationId "ro.ase.pdm.myapplication" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.0.1' compile 'com.android.support:design:23.0.1' } Programming model Linux based operating system ◦ C native libraries Based on Java Native programming interface Personal virtual machine (Dalvik VM) ◦ Binary code not compatible with Java SE ◦ Based on dex files ◦ Each application runs in a different process ◦ Using JIT compiler ART – Android Runtime ◦ The current execution Android environment ◦ Starting with Android 4.4 ◦ Compile before execution Android binary files.java.class.dex.apk (+resources) javac dx aapt Android app, dalvik bytecode Android binary files apk /META-INF /lib /res /assets AndroidManifest.xml classes.dex resources.arsc Android binary files dexopt – Dalvik dex2oat – ART – JIT – just in time native executed compilation AOT –ahead of time compiler.odex – optimized dex file elf – a compiled dex file Development instruments Programming functionalities User interface Personal information Database Telephony ◦ SQLite Sensors Media API ◦ Motion ◦ Audio ◦ Accelerometer ◦ Video ◦ Gravity sensor ◦ Gyroscope Camera ◦ Rotational vector sensors ◦ Environmental Communication ◦ Barometers – pressure ◦ Socket ◦ Photometers – illumination ◦ HTTP ◦ Thermometers - temperature ◦ Bluetooth ◦ Position ◦ NFC ◦ Orientation sensors ◦ Magnetometers - compass 2D Graphics, Animation ◦ Location 3D Graphics, OpenGL Development instruments Software ◦ Java SE Development Kit (JDK) ◦ Android SDK ◦ Android Studio ◦ Android Tools Integrated development environment ◦ Android Studio – Google official release ◦ Eclipse ◦ plugin: Android Development Toolkit (ADT) ◦ IntelliJ IDEA Android SDK A set of specific internal Resources and image libraries for Android emulators Platform specific Tools for compiling and resources binary code generation Android SDK Android SDK Tools ◦ Platform independent ◦ Subdirector: sdk/tools ◦ Instruments: ◦ Ant scripts for generating the binary package ◦ Debug monitor (ddms) ◦ emulator-arm, emulator-x86 Android SDK Platform-tools ◦ Platform dependent ◦ Director: sdk/platform-tools ◦ Instruments: ◦ adb – android devices communication ◦ sqlite3 Android SDK Build-tools ◦ Director: sdk/build-tools/version/ ◦ Instruments ◦ aapt – resources compilation, R class generation, APK creation ◦ dx – converting Java binary code to Dalvik binary code Android SDK Manager Instruments and platform management Direct access or from the IDE interface Content ◦ Libraries ◦ Source code ◦ Documentation ◦ Emulators Android SDK Manager API Versions Android OS API Level Android 1.5 (Cupcake) 3 Android 1.6 (Donut) 4 Android 2.0 – 2.1 (Éclair) 5-7 Android 2.2 (Froyo) 8 Android 2.3.3 – 2.3.7 (Gingerbread) 9 – 10 Android 3.x (Honeycomb) 11-13 (tablets) Android 4.0.x (Ice Cream Sandwich) 14, 15 API Versions Android OS API Level Android 4.1, 4.2, 4.3 (Jelly Bean) 16, 17, 18 Android 4.4 (KitKat) 19 Android 4.4W (Wear) 20 Android 5.0, 5.1.x (Lollipop) 21, 22 Android 6.0 (Marshmallow) 23 Android 7.0 (Nougat) 24-25 API Versions Android OS API Level Android 8.0 (Oreo) 26-27 Android 9.0 (Pie) 28 Android 10 (Quince) 29 Android 11 (Red Velvet) 30 Android 12 (SnowCone) 31/32 Android 13 (Tiramisu) 33 Android 14 Beta (Upside Down Cake) 34 Android device distribution Android Virtual Device (AVD) Android Virtual Devices ◦ Emulators from Google ◦ External emulators - Genymotion Characteristics ◦ Processor, screen, camera, memory, (RAM, internal, external), API version Emulating ◦ ARM ◦ X86, x64 ◦ Needs Intel HAXM and virtualization support processor Communication through ADB AVD Manager Virtual devices management Can be accessed directly or through the local IDE Defines the internal characteristics of a virtual device AVD Manager AVD Manager AVD Manager Android Profiler Gives access to devices ◦ virtual ◦ physical Management ◦ Process ◦ Memory ◦ Network ◦ Messages (LogCat) ◦ Sensors ◦ File system Access: View > Tool Windows > Profiler Android Profiler Message console (LogCat) Displays messages sent by applications Messages ◦ Warnings (w) ◦ Debug (d) ◦ Errors (e) ◦ Info (i) ◦ Detail info or verbose (v) ◦ Assert Message console (LogCat) Message console (LogCat) Messages are displayed using the android.util.Log class Each message type has its own static method: ◦ e(), w(), i(), d(), v(), wtf() Parameters: ◦ Message source identifier (String) ◦ Message tag for easily group messages ◦ Message Content (String) Generic static method ◦ println() ◦ The first parameter includes message type: Log.ASSERT, Log.ERROR, Log.INFO etc. Example ◦ Log.i("Activity", "Message content"); ◦ println(Log.ASSERT, "Activity", "Message content"); Device File Explorer Resources C. Boja, C. Ciurea, M. Doinea – Android Mobile Applications: A Practical Development Guide, ASE Press, 2015, 404 pp., ISBN 978-606-34-0033-9 S. Komatineni, D. MacLean – Pro Android 4, Apress, 2012 R. Meier – Professional Android 4 Application Development, Wiley, 2012 P. Pocatilu, Programarea dispozitivelor mobile, Editura ASE, 2012 P. Pocatilu, I. Ivan ș.a. – Programarea aplicațiilor Android, Editura, ASE, 2015 http://developer.android.com Mobile Devices and Applications UNIT 2 – APP LIFECYCLE AND UI App Components XML Layouts Summary Procedural Interface Containers App Components The basic components of an Android App Activities ◦ android.app.Activity – base class Services ◦ android.app.Service – base class Content providers ◦ android.content.ContentProvider – base class Message receiver ◦ android.content.BroadcastReceiver – base class ◦ messages Intents ◦ android.content.Intent – base class Activities A single, standalone module of app functionality Fully reusable and interchangeable building blocks Associated with application’s windows Just a single main activity Works with visual controls ◦ Inherited from the View class For passing params one can use Intents For returning results they must be started as sub-activities Activities Activities Have their own life cycle managed by the ART ◦ Multiple stages of creation and destruction ◦ With the possibility of saving the activity’s intermediate states ◦ onSaveInstanceState – called before an activity must be destroyed ◦ onRestoreInstanceState – called if a previous state of an activity was saved Two different states from the activity’s lifecycle perspective ◦ Persistent state (database, content providers or files) ◦ Dynamic state (UI state or instance state) 7 Application class Has access to applications’ methods and settings Base class for maintaining global application state Is the first class instantiated from the app’s package Has a specific context ◦ Available on the entire life cycle of an application ◦ getApplicationContext() Context interface An abstract class defined in the package android.content Gives access to the application’s environment Used for accessing application-specific resources Used for launching new activities Has access to system services Has access to internal files and databases UI Android apps Include one or more activities Each activity can have a visual component associated with it ◦ Code defined ◦ Procedural defined in XML files Include resources: ◦ Associated with the UI ◦ Files processed inside the app 10 Activities Each activity is inserted into a stack of activities managed at the application level by the ART ◦ The first activity is referred to as the active An activity has four activity states ◦ Active / running ◦ Paused ◦ Stopped ◦ Killed Activities Activity lifetimes Entire lifetime – everything that happens between the initial call to onCreate() and the onDestroy() Visible lifetime – from onStart() up to onStop() Foreground lifetime – between the calls to onResume() and onPause() Activity lifetimes Activity State onCreate() Created (invisible) onStart() onRestart() Initialized (visible) onResume() Active (visible) onPause() Paused (partially visible) onStop() Inactive (hidden) onDestroy() Destroyed Activity import android.app.Activity; import android.os.Bundle; public class TestActivity extends Activity { @Override public void onCreate(Bundle stare) { super.onCreate(stare); setContentView(view); } } Configuration changes Changing device orientation ◦ Rotations / IO events / alarms ◦ Showing or hiding virtual keyboard Changing language ◦ Regional settings Configuration changes Configuration changes @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Checks the orientation of the screen if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show(); } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show(); } } Intents Intent objects Asynchronous messages Utility ◦ Invoking activities ◦ Calling services ◦ Sending messages ◦ Sharing data Intents Mechanism by which one activity can launch another one Two types of Intents ◦ Explicit – they request the launch of a specific activity by specifying its class name ◦ Implicit – states the type of action to be performed or providing data of a specific type on which the action is to be performed Broadcast Intents – a system intent sent out to all the applications that have registered an interested Broadcast Receiver ◦ Normal (asynchronous) – sent to all interested Broadcast Receivers ◦ Ordered – sent to one receiver which process it and decides either to pass it or to block it 22 Intent characteristics Action Data Category Additional data Destination App communications Activity Other apps / Sub-activity System App communications Activity => Other activity ◦Send: intent (startActivity) ◦Receive: Bundle Activity Sub-activity ◦Send: intent (startActivityForResult) ◦Receive: Bundle Call a second activity Explicit intent Parameters: ◦ The app’s context ◦ Second activity’s class name Methods (Context class) ◦ startActivity(activityIntent) Sending additional data Attached bundle object ◦ Data container Adding data ◦ putExtra(key, value) Adding a whole container ◦ putExtras(bundle) Getting data ◦ getFloatExtra(), getStringExtra() Getting an entire container ◦ Bundle getExtras() App communications Activity => Other apps’ activities ◦ Intent-filter action ◦ Intent-filter category ◦ Intent-filter data System or other apps => Activity ◦ Using intent-filters registered to broadcasted intents Intent resolutions ◦ Declares the intent action accepted, in the name attribute. The value must be the literal string value of an action, not the class constant. [Data] ◦ Declares the type of data accepted, using one or more attributes that specify various aspects of the data URI (scheme, host, port, path) and MIME type. [Category] ◦ Declares the intent category accepted, in the name attribute. The value must be the literal string value of an action, not the class constant. AndroidManifest.xml Intent calls //1.// - intent for web browser Intent callIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")); //2.// - intent for sending text to another app Intent callIntent = new Intent(Intent.ACTION_SEND); callIntent.putExtra(Intent.EXTRA_TEXT,"Hello from an Android app"); callIntent.setType("text/plain"); //3.// - intent for calling a phone number Intent callIntent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel: 0740111222")); //4.// - intent for starting camera capture Intent callIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Intent receiver void onCreate (Bundle savedInstanceState) { // Get intent, action and MIME type Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { handleSendText(intent); // Handle text being sent } else if (type.startsWith("image/")) { handleSendImage(intent); // Handle single image being sent } } } Launching an activity Intent intent = new Intent(this, TestActivity.class); //adding parameters – test id intent.putExtra("idTest", 1001); //launching the intent startActivity(intent); Getting data @Override public void onCreate(Bundle stare) { super.onCreate(stare); //getting the container Bundle param = getIntent().getExtras(); //testing if param is null int idTest = param.getInt("idTest") } User Interface Declared Interfaces XML files Definition ◦ Graphical elements (res/layout) ◦ Menus (res/menu) They can be reused, included Make use of resources ◦ Constant values (res/values) ◦ strings ◦ dimens ◦ colors Binding activity class by a user interface ◦ setContentView() XML Files (layout) Includes important visual components displayed by an activity Each included element is represented by an XML tag The name of an element is the same with the name of the class used to create objects inside activities The properties of an element are the attributes of an object of the same type Properties android:property ◦ for each individual element android:layout_property ◦ found in LayoutParams class ◦ send to the parent for positioning an element mandatory: ◦ android:layout_width and android:layout_height ◦ Values: ◦ wrap_content or match_parent or constant values XML Resources @package:resourceType/resourceName In the current project ◦ @resourceType/resourceName ◦ Example: ◦ @dimen/dim_font ◦ @color/culoare_fundal Predefined resources ◦ @android:resourceType/resourceName ◦ Example ◦ @android:color/background_light ◦ @android:string/dialog_alert_title Layouts A layout defines the structure for a user interface in your app. All elements in the layout are built using a hierarchy of View and ViewGroup objects. The view objects are called widgets. Declare UI elements in XML using the Android XML syntax found in Android namespace; Layouts declaration Instantiate layout elements at runtime; a method inside the View findViewById(int resourceIdentifier) Activity class: Using elements TextView tv = (TextView) findViewById(R.id.textVie Example wTitlul); inside code tv.setText("text stabilit din cod"); The call should be made after the setContentView() px (pixels) - actual screen pixels. Use is not recommended since different displays will have different pixels per inch. Use dp instead of this unit. dp (density-independent pixels) - an abstract unit of measurement based on the physical density of the device display relative to a 160dpi display baseline, one pixel for a 160dpi mm, in – refers to the actual screen size pt (points; 1/72 inch), fonts sp (scale-independent pixels) - scale-independent pixels. Similar to dp but scaled based on the user’s font preference. Screen size Screen size conversions dp = px/(dpi / 160) px = dp * density Screen density Scaling images - the 3:4:6:8:12:16 ratio rule 48x48 (1.0x 36x36 (0.75x) for baseline) for 72x72 (1.5x) for low-density (ldpi) medium-density high-density (hdpi) (mdpi) 192x192 (4.0x) for 96x96 (2.0x) for 144x144 (3.0x) for extra-extra-extra- extra-high-density extra-extra-high- high-density (xhdpi) density (xxhdpi) (xxxhdpi) Gesture sensitivity BASELINE SCREEN (160 DPI) HIGH DENSITY SCREEN (240 DPI) If the app requires 16 pixels to detect a fling If the app requires 16 pixels to detect a fling action than: action than: 16/160 dpi = 1 / 10th of an inch 16/240 dpi = 1 / 15th of an inch approx. 2.5 mm approx. 1.7 mm Screen dimensions Code example: DisplayMetrics dm = getResources().getDisplayMetrics(); //to pixel conversion int px = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp, dm); //or int px = Math.round(dm.density * dp); Dimensions 3.5”, 240x320 7”, 800x1280 4.7”, 768x1280 Properties android:id – component id Associating an id: "@+id/identifier" Using an identifier: ◦ XML: @id/identifier ◦ Java: R.id.identifier Property Attribute Example Text android:text "Text în clar" @string/text_control Distance inside the android:padding 10dp view itself android:paddingTop|Left|Right| Bottom Properties Background colour android:background #FF00FF @drawable/imag Alignment android:gravity center, left Distance outside android:layout_margin, 30dp the view android:layout_marginTop|Left| Right|Bottom Visibility android:visibility visible, invisible, gone Properties Container View margin padding View content height width PROCEDURAL INTERFACE PROCEDURAL Create runtime controls Constructors ◦ The current context Initializing properties Adding the controls to a container ◦ addView() method Displaying the container ◦ setContentView() Common properties Dimensions: ◦ getWidth() ◦ getHeight() Appearance: ◦ setBackgroundColor(int culoare) ◦ setBackground(Drawable) ◦ setBackgroundResource(int idResursa) Common properties Spacing (distance between the margin of the control and the content itself): ◦ setPadding() ◦ getPaddingLeft() ◦ getPaddingTop() ◦ getPaddingRight() ◦ getPaddingBottom() Active (get or set the enabled property) ◦ setEnabled(boolean) ◦ isEnabled() Focus (get or set the focusable property) ◦ setFocusable(boolean) ◦ isFocusable() Common properties Container parameters ◦ setLayoutParams(LayoutParams) ◦ LayoutParams getLayoutParams() Visibility ◦ setVisibility(int) – VISIBLE, INVISIBLE, GONE Common properties Position (pixels): ◦ absolute ◦ setX()/getX() ◦ setY()/getY() ◦ parent relative ◦ setLeft()/getLeft() ◦ setTop()/getTop() ◦ setRight()/getRight() ◦ setBottom()/getBottom() Common properties Events management: ◦ setOnClickListener() ◦ setOnLongClickListener() ◦ setOnDragListener() ◦ setOnKeyListener() ◦ setOnTouchListener() Procedural interface //container LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); //static element TextView tv = new TextView(this); tv.setText("Title:"); //pixel conversion DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); int hPixeli = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, displayMetrics); Procedural interface //height 20dp, width WRAP_CONTENT LayoutParams lpt = new LayoutParams(LayoutParams.WRAP_CONTENT, hPixeli); tv.setLayoutParams(lpt); //WRAP_CONTENT for editText and button LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); Procedural interface //adding controls to the //editText container EditText et = new EditText(this); layout.addView(tv); et.setText(“Input the title”); layout.addView(et); et.setEms(10); layout.addView(button); et.setLayoutParams(lp); //displaying the container //button setContentView(layout); Button buton = new Button(this); buton.setText(“Send"); buton.setLayoutParams(lp); Container’s parameters Base class ViewGroup.LayoutParams Defined in each container class ◦ LinearLayout.LayoutParams ◦ RelativeLayout.LayoutParams Referred from a view ◦ setLayoutParams() ◦ getLayoutParams() Common properties ◦ width, height Container specific properties ◦ gravity, weight Container’s parameters Constructor ◦ width, height Example //height 20 pixels LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 20); lp.setMargins(10, 10, 10, 10);//left, top, right, bottom (pixels) view.setLayoutParams(lp); LayoutParams lpb = view.getLayoutParams(); lpb.width = ViewGroup.LayoutParams. MATCH_PARENT; lpb.height = ViewGroup.LayoutParams.WRAP_CONTENT; view.setLayoutParams(lpb); CONTAINERS Linear layout A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen. LinearLayout android:orientation ◦ horizontal ◦ vertical LinearLayout Distributing remaining space (proportions) ◦ android:layout_weight view1, view2, view3: android:layout_width="wrap_content" view1, view2, view3: android:layout_width="0dp" android:layout_weight="1" view1, view2 android:layout_width="wrap_content" view3: android:layout_width="0dp" android:layout_weight="1" LinearLayout Control alignment inside the parent android:layout_gravity android:layout_gravitiy="center_vertical" android:layout_gravitiy="center_horizontal" "top" "left" "right" "bottom" android:orientation="horizontal" android:orientation="vertical" Layout gravity vs Gravity FrameLayout Usually used for managing one single visual element Elements positioning: ◦Implicitly: top-left corner ◦Controls can overlap ◦android:layout_gravity Frame layout FrameLayout android:layout_gravitiy="center" ScrollView/HorizontalScrollView Can be used with a FrameLayout Uses one single visual component Uses scrollbars ◦android:scrollbars="vertical" Used for filling the entire available view ◦android:fillViewport="true" TableLayout Derived from LinearLayout Lines ◦ TableRow Associated columns ◦ android:layout_column Spreading across multiple columns: ◦ android:layout_span Content wrapping ◦ android:shrinkColumns ◦ remove free space ◦ android:stretchColumns ◦ Extending columns to cover the remaining space ◦ android:collapseColumns ◦ Hiding columns TableLayout TableLayout TableRow android:layout_span="2" android:layout_column="0" Relative layout Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). RelativeLayout Alignment ◦ Relative to the container (true/false): ◦ android:layout_alignParentTop|Left|Right|Bottom ◦ android:layout_centerHorizontal|Vertical ◦ android:layout_centerInParent ◦ Relative to other components (id-ul): ◦ android:layout_alignLeft|Right|Start|Top|End Positioning ◦ android:layout_below, android:layout_above ◦ android:layout_toEnd|Left|Start|RightOf RelativeLayout android:layout_alignLeft="@id/id3" android:layout_alignParentTop = true id1 id2 id3 id4 id5 id6 id7 id8 id9 android:layout_toRightOf="@id/id8" android:layout_below="@id/id1" Number of columns android:columnCount GridLayout Spreading across multiple rows: android:layout_rowSpan Spreading across multiple columns: android:layout_columnSpan GridLayout android:layout_rowSpan="3" android:layout_columnCount="3" android:layout_row="3" android:layout_columnSpan="2" android:layout_column="0" Include , Merge and ViewStub Create separate layouts that can be included as elements into other layout (nesting) for easiness in control Merge two or more elements in the same parent frame layout Lazy loading one or more elements inside a view (at runtime), the system won’t keep track of the unnecessary elements that are loaded onto the screen (deferred inflation) Resources S. Komatineni, D. MacLean – Pro Android 4, Apress, 2012 R. Meier – Professional Android 4 Application Development, Wiley, 2012 P. Pocatilu, Programarea dispozitivelor mobile, Editura ASE, 2012 P. Pocatilu, I. Ivan ș.a. – Programarea aplicațiilor Android, Editura, ASE, 2015 http://developer.android.com Mobile Devices and Applications UNIT 4 –UI & CONTROLS Summary User interface Controls Handlers USER INTERFACE User interface – UI User interface ◦ visual controls ◦ containers UI with the help of the designer tool ◦ Visually with the designer windows ◦ Manually by creating the XML file UI in Java code User interface Easy and productive mechanism for designing the UI Just one designed layout can start first as the layout associated with the main launcher activity Controls can be initialized by ◦ by declaring them in the XML ◦ by declaring them in Java code Visual components (widgets) – controls Organizing controls (ViewGroup/Layout) – containers User interface View ◦ Used for designing the interface and handling the events ◦ Base class for simple visual components like widgets ◦ package android.view ViewGroup ◦ Extends the View class ◦ Base class for complex visual controls ◦ package android.view Containers Define the visual structure of the UI Manages controls in a: ◦ Linear layout (vertical/horizontal) ◦ Table layout ◦ Relative layout Code and visual declaration Containers LinearLayout ◦ Horizontal or vertical TableLayout ◦ Rows and columns ◦ TableRow GridLayout (from API 14) ◦ Rows and columns ◦ Combines TableLayout with LinearLayout RelativeLayout ◦ Relative to other components ConstraintLayout ◦ Adds dependencies between each visual component Containers FrameLayout ◦ Visual components have stack based management ScrollView /HorizontalScrollView ◦ The content can be scrolled horizontally or vertically AbsoluteLayout (deprecated) ◦ Absolute positioning Controls android.widget.* package; Includes ◦ Static text ◦ Editable text ◦ Buttons ◦ Lists ◦ Progress bars ◦ Etc. Controls TextView ◦ Static text EditText ◦ Used as an input control ◦ Used for filtering input content (inputType) AutoCompleteTextView ◦ Extends EditText class ◦ Binds to a list of suggestions Space (from API 14) ◦ Used for inserting spaces between components Controls Button ◦ Standard buttons ◦ Extends TextView class RadioButton ◦ A button used for exclusive selection ◦ Extends TextView class ◦ Regularly include in a RadioGroup; CheckBox ◦ A button used for multiple selection ToggleButton ◦ Two states button (pushed or not) Switch (from API 14) ◦ Also a two states button (left-right) Controls ImageView ◦ For displaying images ImageButton ◦ Button functionality with images on background ◦ Extends an ImageView Controls ProgressBar ◦ Linear progress bar with upper limit ◦ No upper limit, cyclic SeekBar ◦ Extends ProgressBar, used for choosing a current value Controls AnalogClock DigitalClock/TextClock Chronometer RadioGroup ◦ Grouping RadioButtons Controls Spinner ◦ Control used for displaying a list of values ListView ◦ A list of elements displayed vertically GridView ◦ Displays elements using rows and columns Complex controls ExpandableListView ◦ A list with multiple elements grouped by category Complex controls DatePicker ◦ Date selection ◦ Extends FrameLayout TimePicker ◦ Time selection ◦ Extends also FrameLayout Android Support Library A library with additional classes Used for backwards compatibility in Android ◦ Fragments, action bar, toolbar, etc. Includes also some new components ◦ ViewPager, DrawerLayout ◦ RecyclerView ◦ Floating button ◦ Snackbar ◦ Toolbar with motion Events handling Listener interfaces Ex: View.OnClickListener Events handling Methods for handling events Ex.: onClick() Managing events Ex.: setOnClickListener() Events handling Interface Event handler Event registration View.OnClickListener onClick() setOnClickListener() View.OnKeyListener onKey() setOnKeyListener() View.OnTouchListener onTouch() setOnTouchListener () View.OnLongClickListener onLongClick() setOnLongClickListener() Events handling Implementing the interface ◦ activity class ◦ special class Implementing the interface in an anonymous class The fast way for the onClick event: ◦ The onClick property of an object in the XML file ◦ a special method designed in the activity class Events handling public class Activitate extends Activity implements View.OnClickListener { public void onCreate(Bundle savedInstanceState) { //event registration buton.setOnClickListener(this); //... } //event handler public void onClick(View view) { // must test from which view the event is comming } } Events handling public class EvenimClick implements View.OnClickListener { //event handler public void onClick(View view) { // handling the event } } public class Activitate extends Activity { public void onCreate(Bundle savedInstanceState) { //event registration buton.setOnClickListener(new EvenimClick()); //… } } Events handling //anonymous class buton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // handling the event } }); Events handling XML ◦ android:onClick=“methodName" The activity class: ◦ public void methodName(View view) { … } The method can be used for multiple controls ◦ Testing the control which sends the event ◦ view.getId() Resources S. Komatineni, D. MacLean – Pro Android 4, Apress, 2012 R. Meier – Professional Android 4 Application Development, Wiley, 2012 P. Pocatilu, Programarea dispozitivelor mobile, Editura ASE, 2012 P. Pocatilu, I. Ivan ș.a. – Programarea aplicațiilor Android, Editura, ASE, 2015 http://developer.android.com Mobile Devices and Applications Unit 5 – Adapters & Lists Adaptors ArrayAdapter, SimpleAdapter, BaseAdapter Lists ListView, Spinner, GridView, etc. Summary Selection event Event handlers Serialization Parcelable implementation COMPLEX VISUAL CONTROLS ListView, GridView, Spinner – Complex controls which implement the abstract class AdapterView An adaptor is needed for initialization – Classes that extend BaseAdapter (which Complex implements the Adapter interface): ArrayAdapter visual controls CursorAdapter – SimpleCursorAdapter SimpleAdapter Binding: by the use of the setAdapter() method Other usages AutoCompleteTextView MultiAutoCompleteTextView Gallery ListActivity getListView() setListAdapter() ListFragment RecyclerView Complex visual controls Data source Adaptor Complex controls (AdapterView) Array ArrayAdapter ListView ArrayList SimpleCursorAdapter GridView Cursor CursorAdapter Spinner … User defined Layout element user defined implicit (android.R.layout.) simple_spinner_dropdown_item simple_list_item_1 etc. Adapters Used to manage the connection between a Used by the list Creates a View for each data source and the controls for displaying element from the data elements of a data from data source source collection Predefined views for list controls Predefined resource Description android.R.layout.simple_spinner_item Single line text android.R.layout.simple_spinner_dropdown_item Single line text with selection support android.R.layout.simple_list_item_1 Single line text android.R.layout.simple_list_item_2 Text displayed with two lines android.R.layout.simple_list_item_simple_choice Single line text with exclusive selection support android.R.layout.simple_list_item_multiple_choice Single line text with support for multiple selection android.R.layout.simple_expandable_list_item_1 Single line text android.R.layout.simple_expandable_list_item_2 Two lines text ArrayAdapter Uses a simple data For each element in the Constructor: source like: list: ArrayList, Array, etc. Context (activity) data must be The resource’s id for associated with the the layout associated control used for with a list element displaying the values The TextView identifier The array list of values Example (1) String [] countries = new String[] {"Romania", "Bulgaria", "Greece"}; //list initialization ListView lv = (ListView)findViewById(R.id.lista1); //adaptor initialization ArrayAdapter adaptor = new ArrayAdapter(this, android.R.layout.simple_list_item_1, countries) //adaptor binding with controls lv.setAdapter(adaptor); Example (2) class Country{ String name; int population; Bitmap flag; public String toString() { return “Name: " + name + ", population: " + population; } } Example (2) ArrayList countryList = new ArrayList(); //list initialization ListView lv = (ListView)findViewById(R.id.list1); //adaptor initialization ArrayAdapter adaptor = new ArrayAdapter( this, android.R.layout.simple_list_item_1, countryList); //binding adaptor lv.setAdapter(adaptor); SimpleAdapter Current context; Object list used as data source: – Objects are stored using a Map structure A String type key used for storing the values associated in columns param Resource identifier for each item in the layout; Columns param that will be displayed on each item in the list; The resource identifiers associated with each property, attribute; Example (3) ArrayList countries = new ArrayList(); final String NAME = "name"; final String POPULATION = "population"; for (Country object : countryList) { HashMap country = new HashMap(); country.put(NAME, object.getName()); country.put(POPULATION, object.getPopulation()); countries.add(country ); } Example (3) String[] attributes= { NAME, POPULATION }; int[] identifiers = { android.R.id.text1, android.R.id.text2 }; SimpleAdapter adaptor = new SimpleAdapter( this, // context countries,// object list android.R.layout.simple_list_item_2, attributes, // the list of columns the collection should map onto identifiers); list.setAdapter(adaptor); Extending BaseAdapter class int getCount( ) Returns the number of available elements in the data source Object getItem(int position) Returns the item from a specified position long getItemId(int position) Returns the identifier from a specified position View getView(int position, View Returns a view object for displaying it in the list at a given location convertView, ViewGroup parent) Example (4) Container Romania TextView 19.544.000 people TextView ImageView res/layout/element_lista.xml Example (4) public class CountryAdaptor extends BaseAdapter { private static class ViewHolder { public ImageView flag; public TextView name, population; } List countries; LayoutInflater layoutInflater; CountryAdaptor(Context context, List countries) { layoutInflater = LayoutInflater.from(context); this.countries = countries; } Example (4) @Override public int getCount() { return countries.size(); } @Override public Object getItem(int position) { return countries.get(position); } @Override public long getItemId(int position) { return position; } Example (4) @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = layoutInflater.inflate(R.layout.element_lista, parent, false); } //initializing controls found on the layout ImageView flag = (ImageView) convertView.findViewById(R.id.imageViewFlag); TextView name = (TextView) convertView.findViewById(R.id.textViewName); TextView population = (TextView) convertView.findViewById(R.id.textViewPopulation); Country country = countries.get(position); //setting the values flag.setImageBitmap(country.getFlag()); name.setText(country.getName()); population.setText(country.getPopulation() + " people"); return convertView; } } Example (4) @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null) { //the control is rendered for the first time convertView = layoutInflater.inflate(R.layout.element_lista, parent, false); holder = new ViewHolder(); holder.flag = (ImageView) convertView.findViewById(R.id.imageViewFlag); holder.name = (TextView) convertView.findViewById(R.id.textViewName); holder.population = (TextView) convertView.findViewById(R.id.textViewPopulation); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } Country country = countries.get(position); holder.flag.setImageBitmap(country.getFlag()); holder.name.setText(country.getName()); holder.population.setText(country.getPopulation() + " people") return convertView; } Example (4) CountryAdaptor countryAdapter = new CountryAdaptor( this, countryList); lv.setAdapter(countryAdapter); Lists Spinner getSelectedItem() getSelectedItemId() ListView getItemAtPosition() getItemIdAtPosition() GridView getItemAtPosition() getItemIdAtPosition() List events Interface Main event method Registering event AdapterView.OnItemSelectedListener onItemSelected() setOnItemSelectedListener() onNothingSelected() AdapterView.OnItemClickListener onItemClick() setOnItemClickListener() OnItemClickListener (List) private AdapterView.OnItemClickListener movieLVClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { String value = ((TextView)view).getText().toString(); Toast.makeText(MovieList.this,"You selected: " + value,Toast.LENGTH_SHORT).show(); } }; OnItemSelectedListener (Spinner) spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { TextView tv = (TextView)view; movieGenre = tv.getText().toString(); } @Override public void onNothingSelected(AdapterView parent) { } }); Item selection (GridView) private AdapterView.OnItemClickListener gvClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { TextView tv = (TextView)view.findViewById(R.id.textViewTitle); Toast.makeText(MovieGallery.this,"You clicked: " + tv.getText(),Toast.LENGTH_SHORT).show(); } }; OBJECT SERIALIZATION SERIALIZING OBJECTS Serializable Parcelable Java Android Storage Transport Versioning – Process communication Simplicity vs. fast processing Parcel – reflection Efficiency vs. complexity Serializable Interface java.io ObjectOutputStream ObjectInputStream transient – the fields that you don’t wish to serialize Interface methods – void writeObject(ObjectOutputStream out) – void readObject(ObjectInputStream in) Parcel Class Data container Used for carrying data between processes Primitives & String – writeByte(), writeDouble(), writeString() etc. – readByte(), readDouble(), readString() etc. Complex data types – writeList(), writeBundle(), writeStringArray() etc. – readList(), readBundle(), readStringArray() etc. Parcelable Interface android.os writeToParcel() - flattens the object into a Parcel – the object is written in a Parcel the Constructor receives a Parcel object – initializes the object from the Parcel describeContents() - describe the kinds of special objects contained in this Parcelable instance's marshaled representation the static field CREATOR – implements the Parcelable interface – calls for the constructor with a Parcel object Parcelable Interface void writeToParcel(Parcel dest, int flags) ClassName(Parcel in) public static final Parcelable.Creator< ClassName> CREATOR = new Parcelable.Creator< ClassName>() { public Clasa createFromParcel(Parcel pc) { return new ClassName(pc); } public Clasa[] newArray(int dim) { return new ClassName[dim]; } }; public int describeContents() Resources R. Meier – Professional Android 4 Application Development, Wiley, 2012 S. Komatineni, D. MacLean – Pro Android 4, Apress, 2012 P. Pocatilu, Programarea dispozitivelor mobile, Editura ASE, 2012 P. Pocatilu, I. Ivan ș.a. – Programarea aplicațiilor Android, Editura, ASE, 2015 http://developer.android.com Mobile Devices and Applications Unit 6 – Android Asynchronous Operations Threads Handlers Callback / Callable Executor / Runnable Network access Summary – Socket – HTTP – Web services ASYNC OPERATIONS Asynchronous operations Used for heavily resource consuming activities They must be executed on an independent thread – the main thread or UI thread must not be blocked Two main problems: – thread communications, how to send input and output data – publishing progress: how to interact with the controls associated with the main thread Android ANR Application Not Responding Trigger conditions: – while your activity is in the foreground, your app has not responded to an input event or BroadcastReceiver (such as key press or screen touch events) within 5 seconds. – while you do not have an activity in the foreground, your BroadcastReceiver hasn't finished executing within a considerable amount of time. The app is doing slow operations involving I/O on the main thread. The app is doing a long calculation on the main thread. Diagnosing The main thread is doing a synchronous binder call to another process, and that other process is taking a long ANRs time to return. The main thread is blocked waiting for a synchronized block for a long operation that is happening on another thread. The main thread is in a deadlock with another thread, either in your process or via a binder call Asynchronous operations Java – Thread class – Runnable interface Android – Methods synchronized(this) runOnUiThread(Runnable) (Activity class) – switches between threads post(Runnable) (View class) – a new thread managed by a handler postDelayed(Runnable, long) (View class) – Handler class – AsyncTask class Asynchronous operations Other thread UI Thread Runnable Thread Control run() Control.property = result //// Heavy processing + result Asynchronous operations Main thread run() Runnable Control heavy processing + result Thread run() Runnable control.attribut = result Activity#runOnUiThread(Runnable) View#post(Runnable) View#postDelayed(Runnable, long) Handler Manages two types of messages: – what – already created messages – Runnable – messages that contain code to be executed Handles messages processed by the Looper: – extend Handler class with our own custom implementation and override handleMessage() method – create Handler instance with constructor providing custom Handler.Callback (which has handleMessage method) Handler post() – causes the Runnable object to be added to the message queue dispatchMessage() – handle system message on the thread where it is called sendMessage() – pushes a message onto the end of the message queue of the thread where the Handler was created; obtainMessage() – returns a new Message from the global message pool; handleMessage() – used to handle the message into subclasses getMainLooper() – returns the Looper for the main thread Handler workflow Client initializes Handler and Looper Client sends messages to Handler Handler posts messages to Looper’s MessageQueue Looper processes messages in MessageQueue When message is ready to be processed, Looper sends it back to Handler, which can handle message. AsyncTask class -obsolete Abstract class AsyncTask Implemented methods: – doInBackground(paramsType… pars) – onProgressUpdate(progressType…pars) publishProgress() – onPostExecute(resultType par) – onPreExecute() Call: – execute(params) method Does not accept primitives, only object type values AsyncTask class onPreExecute() – The first method executed after initializing a call doInBackground() – Heavily resource processing – Runs asynchronously onProgressUpdate() – It is constantly executed for displaying the progress of the doInBackground operations – publishProgress() onPostExecute() – Called after the doInBackground has finished processing – Receives the result returned by the processing stage Calls for the AsyncTask class UI THREAD SECONDARY THREAD 1. onPreExecute() 2. doInBackground() 4. onProgressUpdate() 3. publishProgress() 5. onPostExecute() AsyncTask class class HeavyTask extends AsyncTask { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Bitmap doInBackground(String... params) { publishProgress((Double)values); return null; } @Override protected void onProgressUpdate(Double... values) { super.onProgressUpdate(values); } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); } } AsyncTask class onPreExecute() method: Important aspects: initialization of anything @Override needed to display the protected void onPreExecute() { super.onPreExecute(); progress //initializing objects called once before the } doInBackground() method AsyncTask class doInBackground() method: Important aspects: @Override output type variable number of arguments, an array of protected Bitmap strings doInBackground(String... parameters are sent from params) the UI thread { input type the execute method of the //heavy processing; AsyncTask will receive a publishProgress(value); variable number of params } the method always returns a parameter of the same type declared by the AsyncTask AsyncTask class onPostExecute() method: Important aspects: third param in the The parameter in the AsyncTask declaration list is the one @Override protected void returned by the onPostExecute(Bitmap bitmap) { doInBackground method super.onPostExecute(bitmap); //processing the result This method runs on } the UI thread so it can interact with the UI controls AsyncTask class onProgressUpdate() method: Important aspects: second param in @Override the AsynTask The values are sent by protected void declaration calling the onProgressUpdate(Double... values) publishProgress() { method from the super.onProgressUpdate(values); doInBackground() //displaying the progress This method runs on } the UI thread so it can interact with the UI controls Downloading files System Service DownloadManager – getSystemService(DOWNLOAD_SERVICE) Initializing a new request object Starting the request – DownloadManager#enqueue() Checking the process state – DownloadManager#query() Finishing the process – BroadcastReceiver for signalling events – Cursor for reading the data Resources S. Komatineni, D. MacLean – Pro Android 4, Apress, 2012 R. Meier – Professional Android 4 Application Development, Wiley, 2012 P. Pocatilu, Programarea dispozitivelor mobile, Editura ASE, 2012 P. Pocatilu, I. Ivan ș.a. – Programarea aplicațiilor Android, Editura, ASE, 2015 http://developer.android.com Mobile Devices and Applications Unit 6 – SOAP & REST Services / XML & JSON Web SOAP services Services REST services Summary Web JSON and XML Service Processing Results WEB SERVICES SOAP Services kSOAP2 library Classes: Methods: SoapObject, object used for setting addProperty, add a parameter for the method’s parameters; the service method; SoapSerializationEnvelope, object setOutputSoapObject, sets the used for enveloping the connection object in which the response will attributes be written; HttpTransportSE, object used for call, makes a call to a specified making the connection to the web service method service; WSDL is an XML format for describing network services as a set of endpoints; The endpoints are operating on messages; Service The operations and messages are described abstractly; description A defined endpoint represents a set of messages and operations bound to a concrete network - WSDL protocol and message format; Example: http://www.w3schools.com/xml/tempconvert.as mx?WSDL Soap Request POST /xml/tempconvert.asmx HTTP/1.1 Host: www.w3schools.com Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://www.w3schools.com/xml/FahrenheitToCelsius" string Soap Response HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length string Actions are implemented by using the HTTP protocol List of possible GET, POST, PUT, operations: DELETE, etc. Web REST JSON (JavaScript Object Notation) Results: XML (eXtended Markup Language) XML AND JSON FILES Elements seen as nodes; A root node representing the element or a collection of elements; XML Files Attributes with their values seen as child nodes of an element; Used to store data and data structure; element value or other elements … XML File Example XML Files < book id="19223"> S. Hashimi S. Komatineni R. Meier D. MacLean Professional Android Application Pro Android 3 Development Apress Wiley> 2011 2009 0-321-15040-6 1-72-11-2222 336 500 PARSING XML AND JSON FILES XML Files SAX (Simple API for XML) – org.xml.sax – SAXParserFactory, SAXParser – Sequential reading of a XML document – Inverse order events XML Pull – org.xmlpull.v1 – XmlPullParserFactory, XmlPullParser – Sequential reading of a XML document – Directly treated events DOM – org.w3c.dom – DocumentBuilderFactory, DocumentBuilder, Document – An hierarchical structure is generated and loaded in memory – The nodes are managed in lists of nodes SAXParserFactory – Used for creating SAXParser objects SAXParser – Used for processing the XML files XMLReader – Used to read the file SAX – parse() Methods: getParser(), getSchema(), getProperty() DefaultHandler: receives callbacks when notifications are triggered Methods called when processing the XML file startElement() Called when start reading an element; endElement() Called when the element was completely read; DefaultHandler characters() Called when a character sequence appears; Is hoocked up to the XmlReader setContentHandler() Returns the result SAXParserFactory fact = SAXParserFactory.newInstance(); SAXParser xmlParser = fact.newSAXParser(); XMLReader xmlReader = xmlParser.getXMLReader(); SAX Example SAXHandler handler = new SAXHandler(); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(streamIn)); XML Pull XmlPullParser interface Initialization – Resources#getXml() res/xml – Xml.newPullParser() – XmlPullParserFactory#newPullParser() XmlPullParserFactory – XmlPullParserFactory.newInstance() Needs an associated input stream (InputStream) – setInput() next() – parsing the document Events: – Types: START_TAG/END_TAG, TEXT, START_DOCUMENT/END_DOCUMENT – getEventType() XmlPullParser nextToken() – advances with the reading process getName() – gets the tag name getText() – gets the content of a tag getAttributeCount() – gets the attribute number getAttributeValue() – gets the attribute value XmlPullParser Example static ArrayList processXML_Pull(InputStream isXML) { ArrayList list = new ArrayList(); Book book = null; int event; String text = null; try { // creates the parser XmlPullParser xmlParser = Xml.newPullParser(); xmlParser.setInput(isXML, null); event = xmlParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name = xmlParser.getName(); //the switch from the next slide event = xmlParser.next(); } } catch (Exception e) {e.printStackTrace(); } return list;} XmlPullParser Example switch (event) { case XmlPullParser.START_TAG: if (name.equals(“book")) { book = new Book(); book.setId(xmlParser.getAttributeValue(null,“id")); } break; case XmlPullParser.TEXT: text = xmlParser.getText(); break; case XmlPullParser.END_TAG: if (name.equals("title")) { book.setTitle(text); } if (name.equals(“book")) { list.add(book); } break; } Interfaces Node Element (impl. Node) NodeList item(position) DOM DocumentBuilder class parse() method InputStream Document (impl. Node) class DOM – Document getElementsByTagName() – NodeList – Element getAttribute() – Node getTextContent() DOM Example DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); //gets the input stream InputStream is = getResources().openRawResource(R.raw.biblx); //create the document Document docXml = docBuilder.parse(is); if (docXml != null) { //gets the list of nodes NodeList books = docXml.getElementsByTagName(“book"); //read each node from the list for (int i = 0; i < books.getLength(); i++) { //book processing Node nodCrt = books.item(i); if (nodCrt.getNodeType() == Node.ELEMENT_NODE) { Element obj= (Element) nodCrt; Book book = new Book(); book.id = obj.getAttribute(“id"); book.title = obj.getElementsByTagName("title"). item(0).getTextContent(); book.isbn = obj.getElementsByTagName("isbn"). item(0).getTextContent(); } } } JSON Files Retrofit library developed by Org.json Square Open Source an independent data exchange format; designed for representing simple structures; limited to text and numeric values; JSON Files { } – describes the object [ ] – represents a list of values "property" : "value" JSON Files { “library": { “book": [ { "-id": "19222", "author": { "name": "R. Meier" }, "title": " Professional Android Application Development ", “publisher": "wiley", "year": "2009", "isbn": "1-72-11-2222", "pages": "500" }, { "-id": "19223", "author": { "name": [ "S. Hashimi", " S. Komatineni", " D. MacLean " ] }, "title": "Pro Android 3", “publisher": "Apress", “year": "2011", "isbn": "0-321-15040-6", "pages": "336" } ] } } JSON Files org.json JSONObject – getType(): getString(), getBoolean(), getInt() etc. – getJSONArray() – getJSONObject() JSONArray – length() – getTIP(index) JSON Files Example JSONObject jObject = new JSONObject(stringJson); JSONObject joLibrary = jObject.getJSONObject(“library"); JSONArray jaBooks = joLibrary.getJSONArray(“book"); for (int i = 0; i < jaBooks.length(); i++) { Book book = new Book(); //book processing JSONObject joBook = jaBooks.getJSONObject(i); String title = joBook.getString("title"); book.setTitle(title); int year = joBook.getInt(“year"); String id = joBook.getString("-id"); …. } POJO objects (Plain Old Java Object) – the model class Interface for managing the URL’s – the service class Retrofit RestAdapter – the rest client class By default Retrofit uses Gson but other converters can be also used; POJO class http://www.jsonschema2pojo.org http://pojo.sodhanalibrary.com Used for creating the Java class associated with the JSON or XML objects Retrofit Interface Manages the URLs to each the service class must connect; Manages the URL calls like GET, PUT, etc. @GET("/data/2.5/weather") public void getWeather(@Query("q") String city, @Query("APPID") String apikey, Callback response); RestAdapter RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(API).build(); RestInterface restInterface = restAdapter.create(RestInterface.class ); Resources S. Komatineni, D. MacLean – Pro Android 4, Apress, 2012 R. Meier – Professional Android 4 Application Development, Wiley, 2012 P. Pocatilu, Programarea dispozitivelor mobile, Editura ASE, 2012 P. Pocatilu, I. Ivan ș.a. – Programarea aplicațiilor Android, Editura, ASE, 2015 http://developer.android.com Mobile Devices and Unit 7 – Persistent Applications storage Persistent storage Agenda Application container Shared Preferences files Internal and External files SQLite databases Content Providers APPLICATION CONTAINER PERSISTENT STORAGE Resources Directories res/raw – any type of files saved in the raw format res/xml – XML compiled files APPLICATION Uses a resources identifier in order to CONTAINER get access Assets directory Processing data flow Used for grouping directories and files getResources() -> Resources – Gets files inside res/raw openRawResource() -> APPLICATION InputStream CONTAINER – Gets files from res/xml getXml() -> XmlPullParser APPLICATION CONTAINER AssetManager – provides access to an application’s raw asset files; – getAssets() (Context class) – open(file_name) -> InputStream – list(path) Returns a String[] of all assets at the given path Files list – openXmlResourceParser(file_name) Retrieve a parser to an compiled XML file APPLICATION CONTAINER App’s private area – /data/data/app_package App’s private external storage area – /ext_dir/Android/data/app_package Subdirectories – cache – databases – shared_prefs – files SHARED PREFERENCES Properties files Android Preferences What can and can’t do Open mode Storing non-primitive values PROPERTIES FILES Uses the SharedPreferences Interface Persistent storage of key-value pair Data types allowed – boolean – int – float – long – String getType() methods like getBoolean(), getInt() etc. PROPERTIES FILES At application level – getSharedPreferences(String file_name, int operating_mode) – An application can have multiple preference files At activity level – getPreferences(int mode) – A single properties file per application activity From PreferenceManager class – getDefaultSharedPreferences(context) – The default file for storing preferences in the current context Returns an object of type – SharedPreferences Mode – Activity.MODE_PRIVATE - default PROPERTIES FILES SharedPreferences.Editor Initialization – SharedPreferences#edit() Writing – putType() methods Deleting preferences – remove() Delete all preferences – clear() Saving changes – commit() PROPERTIES FILES SharedPreferences settings = getSharedPreferences("settings", Activity.MODE_PRIVATE); SharedPreferences.Editor editorProp = settings.edit(); editorProp.putBoolean("title", false); editorProp.putBoolean(“help", true); editorProp.putInt("max", 5); editorProp.commit(); PROPERTIES FILES SharedPreferences settings = getSharedPreferences("settings", Activity.MODE_PRIVATE); boolean fTitle = settings.getBoolean("title", false); boolean fHelp = settings.getBoolean(“help", true); int nMax = settings.getInt("max", 5); Activities for saving preferences Classes – PreferenceActivity – PreferenceFragment – PreferenceScreen – PreferenceCategory Preferences Dialog windows – EditTextPreference – ListPreference – MultiSelectListPreference Controls – CheckBoxPreference – SwitchPreference Activities for saving preferences PreferenceActivity PreferenceFragment XML files associated with content – addPreferencesFromResource(R.xml.preferences); Activities for saving preferences Activities for saving preferences Activities for saving preferences SharedPreferences preferinte = PreferenceManager.getDefaultSharedPreferences(this); boolean modNoapte = preferinte.getBoolean("modNoapte", false); String user = preferinte.getString("utilizator", "neconectat"); String [] setariFonturi = new String; preferinte.getStringSet("listaFont", new HashSet()).toArray(setariFonturi); FILES Can be used as internal persistent storage external option The internal files are implicitly FILES available just from the application’s context The files are deleted once the application is uninstalled Environment class External storage access: – isExternalStorageRemovable() External storage state – getExternalStorageState() MEDIA_MOUNTED MEDIA_MOUNTED_READ_ONLY MEDIA_UNMOUNTED MEDIA_REMOVED Special directories Environment class Root directory – getRootDirectory() User directory – getDataDirectory() Cache directory – getDownloadCacheDirectory() External directory – getExternalStorageDirectory() Special directories Public directory for external storage – getExternalStoragePublicDirectory(type) type (static members) – DIRECTORY_PICTURES – DIRECTORY_MUSIC – DIRECTORY_DOWNLOADS – DIRECTORY_DCIM – DIRECTORY_RINGTONES – DIRECTORY_ALARMS Special directories Activity class (Context) External directory for the application – getExternalFilesDir() External directories for the app (API 19) – getExtenalFilesDirs() Data directory – getFilesDir() Internal cache directory – getCacheDir() External cache directory – getExternalCacheDir() File class File and directory based operations Setting properties for each file Change or move the objects Can create a directory or a file Can read the content of a directory or a file InputStream and OutputStream Abstract classes Used for data stream operations FileInputStream and FileOutputStream Files Reading and writing data bytes streams; FileReader and FileWriter Reading and writing char sequences; Files InputStreamReader and OutputStreamWriter – Char based streams – Both extends the abstract classes Reader, respectively Writer – Associated to objects of type InputStream, respectively OutputStream; BufferedReader and BufferedWriter – Associated with objects of type Reader, respectively Writer – Are using buffers in order to implement input/output operations Files Context class: FileInputStream openFileInput(String fileName) FileOutputStream openFileOutput(String fileName, int mode) – Context.MODE_PRIVATE/ Context.MODE_APPEND boolean deleteFile(String fileName) String[] fileList() File getDir(String dirName, int mode) Internal Storage Example private void writeInternalStorage() throws private void readInternalStorage() IOException { throws IOException { FileInputStream inputStream = String message = "These are sample contents openFileInput("sample.txt"); written to internal file"; InputStreamReader streamReader FileOutputStream outputStream = = new openFileOutput("sample.txt", InputStreamReader(inputStream); Context.MODE_PRIVATE); BufferedReader reader = new outputStream.write(message.getBytes()); BufferedReader(streamReader); outputStream.close(); String message = reader.readLine(); Toast.makeText(this, "Write Successful", Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } Toast.LENGTH_LONG).show(); } External files android.permission.WRITE_EXTERNAL_STORAGE Checking the availability of the external storage Checking the permission for accessing and working with the external storage External Storage Example private void writeExternalStorage() throws private void readExternalStorage() throws IOException { IOException { String message = "These are the contents which would be written to external file"; File file = new File(Environment.getExternalStorageDirectory(), File file = new "sample.txt"); File(Environment.getExternalStorageDirectory(), FileInputStream inputStream = new "sample.txt"); FileInputStream(file); if (!file.exists()) { InputStreamReader streamReader = new file.createNewFile(); InputStreamReader(inputStream); } BufferedReader bufferedReader = new BufferedReader(streamReader); FileOutputStream outputStream = new FileOutputStream(file); String message = bufferedReader.readLine(); outputStream.write(message.getBytes()); outputStream.close(); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); Toast.makeText(this, "Write Successful", Toast.LENGTH_LONG).show(); } } Resources S. Komatineni, D. MacLean – Pro Android 4, Apress, 2012 R. Meier – Professional Android 4 Application Development, Wiley, 2012 P. Pocatilu, Programarea dispozitivelor mobile, Editura ASE, 2012 P. Pocatilu, I. Ivan ș.a. – Programarea aplicațiilor Android, Editura, ASE, 2015 http://developer.android.com Mobile Devices and Applications Unit 10 – Persistent storage Summary Persistent data storage – Databases – SQLite – Application container – Property files – External files Content providers DATA STORAGE Storage Options – Shared preferences – primitive data – Internal storage – private Android data Persistence – External storage – large data sets, not private – SQLite databases – structured data – Remote storage Shared preferences Primitive values: boolean, float, int, long and string Data persist across user sessions SharedPreferences objects getSharedPreferences() getPreferences() edit() – to get an editor put and get like methods commit to save data Internal storage save files directly on the device's internal storage, private by default; The files are deleted after uninstalling the application openFileOutput() using a FileOutputStream object Write bytes into the file; openFileInput() using a FileInputStream object Read bytes from the file; Context modes: PRIVATE, APPEND, WORLD_READABLE, WORLD_WRITEABLE Also used for storing cache files with getCacheDir() External storage An external storage represents a shared space such as an SD card, removable storage media, or an internal storage; Needs access to external storage declared in manifest file – Check media availability – getExternalStorageState() Get the location for saving files: – getExternalStoragePublicDirectory() SQLITE STORING DATA IN DATABASES Android provides full support for SQLite Relational databases android.database.sqlite package Database Uses SQLiteOpenHelper for creating a database CRUD operations from SQLiteDatabase object SQLite Definition SQLite Supported data types – INTEGER – REAL – TEXT – BLOB – NULL Restrictions: – RIGHT OUTER JOIN and FULL OUTER JOIN not implemented; – Not all ALTER TABLE options are implemented, such as: DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT – FOR EACH STATEMENT trigger is not supported; – VIEWs are READ ONLY OBJECTS Limitations: – max. length of a string or BLOB: 231 − 1 = 2.147.483.647 𝑏𝑦𝑡𝑒𝑠 – max. no. of columns / tables in a join / arguments in a function – max. no. of rows in a table: 264 – max. database size: 231 − 2 pages / with 65536 bytes /page => 140 TB / 140.000 GB SQLiteDatabase Create/Open Database – SQLiteDatabase class openDatabase() static method openOrCreateDatabase() static method – Context class openOrCreateDatabase() – SQLiteOpenHelper class getReadableDatabase() getWritableDatabase() Close Database – close() SQLite in Android App Example SQLiteDatabase db = SQLiteDatabase.openDatabase( "pim.db", null); //or SQLiteDatabase db = openOrCreateDatabase("pim.db", Context.MODE_PRIVATE, null); //… db.close(); SQLiteDatabase SQL commands: – execSQL() – doesn’t return any value – rawQuery() – return values (Cursor) Specialized methods – query() – insert() – update() – delete() Database selection query() method – Table name – Selected columns String[] – Selection criteria (WHERE) String – Values associated with the each parameter from the selection criteria String[] Database selection – Grouping (GROUP BY) String – Grouping condition (HAVING) String [] – Sorting (ORDER BY) String Return type: – Cursor Selection example Cursor cursor = db.query( “students", null,//all columns null,//without selection null, null,//without grouping null, null//without sorting ); Selection example Cursor cursor = db.query( "students", new String[] {"ids", "name", "faculty" } "faculty=?", new String[] {"CSIE"}, null,//without grouping null, "ids ASC" ); Database insertion ContentValues class – put("key", value); SQLiteDatabase#insert() method – table name – null – optional, for inserting null into an explicit column – ContentValues object Result: – Long – row ID of the newly inserted column or -1 Insertion example ContentValues value = new ContentValues(); value.put(“ids", 1200); value.put("name", “Popescu"); long result = bd.insert("students" , null, value) Database update update() method – table name – ContentValues object with the new values – WHERE clause, null value will update all rows – WHERE args, string values replacing the ? from the WHERE clause – returns an int representing the numbers of rows affected Update example ContentValues value = new ContentValues(); value.put("name", "new student"); int rez; rez =