Está en la página 1de 40

Quick Time For Android En.

No: 100430723009 Seminar Report On QUICK TIME FOR ANDROID DESIGNED AND IMPLEMENTED BY: Mr. PINAL K SHAH (100430723009) Semester: III, M.E. (Information Technology) GUIDED BY: Prof. Preeti Dave EC Engineering Department SHANTILAL SHAH ENGINEERING COLLEGE BHAVNAGAR Gujarat Technological University, A hmadabad S. S. College, Bhavnagar Pinal Shah 1

Quick Time For Android En. No: 100430723009 CERTIFICATE This is to certify that the work presented in the seminar entitled Quick Time for Android Has been carried out by Mr. Pinal Shah Enrollment No.:100430723009 Under my guidance as a partial fulfillment of requirements to Award ME Information Technology By Gujarat Technological University, Ahmadabad Date: Prof. Preeti Dave Asst. Prof. E.C. Dept. S.S.E.C. Dr. J.S. Shah Prof. & Head Computer Engg. Dept. L.D.C.E Prof. Kalpesh Patel/ Harkishan Jethva Asst. Prof. Computer Engg. Dep L.D.C.E S. S. College, Bhavnagar Pinal Shah 2

Quick Time For Android En. No: 100430723009 Acknowledgement I wish to thank all who helped me in this seminar work. I thank my Head of the d epartment S.B Parmar and Dr. J. S Shah sir for helping me in sorting out the pro cedural work and his guidance. I also thank Prof. Kalpesh Patel, Prof Harkishan Jethva and Prof. Preeti Dave for their kind support and guidance during seminar preparation. Books, Internet and computing facilities have been a treasure in de veloping this seminar, so words of gratitude for the staff of library and comput er department of Shantilal Shah Engineering College, Bhavnagar S. S. College, Bhavnagar Pinal Shah 3

Quick Time For Android En. No: 100430723009 Index Chapter 1 1.1 1.2 1.3 1.4 Introduction Abstract Purpose (Why Android?) Goal Overview of Android 6 7 8 8 Chapter 2 2.1 2.2 2.3 2.4 2.5 2.6 What Is Android? What is Android? Android Landscape Different version comparisons Android Archite cture Android vs. IPhone Drawback of Android Platform 11 13 14 16 17 18 Chapter 3 3.1 3.2 3.3 3.4 3.5 Android Application Basics Activity, View, Event, Intent Application Life Cycle Setting Development Environ ment Develop Hello World Application Demo of another Application 21 22 23 26 31 Appendix Source Codes A Appendix Source Codes B Appendix Source Codes C Referenc es 36 37 38 39 S. S. College, Bhavnagar Pinal Shah 4

Quick Time For Android En. No: 100430723009 Chapter 1 Introduction 1.1 Abstract 1.2 Purpose (Why Android?) 1.3 Goal 1.4 Overview of Android S. S. College, Bhavnagar Pinal Shah 5

Quick Time For Android En. No: 100430723009 1.1 Abstract Android is a software stack for mobile devices that includes an operating system , middleware and key applications. Android is a software platform and operating system for mobile devices based on the Linux operating system and developed by G oogle and the Open Handset Alliance. It allows developers to write managed code in a Java-like language that utilizes Google-developed Java libraries, but does not support programs developed in native code. The unveiling of the Android plat form on 5 November 2007 was announced with the founding of the Open Handset Alli ance, a consortium of 34 hardware, software and telecom companies devoted to adv ancing open standards for mobile devices. When released in 2008, most of the And roid platform will be made available under the Apache free-software and open-sou rce license S. S. College, Bhavnagar Pinal Shah 6

Quick Time For Android En. No: 100430723009 1.2 Purpose of Seminar There are a few reason why developing Android and making it an open standard mak es sense for Google on a strategic level. However, it should also be said that A ndroid is not properly open (code can't be checked in by 3rd parties without Goo gle approval), neither free (there are fees associated with implementing it). In any case, by making it "open" and 'free", Google achieves a much higher market penetration and distribution across different territories and brands. Some longterm strategic advantages for Google are: 1) Access to usage data and profiling: through the numerous Google apps that are used on Android phones, through Googl e ID and sometimes through the OS itself, Google can enrich over time their know ledge of each user's activities, and most importantly build knowledge of what pe ople do when they're not in front of a PC. As information is what Google runs on , this becomes invaluable for the company 2) Smartphone role as a computing platform + emerging countries: it's projected that smart phones will outnumber PCs worldwide by 2012. Additionally, as Google' s business in developed countries reaches a point of saturation and starts to gr ow more slowly, developing countries are going to offer some of the biggest oppo rtunities to grow. In countries like China or India, part of the population is l eapfrogging PCs, and satisfying its computing needs through smart phones. This t rend is only going to increase 3) Mobile advertising opportunities: Google's mai n (some would say only) business is targeted advertising, and there are clearly huge opportunities for targeted advertising on smart phones, enabled by profilin g and by location awareness. Owning the OS that enables part of the ecosystem is going to allow Google to play a bigger role and to integrate more deeply with i ts advertising initiatives 4) Other business opportunities: several existing and rumored Google initiatives and acquisitions point to the fact that Google aims to extend their footprint i n the mobile ecosystem. My opinion is that, having started with the idea of enab ling a mobile ecosystem by providing the basic tools, Google now sees that the e cosystem needs to be nurtured and pushed in the right direction, and that there' s a huge business opportunity in doing so. I would not be surprised if, a couple of years from now, Google was offering an end-to-end solution for mobile conten t / information, starting with discovery and encompassing billing and delivery. S. S. College, Bhavnagar Pinal Shah 7

Quick Time For Android En. No: 100430723009 1.3 Goal of Seminar Google makes money every time someone does a search. The reason Google bought An droid and is giving it away to hundreds of hardware makers -- from phones to tel evisions to tablets -- is to make more places where more consumers do more searc hes. It is the next big wave of growth for Google. By the way, an Android tablet device is called a Tabloid. 1.4 Android Overview Android delivers a complete set of software for mobile devices: an operating sys tem, middleware and key mobile applications. Open Android was built from the ground-up to enable developers to create compelling m obile applications that take full advantage of all a handset has to offer. It wa s built to be truly open. For example, an application can call upon any of the p hones core functionality such as making calls, sending text messages, or using th e camera, allowing developers to create richer and more cohesive experiences for users. Android is built on the open Linux Kernel. Furthermore, it utilizes a cu stom virtual machine that was designed to optimize memory and hardware resources in a mobile environment. Android is open source; it can be liberally extended t o incorporate new cutting edge technologies as they emerge. The platform will co ntinue to evolve as the developer community works together to build innovative m obile applications. All applications are created equal Android does not differentiate between the phones core applications and thirdpart y applications. They can all be built to have equal access to a phones capabiliti es providing users with a broad spectrum of applications and services. With devi ces built on the Android Platform, users are able to fully tailor the phone to t heir interests. They can swap out the phone s home screen, the style of the dial er, or any of the applications. They can even instruct their phones to use their favorite photo viewing application to handle the viewing of all photos. S. S. College, Bhavnagar Pinal Shah 8

Quick Time For Android En. No: 100430723009 Breaking down application boundaries Android breaks down the barriers to building new and innovative applications. Fo r example, a developer can combine information from the web with data on an indi viduals mobile phone such as the users contacts, calendar, or geographic location to provide a more relevant user experience. With Android, a developer can build an application that enables users to view the location of their friends and be a lerted when they are in the vicinity giving them a chance to connect. Fast & easy application development Android provides access to a wide range of useful libraries and tools that can b e used to build rich applications. For example, Android enables developers to ob tain the location of the device, and allows devices to communicate with one anot her enabling rich peertopeer social applications. In addition, Android includes a full set of tools that have been built from the ground up alongside the platform providing developers with high productivity and deep insight into their applica tions. S. S. College, Bhavnagar Pinal Shah 9

Quick Time For Android En. No: 100430723009 Chapter 2 What is Android? 2.1 What is Android? 2.2 Android Landscape 2.3 Android different version compari sons 2.4 Android Architecture 2.5 Android vs. IPhone 2.6 Drawback of Android Pla tform S. S. College, Bhavnagar Pinal Shah 10

Quick Time For Android En. No: 100430723009 2.1 What is Android? Android is an operating system for mobile devices such as smart phones and table t computers. It is developed by the Open Handset Alliance led by Google. Google purchased the initial developer of the software, Android Inc., in 2005. The unve iling of the Android distribution on 5 November 2007 was announced with the foun ding of the Open Handset Alliance, a consortium of 84 hardware, software, and te lecommunication companies devoted to advancing open standards for mobile devices . Android consists of a kernel based on the Linux kernel, with middleware, libra ries and APIs written in C and application software running on an application fr amework which includes Java-compatible libraries based on Apache Harmony. Androi d uses the Dalvik virtual machine with just-intime compilation to run compiled J ava code. Android has a large community of developers writing applications ("app s") that extend the functionality of the devices. Developers write primarily in a customized version of Java. There are currently more than 250,000 apps availab le for Android. Apps can be downloaded from third-party sites or through online stores such as Android Market, the app store run by Google. S. S. College, Bhavnagar Pinal Shah 11

Quick Time For Android En. No: 100430723009 Why Android? Android is one of the most versatile, powerful and elegant platforms coming out of Google in recent years. It was initially developed by Android Inc later purch ased by Google and positioned in the Open Handset Alliance. As per the NPD group the unit sales Android phones is the largest among Smart Phones. Because it is widely supported by large number of hardware, software and network carriers its market share is growing worldwide in leaps and bounds. Being an open system base d on modified Linux kernel it has been widely accepted by the developer communit y and presents a golden opportunity to create products and services for this ama zing platform. Android is an open source platform and it is released under open source license. The Android operating system software stack consists of Java applications runni ng on a Java. S. S. College, Bhavnagar Pinal Shah 12

Quick Time For Android En. No: 100430723009 2.2 Android Landscape 2.0 clair included a new web browser, with a new user interface and support for H TML5 and the W3C Geolocation API. It also included an enhanced camera app with f eatures like digital zoom, flash, color effects, and more. 2.1 clair included sup port for voice controls throughout the entire OS. It also included a new launche r, with 5 home screens instead of 3, animated backgrounds, and a button to open the menu (instead of a slider). It also included a new weather app, and improved functionality in the Email and Phonebook apps. 2.2 Froyo introduced speed impro vements with JIT optimization and the Chrome V8 JavaScript engine and added Wi-F i hotspot tethering and Adobe Flash support . 2.3 Gingerbread refined the user i nterface, improved the soft keyboard and copy/paste features, SIP support (VoIP calls), and added support for Near Field Communication. 3.0 Honeycomb was a tabl et-oriented release which supports larger screen devices and introduces many new user interface features, and supports multicore processors and hardware acceler ation for graphics. The Honeycomb SDK has been released and the first device fea turing this version, the Motorola Zoom tablet, went on sale in February 2011. 3. 1 Honeycomb was announced at the 2011 Google I/O on 10 May 2011. One feature foc uses on allowing Honeycomb devices to directly transfer content from USB devices . 3.2 Honeycomb is "an incremental release that adds several new capabilities fo r users and developers". Highlights include optimization for a broader range of screen sizes; new "zoom-to-fill" screen compatibility mode; capability to load m edia files directly from the SD card; and an extended screen support API, provid ing developers with more precise control over the UI.

S. S. College, Bhavnagar Pinal Shah 13

Quick Time For Android En. No: 100430723009 2.3 Android Different Versions Comparisons S. S. College, Bhavnagar Pinal Shah 14

Quick Time For Android En. No: 100430723009 Features provided by latest Android Mobile Phone Handset Layout: Storage: Connectivity: GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Blueto oth, WiFi, LTE, NFC and WiMAX. Multiple language support: Web Browser: The web b rowser available in Android is based on the open-source Web Kit layout engine, c oupled with Chrome s V8 JavaScript engine. The browser scores a 93/100 on the Ac id3 Test. Additional hardware support: Multi touch Bluetooth Video calling Voice based Features Provides support for total 65 languages. SQLite Database support Support Graphics 2D and 3D S. S. College, Bhavnagar Pinal Shah 15

Quick Time For Android En. No: 100430723009 2.4 Android Architecture S. S. College, Bhavnagar Pinal Shah 16

Quick Time For Android En. No: 100430723009 2.5 Android vs. Iphone Android can Run Multiple Apps at the Same Time Android Gives You Better Notifica tions Android Lets You Choose Your Hardware Android Lets You Choose Your Carrier Android Does Google and Social Integration S. S. College, Bhavnagar Pinal Shah 17

Quick Time For Android En. No: 100430723009 Android takes a bite from Apple When Android first debuted on the HTC Dream (also known as the G1) back in Octob er of 2008, it was deemed an "iPhone Killer." While it didn t quite slay Apple s handset, it was the first step in a revolution against the tyrannous iPhone. Th e initial Android platform bested the iPhone OS on several levels, but lacked so me key functionality that the iPhone could provide. Since then, Android has grow n - not only meeting all of the functionalities of the iPhone, but besting it in nearly all aspects from an extensive list of devices to a growing Android Marke tplace. 2.6 Drawback of Android OS Malware and security a Chinese internet security firm, noted in a report that An droid is the second largest mobile OS (behind Symbian) to be infected with malwa re within China. The report stated that Android has become the new "malware hots pot" largely due to the operating system s rise in popularity Must know before going for Android Core Java: Standard Java programming is necessary to program applications for An droid. You should understand operators, loops and should have a basic idea of cl asses and objects. You can refer here to brush up your java skills. XML: You sho uld know what the XML standard is all about and how it is used in software appli cations. Eclipse: If you have worked in any IDE for Java you should be ok with e clipse. You can read more about it here. Object fundamentals: You will be able t o create elegant and efficient programs if you know the basics of OOPs. Features like Inheritance, Polymorphism, Encapsulation and Overloading help us create ef ficient and organized software systems and it is expected that you as ajava prog rammer must know them. S. S. College, Bhavnagar Pinal Shah 18

Quick Time For Android En. No: 100430723009 The Android programming is done on two levels System Level: It involves modifying the Android system code and adapting it to v arious hardware platforms. It also involves creating additional services and fea tures in the android system itself. Application Level: It involves creating soft ware products and services which sits on top of the Android software stack and i nteracts with the hardware through the underlying Android platform. Android appl ications are built using Java. The Java byte code executes on a efficient and mo dified virtual machine known as Dalvik Virtual Machine. Dalvik does not align to Java SE nor Java ME Class Library profiles (e.g., Java ME classes, AWT or Swing are not supported). How program will execute? Important component is Dalvik Virtual Machine: Dalvik replaces the JVM in provid ing the runtime environment to Java platform applications. The VM runs Java appl ications which have been converted to the Dalvik Executable format .dex The dx t ool available in the SDK converts Java byte code to DVM byte code at build time. The dx format is a highly efficient and compact byte code. dx installed to incr ease efficiency. The compiled application is bundled by the aapt tool into an An droid package .apk Like .jad & .jar in J2ME, .apk files are distributed and inst alled on Android powered devices can be installed on different devices and can b e further modified after being

S. S. College, Bhavnagar Pinal Shah 19

Quick Time For Android En. No: 100430723009 Chapter 3 Android Application Basics 3.1 Activity, View, Event, Intent 3.2 Application Life Cycle 3.3 Setting Develop ment Environment 3.4 Develop Hello World Application 3.5 Demo of another Applicati on S. S. College, Bhavnagar Pinal Shah 20

Quick Time For Android En. No: 100430723009 Android App Basics: Android apps are written in Java Almost all Java classes available plus encrypti on, http, json, xml processing libraries No main() function instead: loosely cou pled components, one or more of them defined as entry point(s) Most important co mponent: Activity corresponds to a visible window on the screen 3.1 Android App Basics Activity, View, Event, Intent Activity Defines view to be displayed in its window Handles events (e.g. click on a button) Uses Intents to start other activities View View is the visible part of the activity Defined in an XML layout file (or in code) Intent Starts another a ctivity (opens a new window ) Can pass data to the started activity Can even start activities from another app S. S. College, Bhavnagar Pinal Shah 21

Quick Time For Android En. No: 100430723009 3.2 Android App Basics Activity Lifecycle As resources are limited in mobile phone the operating system must have some cap ability to destroy some activity which are not required by the system means the activity which are running in background some times it is required to destroy th at activity. Therefore every activity has a lifecycle that will be maintain by O perating System. To avoid losing data or the state of an activity, you must over ride lifecycle methods to save your data when your activity is paused or stopped . S. S. College, Bhavnagar Pinal Shah 22

Quick Time For Android En. No: 100430723009 3.3 Development Environment Requirements Eclipse Android SDK Starter Package from http://developer.android.com/sdk/index. html Use SDK Starter Package (run as Administrator) to install: SDKs for all pla tforms your app shall be running on (e.g. all from 1.5 to 2.1) USB Driver Packag e for USB debugging (debug apps directly on your phone) S. S. College, Bhavnagar Pinal Shah 23

Quick Time For Android ADT (Android Development Tools) Eclipse Plug in En. No: 100430723009 (Install from within Eclipse; location: https://dl-ssl.google.com/android/eclips e/) What is the ADT good for? Wizard to create a new Android project Code editor for Android XML files Automatic build process (creates APK Android Package file) d ebugging of apps in the emulator or on a real phone Take screenshots from a real phone Export signed APKs to be uploaded into Android Market Setting up the Development Environment (1/3) 1. Eclipse is expected to be installed. 2. Download and install the SDK Starter Package appropriate to your operating sy stem from http://developer.android.com/sdk/index.html 3. Run SDK Starter Package(as Administrator on Vista / Windows 7). Install... all SDK platforms (for this tutorial, 1.6 is enough), - the USB driver package ( not required for this tutorial), - and the documentation (not required for this tutorial). S. S. College, Bhavnagar Pinal Shah 24

Quick Time For Android En. No: 100430723009 Setting up the Development Environment (2/3) 4. Install the ADT (Android Development Tools) plugin. The following instruction s are for Eclipse 3.5 (Galileo) and Eclipse 3.6 (Helios). Instructions for Eclip se 3.4 (Ganymede) can be found at http://developer.android.com/sdk/eclipse-adt.h tml. 4.1. Select Help Install New Software . 4.2. In the Available Software dialog, ck the Add button. 4.3. In the Add Site dialog, enter a name (e.g.Android Plugin) a nd try to add URL Location like https: and click on OK button. Setting up the Development Environment (3/3) 4.4. Back in the Available Software dialog, select the checkbox next to Developer Tools and click Next . 4.5. In the Install Details dialog, click Agree button to licen ce the product. 4.6 Restart Eclipse. 4.7 Select Window -> Preference S. S. College, Bhavnagar Pinal Shah 25

Quick Time For Android 4.8 In the preference dialogue box select the Android. 4.9 Enter the SDK folder. For Example: En. No: 100430723009 3.4 Developing and Testing a Hello World App (1/20) Use a the ADT s New Select Project wizard to create new project: File New

Project... ; in the New Project dialog Select Android Project from the Android folde S. S. College, Bhavnagar Pinal Shah 26

Quick Time For Android Fill out the New Android Project dialog as follows: Project name: Hello Workshop U se default location or define your own location En. No: 100430723009 Build target: Android 1.6 (we ll make this 1.5-compatible later) Application nam e: Hello Workshop Package name: de.test.hello Create Activity: HelloWorkshopActiv ity Min SDK Version: 4 Click on the Finish button. Developing and Testing a Hello World App (2/20) The New Project Wizard created the following files and folders: --------- Main Activity Class --------Resource ID definitions (autocreated; never modify this file) --------- Folder for binary files (everything n ot handled by Android) Folder for resource files (images, layouts, strings ...) --------- Main activity s view --------- Manifest file defining things like app name, logo and main activity S. S. College, Bhavnagar Pinal Shah 27

Quick Time For Android En. No: 100430723009 Developing and Testing a Hello World App (3/20) For phones with high density screens (e.g. Motorola Milestone) to use the hdpi r esources, we must add the following entry to the AndroidManifest.xml file: <supp orts-screens android:anyDensity="true" /> Otherwise, those phones will use the m dpi resources and scale them up. For phones with large (Archos 5) or small scree ns (HTC Tattoo) to use the full screen or to run the app at all, we must further add the following definitions to the entry created before: <supports-screens an droid:anyDensity="true" android:largeScreens="true" android:smallScreens="true" /> Otherwise, phones with large screens will display the app only in a small are a of the screen with a black border around it, and phones with small screens won t start the app at all. Developing and Testing a Hello World App (4/20) values/strings.xml <?xmlversion="1.0" encoding="utf-8"?> <resources> <stringname ="hello">Hello World, HelloWorkshopActivity!</string> <stringname="app_name">Hel lo Workshop</string> </resources> Developing and Testing a Hello World App (5/20) S. S. College, Bhavnagar Pinal Shah 28

Quick Time For Android layout/main.xml <?xmlversion="1.0" encoding="utf-8"?> En. No: 100430723009 <LinearLayout xmlns:android="http://[...]" android:orientation="vertical" androi d:layout_width=" fill_parent" android:layout_height="fill_parent"> <TextView and roid:layout_width="fill_parent" android:layout_height="wrap_content" android:tex t="@string/hello"/> </LinearLayout> Defines a (simple) layout called main (just a name, no meaning), which is later referenced by the activity to create its view. Developing and Testing a Hello World App (6/20) R.java Automatically created defines integer constants for each resource. Never modify this file no need to even look at it. package de.test.hello; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { p ublic static final int app_name=0x7f040001; public static final int hello=0x7f04 0000; } } S. S. College, Bhavnagar Pinal Shah 29

Quick Time For Android En. No: 100430723009 Developing and Testing a Hello World App (7/20) HelloWorkshop2Activity.java package de.test.hello; import android.app.Activity; import android.os.Bundle; public class HelloWorkshopActivity extends Activity { /**Called when the activity is first created. */ @Override publicvoid onCreate(B undle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R .layout.main); } } Constant from R class referencing the layout defined in main. xml Sets the specified view as view for this activity. Developing and Testing a Hello World App (8/20) Create an Android Virtual Device(Emulator) Click on the Android SDK and AVD manag er icon in the Eclipse icon bar. Click on New In the Create new AVD dialog, ente r: - Name: G1 - Target: Android 1.6 - API Level 4 - SD Card Size: 1024 MiB - Ski n: Built-in: Default (HVGA) Then click on Create AVD (might take a while now) S. S. College, Bhavnagar Pinal Shah 30

Quick Time For Android En. No: 100430723009 Developing and Testing a Hello World App (9/20) Run the App for the First Time Select Run -> Run (or press Ctrl + F11). In the Run As dialog, select Android Ap plication and click on OK. Eclipse will now automatically start the G1 AVD we just created (If you have multiple matching AVDs, a selection dialog will let you cho se one). After about a minute we should See our app running in the emulator! 3.5 Developing and Testing a Hello World App (10/20) This is what we want to do today: Create a view that looks like the one at the l eft Let the user enter his name in the input field When the user clicks one of t he buttons and no name was entered, display an alert dialog with an error messag e. When the user clicks a button with his name entered the user shall be greeted with a popup message (toast) the greeting at the top of the screen shall change S. S. College, Bhavnagar Pinal Shah 31

Quick Time For Android En. No: 100430723009 Developing and Testing a Hello World App (11/20) Add Components to the Layout Add the Enter your name label below the first TextVie w component: <TextView android:layout_width="fill_parent" android:layout_height= "wrap_content" android:layout_marginTop="20dp" android:text="@string/enter_your_ name" /> Eclipse will now show an error message: No resource found that matches the given name (at text with value @string/enter_your_name). Add the missing r esource to the strings.xml file: <stringname="enter_your_name">Enter your name:< /string> The error message from main.xml will now disappear. Developing and Testing a Hello World App (12/20) Add the input field below the Enter your name component: <EditText android:id="@+i d/name_field" android:layout_width="fill_parent" android:layout_height="wrap_con tent" /> The first line assigns the id name field to this component. Below the n ame field We want to buttons beside each other. Therefore we need a nested Linea rLayout with horizontal orientation and inside it the two buttons. Developing and Testing a Hello World App (13/20) Developing and Testing a Hello World App (14/20) Developing and Testing a Hello World App (15/20) Now we need to extend our Activity. Open HelloWorkshopActivity.java and add the following field definitions at the top of the class: S. S. College, Bhavnagar Pinal Shah 32

Quick Time For Android En. No: 100430723009 private Button hiButton; private Button helloButton; At the end of the onCreate method, insert the following code: hiButton = (Button)findViewById(R.id.hi_butto n); hiButton.setOnClickListener(this); helloButton = (Button)findViewById(R.id.h ello_button); helloButton.setOnClickListener(this); We will now see an error mes sage as HelloWorkshopActivity does not implement OnClickListener yet. Click on t he error message and select Let HelloWorkshopActivity implement OnClickListene r. We ll see the next error message because HelloWorkshopActivity does not imple ment the methods defined in OnClickListener. Click on the error message and sele ct Add unimplemented methods. Developing and Testing a Hello World App (16/20) When the user clicks on one of the buttons, we first need to check if he entered his name. Insert the following code into the onClick method Eclipse has just crea ted for us: EditText nameField = (EditText) findViewById(R.id.name_field); String name = nam eField.getText().toString(); if (name.length() == 0) { new AlertDialog.Builder(t his) .setMessage(R.string.error_name_missing) .setNeutralButton(R.string.error_o k, null) .show(); return; } Add the two string resources we just used and two ot hers we use in the next step to the strings.xml file: <string name="error_name_m issing">Please enter your name.</string> <string name="error_ok">OK</string> <st ring name="hi_greeting">Hi %s!</string> <string name="hello_greeting">Hello %s!< /string> S. S. College, Bhavnagar Pinal Shah 33

Quick Time For Android En. No: 100430723009 Developing and Testing a Hello World App (17/20) We ve made sure the user entered a name. Now display the greeting depending on t he button: if(v == hiButton v == helloButton) { intresourceId = v == hiButton ? R.string.hi_greeting :R.string.hello_greeting; Stringgreeting = getResources( ).getString(resourceId, name); Toast.makeText(this, greeting, Toast.LENGTH_LONG) .show(); } Developing and Testing a Hello World App (18/20) The method we ve just created can now be extended: if(v == hiButton v == hell oButton) { Int resourceId = v == hiButton ? R.string.hi_greeting :R.string.hello _greeting; String greeting = getResources().getString(resourceId, name); Toast.m akeText(this, greeting, Toast.LENGTH_LONG).show(); TextViewgreetingField = (Text View) findViewById(R.id.greeting_field); greetingField.setText(greeting); } And now? We re ready - run the project! You ll find the complete sources in the appe ndix. S. S. College, Bhavnagar Pinal Shah 34

Quick Time For Android En. No: 100430723009 Developing and Testing a Hello World App (19-20/20) S. S. College, Bhavnagar Pinal Shah 35

Quick Time For Android En. No: 100430723009 Appendix Source Codes A HelloWorkshopActivity.java: packagede.test.hello; import android.app.Activity; i mport A ndroid.app.AlertDialog; import android.os.Bundle; import android.view.Vi ew; import android.view.View.OnClickListener; import android.widget.Button; impo rt android.widget.EditText; import android.widget.TextView; import android.widge t.Toast; publi cclass HelloWorkshopActivi t xtendsActivity implementsOnClickList ener { ey privateButton hiButton ; privateButton helloButto; n @Override publi c void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layou a.n); mt i hiButton = (Button) findViewById(R.hd_ ii .but ton ); hiButton .setOnClickListeneth r (is); n r (is); helloButton= (Button) fin dViewById(R.helloButto. setOnClickListeneth } @Override publicvoid onClick(View v) { EditText nameField = (EditText) findViewById( R . i d fiel) ; String name = n ame _. d nameField.getText().toString(); if (name.length() == 0) { new AlertD ialog.Buildeth r (is).setMessage( R.stringerror_name_missing setNeutralButton( R .stringerror_ok . ). . , null) .show(); return ; } if (v ==hiButton v ==hello Butto) { n int resourceId = v =h =iButton ? R.stringh .i_greeting : R.stringh .e llo_greetin ;g String greeting = getResources().getString(resourceId, name); Toa st. akeText this, greeting, Toast . NGTH_LON) .show(); m ( LE G TextView greetin gField = (TextView) findViewById( Rei di ng_fiel d g r. e t. ); greetingField.se tText(greeting); } } } S. S. College, Bhavnagar Pinal Shah 36

Quick Time For Android En. No: 100430723009 Appendix Source Codes B main.xml <? Xml version ="1.0"encoding ="utf-8" ?> <LinearLayout xmlns:androi= " ht tp ://schemas .a nd roid.c om /a pk /res/and roid " d android:orientati= nve rtical" o" android:layout_wid= hfill_parent" t" android:layout_heig= tfill_paren t" h" > <TextView android:i= d"@+id/greeting_field" android:layout_wid= hfill_pa rent" t" android:layout_heig= twrap_content" android:tex= h" t"@string/hello" /> <TextView android:layout_wid= hfill_parent" t" android:layout_heig= twrap_conte nt" android:layout_marginT "p h" =o 20dp" android:tex= t"@string/enter_your_name " /> <EditText android:i= d"@+id/name_field" android:layout_wid= hfill_parent" t " android:layout_heig= twrap_content" h" /> <LinearLayout android:orientati= nho rizontal" o" android:layout_wid= hfill_parent" t" android:layout_heig= twrap_con tent" h" > <Button android:i= d"@+id/hi_button" android:layout_wid= hwrap_conten t" t" android:layout_heig= twrap_content" h" android:tex= t"@string/hi_button" a ndroid:layout_weig= t1" h" /> <Button android:i= d"@+id/hello_button" android:la yout_wid=hwrap_content" android:layout_heig= twrap_content" t" h" android:tex= t "@string/hello_button" android:layout_weig= t1" h" /> </LinearLayou> t </LinearL ayout> S. S. College, Bhavnagar Pinal Shah 37

Quick Time For Android En. No: 100430723009 Appendix Source Codes C strings.xml <?xml versi on ="1.0" encoding ="utf-8" ?> <resources > <stringname ="hello" >Hello World, HelloWorkshopActivi <t s ! ring /y t > <stringname ="app_ name> "Hello Worksho p < /string > <stringname ="enter_your_name E nter your nam e /string >" <: > <stringname ="hi_button> "Say Hi! /string < > <stringname ="he llo_button " > Say Hello< !/string > <stringname ="error_name_missin> "lease ent er your nam e . tring gP </ s > <stringname ="error_ok> "OK</string > <stringnam e ="hi_greeting> Hi %s! /string " < > <stringname ="hello_greeting Hello %s! /st ring >" < > </resources > S. S. College, Bhavnagar Pinal Shah 38

Quick Time For Android En. No: 100430723009 References http://sites.google.com/site/io/dalvik-vm-internals http://www.bright hub.com/mobile/googleandroid/articles/ 17822.aspx http://glab.wordpress.com/2008 /05/21/android-a-quickOverview S. S. College, Bhavnagar Pinal Shah 39

También podría gustarte