Survey							
                            
		                
		                * Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Mobile Phone Programming Android Platform Basics Dr. Péter Ekler [email protected] Agenda  Android platform introduction  Android environment  Android application components  Android Activity life cycle  Android Development Environment  Android Emulator  First 2 Android project Mobile Phone Programming Quick quizzes during the course Web interface: http://avalon.aut.bme.hu/~tyrael/votes/ http://avalon.aut.bme.hu/~tyrael/votes/ index2.php Android application (QR): http://avalon.aut.bme.hu/~tyrael/ votes/download/AmorgVote.apk 3 Mobile Phone Programming Question  In case of try-catch-finally, will the finally block run if there is a return statement at the end of the try block? try { System.out.println("try"); return; A. Yes B. No C. Do not know D. Depends from compiler } catch(Exception e) { e.printStackTrace(); } finally { System.out.println("finally"); } http://avalon.aut.bme.hu/~tyrael/votes/ 4 Mobile Phone Programming First steps of mobile application development   5 What type of devices do we need to support?  Mobile phones  Tablets  Others… What type of platforms do we need to support?  Android  iOS  Windows Phone  BlackBerry  Java ME (feature phone)  Etc.  Requirement clarification  User Interface requirements (etc. via mockups) Mobile Phone Programming Why Android? (2013 February) Source: http://www.onbile.com/info/usandroid-market-share/ 6 Mobile Phone Programming Typical requirements and possibilities 1/2 7  How should the application behave?  What are the requirements related to UI? (default UI, unique UI, similar than on other platforms..)  What type of persistence layer and data storage do we need? (content, gallery, sqlite, file, security…)  What type of communication technique do we need? (telco, cloud, server, peer-to-peer, special, social network integration, push, security..) Mobile Phone Programming Typical requirements and possibilities 2/2 8  Do we need multimedia or location services?  Other special requirements? (like native support)  How should we publish the application, are there special requirements? (in-app payment, play store, admob, etc.)  What kind of best practices, external libraries or previous implementations can/should we use? Mobile Phone Programming The capabilities of the Android platform 1/2 9  Reach application behavior capabilities (background services, lazy connected components, easy to reach system services)  Full JavaSE class library + reach Java API for Android functions like network handling, telco, etc.  Reach UI widget library, easy to develop custom widgets, styles and themes  Dynamic UI behavior, animations, reach resource capabilities Mobile Phone Programming The capabilities of the Android platform 2/2  Secure file management, SQLite and easy-touse key-value storage  Linux based; native development is supported  Rich external library collection (Java and native):  10 Always check first! – GitHub, Google Code, etc.  Rich Google Services for publishing, advertising and for development  … there are always new components and tools! Mobile Phone Programming Application behavior    11 When the application starts and activates  Manual start (clicking on an icon)  Activation by some external event (incoming call, battery status, boot ready)  Services and contents provided by the application Application running type  Foreground running  Background services How do we handle these on Android? Special needs  Widget support  Live wallpaper Android application components Mobile Phone Programming INTRODUCING THE ANDROID PLATFORM Origin of Android  13 Android is one of the most popular mobile operating systems of present days  It become a brand by intent (TV spots, ads, etc.)  Google stands behind the platform  Android offers the picture of a well functioning OS  Revolutionized the picture of mobile operating systems Mobile Phone Programming Android devices 14  Mobile phone and tablet manufacturers  Car navigation and multimedia systems  Industrial solutions  Android has potential on many other fields:  Small and large screen  Limited resource capabilities (e.g. battery)  Touch screen support  Android@Home Mobile Phone Programming What is Android? 15  An operating system not only for mobile phones!  The collection of all devices that support Android  It is in the hands of Goolge  2005: Google buys a company, called: Android Incorporated  2007: The first news have been leaked that Google will enter into the mobile market  November 5, 2007: The newly formed Open Handset Alliance has introduced the Android platform  End of 2008: The HTC G1 (Dev Phone) was available on the market by T-Mobile Mobile Phone Programming Open Handset Alliance  Android is not only Google’s development  More than 50 member companies  11 manufacturer (HTC, LG, Motorola, Samsung, Asus, Garmin, Huawei, Sony Ericsson, Ericsson, Toshiba, Acer)  13 semiconductor manufacturer (not at least Intel, Marvell, nVidia, Broadcom, SiRF, ARM and Atheros)  10 operator (example T-Mobile and Vodafone)  12 software company (Google, eBay)  7 other corporation  Members are changing frequently  Android:  16 Product of huge knowledge and lot of work Mobile Phone Programming What was the purpose of Google?  Open source, flexibility, a system that is easy to develop further, easy to develop external application  Applications can reach system services easily  Monolithic Linux kernel  Apache licence and open soruce licence (etc. org.apache packages) 17 Mobile Phone Programming What is the propose of the following function from the AlarmClock application? private void saveAlarm() { final String alert = mAlarmPref.getAlertString(); Alarms.setAlarm(this, mId, mEnabled, mHour, mMinutes, mRepeatPref.getDaysOfWeek(), mVibratePref.isChecked(), mLabel.getText(), alert); if (mEnabled) { popAlarmSetToast(this, mHour, mMinutes, mRepeatPref.getDaysOfWeek()); } } 18 A. Restart phone after specific time B. Share alarm in Google+ C. Save alarm and exit from AlarmClock D. Save alarm and display time to left till the alarm Mobile Phone Programming Android versions  Developers must follow version changes  Could be significant differences between versions  Google pursue backward compatibility, but there are deep gaps (v 3.0)  Before developing, it's neccesary to choose the minimum supported version well  Version 19 codename: some candy  Mobile Phone Programming Android versions 20  Android 1.0 – 2008. October  Android 1.1 – 2009. February  Android 1.5 (Cupcake) – 2009. April  Android 1.6 (Donut) – 2009. September  Android 2.0 and 2.1 (Eclair) – 2009. October  Android 2.2 (Froyo) – 2010. May  Android 2.3 (Gingerbread) – 2010. December  Android 3.0-3.2 (Honeycomb) – 2011 January-July  Android 4.0 (Ice Cream Sandwich) – 2011. October  Android 4.1 (Jelly Bean) – 2012. July  Android 4.2 (Jelly Bean) – 2012. Nobember  Android 4.3 (Jelly Bean)  Android 4.4 (Kit Kat) Mobile Phone Programming ANDROID PLATFORM STRUCTURE Structure of Android platform 22 Mobile Phone Programming Platform build-up 1/3 23  The structure of the platform is simple and clean  The red part is the Linux kernel, which contains:  Drivers of the hardware components  These parts are created by the device manufacturers, because they know best „what is in the box”  Memory management, process scheduling, low energy consumption performance management Mobile Phone Programming Platform build-up 2/3 24  The green parts are program libraries/services which running on the Linux kernel, like: libc, SSL, SQLite, etc. These are implemented in C/C++.  The Dalvik virtual machine in the yellow part is based on these parts.  Not compatible with Sun’s virtual machine  Totally different instruction set  It runs different binary programs  After compiling, Java programs are not compiled into .class files, but to a Dalvik Executable format, which extension is .dex. It is usually smaller then .class files size.  Java is only the programmig language! Mobile Phone Programming Platform build-up 3/3  Ont the blue parts are only Java source code  Java source is runned by the virtual machine. This is the essence of Android:  25  A visible and touchable operating system  Running programs The virtual machine can hide the whole Linux file system, and users can see only the file system provided by Android Runtime Mobile Phone Programming Managed code 26  Managed code runs on a virtual machine (Dalvik)  It makes the application run secure  An application can't ruin the whole system  Memory management is happening with a garbage collector  But! Be careful to create „good” source code Mobile Phone Programming What is not true about Android platform? A. Linux based system B. Each standard application runs on a virtual machine instance C. Built-in applications (e.g. phone, contacts) are part of the operating system D. Supports only managed code http://avalon.aut.bme.hu/~tyrael/votes/ http://avalon.aut.bme.hu/~tyrael/votes/index2.php 27 Mobile Phone Programming ANDROID ENVIRONMENT Google Play (earlier: Android Market) 29  https://play.google.com/store  Available since 22. October, 2008.  Application store for Android devices  The Play Store application is not open source!  Pre-installed on all major Android device  One of the biggest application store nowadays Mobile Phone Programming Google Play capabilities 30  From 2010 December, the revenue arrives to the developer after 15 minutes, earlier it was 24/48 hours  From 2011 February, the Play Store is available on the Web as well  From 2011 May, there are new categories in the Store:  Top Grossing  Top Developers  Trending  Editors Recommendations  Goal: Increase applications visibility Mobile Phone Programming Google Play Services 31  Android Licensing Service  In-app Billing  Google authentication  Google+ integration Mobile Phone Programming Installing Android Applications  Applications are distributed in .apk files  Installation is managed via the PackageManagerService  PackageManager handles direct .apk installation as well  Applications can be installed from device memory, e-mail attachment, web address, etc. 32 Mobile Phone Programming The .apk file  It is close to Java .jar files, but has major differences  Compressed file with the following typical content:  META-INF folder    CERT.RSA: certificate MANIFEST.MF: meta information CERT.SF: resource list and SHA1 prints Signature-Version: 1.0 Created-By: 1.0 (Android) SHA1-Digest-Manifest: wxqnEAI0UA5nO5QJ8CGMwjkGGWE= ... Name: res/layout/exchange_component_back_bottom.xml SHA1-Digest: eACjMjESj7Zkf0cBFTZ0nqWrt7w= ... Name: res/drawable-hdpi/icon.png SHA1-Digest: DGEqylP8W0n0iV/ZzBx3MW0WGCA= 33  Res folder: resources  AndroidManifest.xml (meta): name, version, permissions, components, etc.  classes.dex: Dalvik binary  resources.arsc Mobile Phone Programming ANDROID PROJECT SOURCE ELEMENTS Software Development Tools on Android    35 Android SDK (Software Development Kit):  Development tools, documentation, all Android version  Emulator management (AVD Manager)  Always up to date  Java, reach API  Eclipse plugin, .apk generation Android NDK (Native Development Kit):  Enables to compile native code  C++  Eclipse plugin Android ADK (Accessory Development Kit):  Support for designing accessories like: docking station, health devices, etc.)  Android Open Accessory protocol (USB and Bluetooth) Mobile Phone Programming Let’s see some examples  Let’s exam the structure of the Android SDK!  Look for Android source code and check the structure of it! 36 Mobile Phone Programming Installing the Development Environment  ADT Bundle (download&install)  Eclipse  37 + Android SDK http://developer.android.com/sdk/index.html Mobile Phone Programming The Capabilities of the Development Tool 38  On Device Debugging  Port forwarding  Instant screenshot tool  Thread, heap and other memory information  LogCat  Process monitoring  Mobile radio status  Call and SMS handling  Location based services  Etc. Mobile Phone Programming Emulator configuration 39  For launching the emulator an AVD (Android Virtual Device) must be configured  AVDs can be created via the AVD Manager application that is part of the SDK  AVD properties:  Name  Android platform version  SD card size  Skin  Screen properties Mobile Phone Programming Emulator 40  Emulates the whole Android OS (slow…)  Built-in applications are available  Ctrl+F11 (screen orientation)  For Mac: Fn+Ctrl+F11  Use Intel Acceleration (HAX) Mobile Phone Programming Use the Emulator from console  List the connected devices/emulators:   Shell:     Open a telnet client  o localhost 5554 SMS sending to the emulator: gsm call <caller number> Redirect log to file:  41 sms send <sender number> <message> Voice call to the emulator:   adb shell Connect via telnet:   adb devices adb logcat -f <filename> Mobile Phone Programming Debug through DDMS  42 On-device debug is fully supported  Proper USB driver is required  USB debugging must be enabled on the device  Every application has a separate process  Every process has a Virtual Machine instance  Each VM opens a port, to which the debugger can connect (8600, 8601, etc.)  There is also a „base port” (8700), that monitors all VM port and each VM can be observed at the same time Mobile Phone Programming Coffee Break 43 Mobile Phone Programming Android project elements 44  Package: unique identifier  Java source  Resources  Layout (XML)  Themes and styles (XML)  Text elements (XML)  Animations and other dynamic graphics (XML)  Images, sound, video, etc.  R.java (generated automatically)  AndroidManifest.xml  External libraries (.jar or other projects) Mobile Phone Programming Manifest file  Application descriptor  Meta information  Pre-defined component list  45 Can be modified dynamically from code  XML format  The system checks the descriptors and components in the Manifest  Other meta information like minimal Android version, permissions, etc.  It is checked by the system before installation Mobile Phone Programming Manifest content 46  Java package – unique identifier  Permissions (e.g.: Internet access, Location information, Phone calls, etc.)  Minimum API level  Hardware and software requirements (e.g. necessary camera, etc.)  External APIs (e.g.: Google Maps API) Mobile Phone Programming Manifest example 1/2 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/android" package="hu.bute.daai.amorg.examples" Unique package name (identifier) android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" /> <application Minimum supported version android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity …>…</activity> </application> Application icon and label </manifest> 47 Mobile Phone Programming 47 Manifest example2/2 <?xml version="1.0" encoding="utf-8"?> <manifest …/> Activity class and title … <application …> <activity android:name=".AndHelloWorldActivity" android:label="@string/app_name"> <intent-filter> Application entry point <action android:name= "android.intent.action.MAIN"/> <category android:name= "android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> Appears in the applications list </manifest> 48 Mobile Phone Programming 48 Manifest attributes and tags 49  android:icon: application icon  android:name: Application name with package name  android:label: Application title  List of components:  <activity>: Activity  <service>: Service  <provider>: Content provider  <receiver>: Broadcast receiver  The Activities, Services and ContentProviders that are not present in the Manifest, are not visible for the system  However BroadcastReceivers can be defined dynamically from code: registerReceiver() Mobile Phone Programming ANDROID APPLICATION COMPONENTS Android Application Components  51 An Android application stands from one or more components:  Activity  Service  Content Provider  Broadcast Receiver Mobile Phone Programming Component Activation 52  Each component has special role  Each component can be activated independently  Even another application can activate a component Mobile Phone Programming Activity  Special view with own UI  Example:  Todo application  3 Activityies: ToDo list, new ToDo form, ToDo details view  Independent Activities, but they have an important role in the whole application  Another application can start the Activity, e.g.:   53 Camera application can start the new Todo activity with the instant camera photo that will be stored with the new Todo element Extends from the android.app.Activity class Mobile Phone Programming Service  Service represents a background task in the application  Does not have specific UI  For example: a download process, while we are using the application in the foreground  Other components can start or bind to it  Extends from the android.app.Service class 54 Mobile Phone Programming ContentProvider 55  Main objective of ContentProvider is to share a data source with other components  The data can be stored in different locations: SQLite, file, SharedPreferences, remote server, etc.  Other applications can work on the same data by using ContentProvider  For example: CallLog ContentProvider  Extends from the android.content.ContentProvider class Mobile Phone Programming BroadcastReceiver  BroadcastReceiver activates by different system or application events  For example: screen turns off, low battery, incoming call, photo ready, etc.  An application can also fire custom broadcast event, for example a Service broadcasts that the download is ready  Does not have specific user interface, typically it awakes other components, or display a notification  Extends from the android.content.BroadcastReceiver class 56 Mobile Phone Programming ACTIVITY COMPONENT Activity start 58  No main() method!  The Android system initiates code in an Activity instance by invoking specific callback methods  During the life of an activity, the system calls a core set of lifecycle methods in a sequence similar to a step pyramid Mobile Phone Programming Activity start - notice  After the system calls onCreate(), it quickly calls onStart(), which is quickly followed by onResume()  The system quickly moves between states by calling the next lifecycle callback method  The Activity never resides in the Created or Started state 59 Mobile Phone Programming Activity life cycle Entire Visible  Life cycle functions are called during state change  Life cycle functions can be overwritten   60 It is necessary to call bas Foreground class function, e.g.: super.onCreate(); Huge responsibility on the developer! Mobile Phone Programming Activity skeleton 1/2 public class ExampleActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Activity is being created } @Override protected void onStart() { super.onStart(); // Activity becomes visible } @Override protected void onResume() { super.onResume(); // Activity is visible and has focus } 61 Mobile Phone Programming Activity skeleton 2/2 @Override protected void onPause() { super.onPause(); // Another Activity gets focus // This Activity will go into pause state } @Override protected void onStop() { super.onStop(); // The Activity is not visible // The Activity is in stopped state } @Override protected void onDestroy() { super.onDestroy(); // The Activity will destroy } } 62 Mobile Phone Programming Ensure correct behavior  63 Not necessary to implement all life-cycle methods, but implement those that ensure the correct behavior in your application:  Does not crash if the user receives a phone call or switches to another app while using your app.  Does not consume valuable system resources when the user is not actively using it.  Does not lose the user's progress if they leave your app and return to it at a later time.  Does not crash or lose the user's progress when the screen rotates between landscape and portrait orientation. Mobile Phone Programming Launcher Activity  How/where do we define which activity will launched when the user clicks on the icon?  In AndroidManifest.xml <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name= "android.intent.category.LAUNCHER" /> </intent-filter> Otherwise the </activity> application will not be visible 64 Mobile Phone Programming First Android application Base class public class HelloAndroid extends Activity { /** Called when the activity is first created. */ Call base class implementation @Override first public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hello AIT!"); setContentView(tv); } Display } a TextView 65 Mobile Phone Programming Android HelloWorld with XML UI 1/2 Hello Android XML (layout/main.xml): <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/tvHello" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> 66 Mobile Phone Programming Unique ID Android HelloWorld with XML UI 2/2 package hu.bute.daai.amorg.examples; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloWorldActivity extends Activity { /** Called when the activity is first created. */ Never forget to call super class implementation in every life cycle method! @Override public void onCreate(Bundle savedInstanceState) { XML based layout super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView myTextView = (TextView)findViewById(R.id.tvHello); myTextView.append("\n--MODIFIED--"); } } 67 Find and get reference on for the proper UI component Mobile Phone Programming Simple event processing public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView myTextView = Because we use it from an anonim class (TextView)findViewById(R.id.tvHello); myTextView.append("\n--MODIFIED--"); myTextView.setOnClickListener(new OnClickListener() { public void onClick(View v) { myTextView.append("\n--CLICKED--"); } }); } Simple touch event handling 68 Mobile Phone Programming