Android 4.0 Development Tutorial Lars Vogel

48 307 0
Android 4.0 Development Tutorial Lars Vogel

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Android 4.0 Development Tutorial Lars Vogel Version 8.7 Copyright © 2009 - 2011 Lars Vogel 24.11.2011 Revision History Revision 0.1 Created Revision 0.2 - 8.7 bug fixing and enhancements 04.07.2009 07.07.2009 - 24.11.2011 Development with Android Gingerbread and Eclipse This tutorial describes how to create Android applications with Eclipse It is based on Eclipse 3.7 (Indigo), Java 1.6 and Android 4.0 (Ice Cream Sandwich) Table of Contents What is Android? 1.1 Android Operation System 1.2 Important Android components 1.3 Dalvik Virtual Machine 1.4 Security and permissions Android Application Architecture 2.1 AndroidManifest.xml 2.2 R.java, Resources and Assets 2.3 Reference to resources in XML files 2.4 Activities and Layouts 2.5 Activities and Lifecycle 2.6 Context Installation 3.1 Eclipse and automatic Android SDK 3.2 Manually install Android SDK 3.3 Install a specific Android version 3.4 Android Source Code Emulator Shortcuts 4.1 Create an Android Emulator Device 4.2 Using the emulator 4.3 Performance Error handling and typical problems 5.1 Clean Project 5.2 LogCat 5.2 LogCat 5.3 Emulator does not start 5.4 Error message for @override 5.5 Missing Imports 5.6 Eclipse Tips Your first Android project 6.1 Create Project 6.2 Two faces of things 6.3 Create attributes 6.4 Add UI Elements 6.5 Edit UI properties 6.6 Code your application 6.7 Start Project Starting an deployed application Menus and Action Bar 8.1 Definition of menu entries 8.2 Action bar tabs 8.3 Context menus Tutorial: Menus and Action Bar 9.1 Project 9.2 Add a menu XML resource 10 Preferences 11 Tutorial: Preferences 11.1 Using preferences 11.2 Run 12 Dialogs via the AlertDialog 13 Layouts 14 TableLayout 14.1 Overview 14.2 Example 15 ContentProvider 15.1 Overview 15.2 Create contacts on your emulator 15.3 Using the Contact Content Provider 16 ScrollView 17 DDMS perspective and important views 17.1 DDMS - Dalvik Debug Monitor Server 17.2 LogCat View 17.3 File explorer 18 Shell 18.1 Android Debugging Bridge - Shell 18.2 Uninstall an application via adb 18.3 Emulator Console via telnet 19 Deploy your application on a real device 20 Thank you 21 Questions and Discussion 22 Links and Literature 22.1 Source Code 22.2 Android Resources 22.3 vogella Resources What is Android? 1.1 Android Operation System Android is an operating system based on Linux with a Java programming interface It provides tools, e.g a compiler, debugger and a device emulator as well as its own Java Virtual machine (Dalvik Virtual Machine - DVM) Android is officially guided by the Open Handset Alliance but in reality Google leads the project Android supports 2-D and 3-D graphics using the OpenGL libraries and supports data storage in a SQLite database Every Android applications runs in its own process and under its own user id which is generated automatically by the Android system during deployment Therefore the application is isolated from other running applications and a misbehaving application cannot easily harm other Android applications 1.2 Important Android components An Android application consists out of the following parts: Activity - represents the presentation layer of an Android application, e.g a screen which the user sees An Android application can have several activities and it can be switched between them during runtime of the application Views - the User interface of an Activities is built with widget classes which inherent from android.view.View The layout of the views is managed by android.view.ViewGroups Views often have attributes which can be used to change their appearance and behavior Services - perform background tasks without providing an UI They can notify the user via the notification framework in Android ContentProvider - provides data to applications, via a content provider your application can share data with other applications Android contains a SQLite DB which can serve as data provider Intents - are asynchronous messages which allow the application to request functionality from other services or activities An application can call directly a service or activity (explicit intent) or ask the Android system for registered services and applications for an intent (implicit intents) For example the application could ask via an intent for a contact application Applications register themselves to an intent via an IntentFilter Intents are a powerful concept as they allow the creation of loosely coupled applications BroadcastReceiver - receives system messages and implicit intents, can be used to react to changed conditions in the system An application can register as a BroadcastReceiver for certain events and can be started if such an event occurs Widgets - interactive components primary used on the Android homescreen to display certain data and to allow the user to have quick access the the information Other Android components are Live Folders and Android Live Wallpapers Live Folders display data on the homescreen without launching the corresponding application 1.3 Dalvik Virtual Machine Android uses a special virtual machine, e.g the Dalvik Virtual Machine Dalvik uses special bytecode Therefore you cannot run standard Java bytecode on Android Android provides a tool dx which allows to convert Java Class files into dex (Dalvik Executable) files Android applications are packed into an apk (Android Package) file by the program aapt (Android Asset Packaging Tool) To simplify development Google provides the Android Development Tools (ADT) for Eclipse The ADT performs automatically the conversion from class to dex files and creates the apk during deployment 1.4 Security and permissions Android defines certain permissions for certain tasks For example if the application wants to access the Internet it must define in its configuration file that it would like to use the related permission During the installation of an Android application the user receives a screen in which he needs to confirm the required permissions of the application Android Application Architecture 2.1 AndroidManifest.xml An Android application is described in the file AndroidManifest.xml This file must declare all Activities, Services, BroadcastReceivers and ContentProvider of the application It must also contain the required permissions for the application For example if the application requires network access it must be specified here AndroidManifest.xml can be thought as the deployment descriptor for an Android application The package attribute defines the base package for the following Java elements It also must be The package attribute defines the base package for the following Java elements It also must be unique as the Android Marketplace only allows application for a specific package once Therefore a good habit is to use your reverse domain name as a package to avoid collisions with other developers android:versionName and android:versionCode specify the version of your application versionName is what the user sees and can be any string versionCode must be an integer and the Android Market uses this to determine if you provided a newer version to trigger the update on devices which have your application installed You typically start with "1" and increase this value by one if you roll-out a new version of your application The tag defines an Activity , in this example pointing to the class "de.vogella.android.temperature.Convert" An intent filter is registered for this class which defines that this Activity is started once the application starts (action android:name="android.intent.action.MAIN" ) The category definition category android:name="android.intent.category.LAUNCHER" defines that this application is added to the application directory on the Android device The @string/app_name value refer to resource files which contain the actual values This makes it easy to provide different resources, e.g strings, colors, icons, for different devices and makes it easy to translate applications The "uses-sdk" part of the "AndroidManifest.xml" defines the minimal SDK version your application is valid for This will prevent your application being installed on devices with older SDK versions 2.2 R.java, Resources and Assets The directory gen in an Android project contains generated values R.java is a generated class which contains references to resources of the res folder in the project These resources are defined in the res directory and can be values, menus, layouts, icons or pictures or animations For example a resource can be an image or an XML file which defines strings If you create a new resource, the corresponding reference is automatically created in R.java The references are static int values, the Android system provides methods to access the corresponding resource For example to access a String with the reference id R.string.yourString use the method getString(R.string.yourString)); R.java is automatically maintained by the Eclipse development environment, manual changes are not necessary While the directory res contains structured values which are known to the Android platform the directory assets can be used to store any kind of data In Java you can access this data via the AssetsManager and the method getAssets() 2.3 Reference to resources in XML files In your XML files, e.g your layout files you can refer to other resources via the @ sign For example if you want to refer to a color you defined as resources you can refer to it via @color/your_id or if you have defined a "hello" string as resource you can access it via @string/hello 2.4 Activities and Layouts The user interface for Activities is defined via layouts At runtime, layouts are instances of The user interface for Activities is defined via layouts At runtime, layouts are instances of android.view.ViewGroups The layout defines the UI elements, their properties and their arrangement UI elements are based on the class android.view.View ViewGroup is a subclass of the class View and a layout can contain UI components ( Views ) or other layouts ( ViewGroups ) You should not nestle ViewGroups too deeply as this has a negative impact on performance A layout can be defined via Java code or via XML You typically uses Java code to generate the layout if you don't know the content until runtime; for example if your layout depends on content which you read from the Internet XML based layouts are defined via a resource file in the folder /res/layout This file specifies the ViewGroups , Views , their relationship and their attributes for a specific layout If a UI element needs to be accessed via Java code you have to give the UI element an unique id via the android:id attribute To assign a new id to an UI element use @+id/yourvalue By conversion this will create and assign a new id yourvalue to the corresponding UI element In your Java code you can later access these UI elements via the method findViewById(R.id.yourvalue) Defining layouts via XML is usually the preferred way as this separates the programming logic from the layout definition It also allows the definition of different layouts for different devices You can also mix both approaches 2.5 Activities and Lifecycle The operating system controls the life cycle of your application At any time the Android system may stop or destroy your application, e.g because of an incoming call The Android system defines a life cycle for activities via pre-defined methods The most important methods are: onSaveInstanceState() - called if the activity is stopped Used to save data so that the activity can restore its states if re-started onPause() - always called if the Activity ends, can be used to release resource or save data onResume() - called if the Activity is re-started, can be used to initialize fields The activity will also be restarted if a so called "configuration change" happens A configuration change for example happens if the user changes the orientation of the device (vertical or horizontal) The activity is in this case restarted to enable the Android platform to load different resources for these configuration, e.g layouts for vertical or horizontal mode In the emulator you can simulate the change of the orientation via CNTR+F11 You can avoid a restart of your application for certain configuration changes via the configChanges attribute on your activity definition in your AndroidManifest.xml The following activity will not be restarted in case of orientation changes or position of the physical keyboard (hidden / visible) 2.6 Context The class android.content.Context provides the connections to the Android system It is the interface to global information about the application environment Context also provides access to Android Services , e.g theLocation Service As Activities and Services extend the class Context you can directly access the context via this Installation The following assume that you have already Eclipse installed For details please see Eclipse Tutorial 3.1 Eclipse and automatic Android SDK Use the Eclipse update manager to install all available components for the Android Development Tools (ADT) from the URL https://dl-ssl.google.com/android/eclipse/ If you are not familiar with the Eclipse update manager the usage is described in Eclipse update manager After the new Android development components are installed you will be prompted to install the Android SDK You can follow the following wizard or go to the next section to learn how to it manually 3.2 Manually install Android SDK The previous step downloads the Android SDK automatically for you You can also download the Android SDK manuallz from the Android homepage under Android SDK download The download contains a zip file which you can extract to any place in your file system, e.g I placed it under "c:\android-sdk-windows" Avoid using spaces in the path name otherwise you may experience problems later You also have to define the location of the Android SDK in the Eclipse Preferences In Eclipse open the Preferences dialog via Windows → Preferences Select Android and enter the installation path of the Preferences dialog via Windows → Preferences Select Android and enter the installation path of the Android SDK 3.3 Install a specific Android version The Android SDK Manager allows you to install specific versions of Android Select Window → Android SDK Manager from the Eclipse menu The dialog allows you to install new package and also allow you to delete them Select "Available packages" and open the "Third Party Add-ons" Select the Google API 14 (Android 4.0) version of the SDK and press "Install" Press the "Install" button and confirm the license for all package After the installation restart Eclipse 3.4 Android Source Code The following step is optional } edit.commit(); // A toast is a view containing a quick little message for the // user We give a little feedback Toast.makeText(OverviewActivity.t th i s s, "Reverted string sequence of user name.", Toast.LENGTH_LONG).show(); To open the new preference activity we will use the method onOptionsItemSelected() Even though we currently have only one option in our menu we use a switch to be ready for several new menu entries To see the current values of the preferences we define a button and use the class "PreferenceManager" to get the sharedPreferences @Override p u b l i c b o o l e a n onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); r e t u r n true; } // This method is called once the menu is selected @Override p u b l i c b o o l e a n onOptionsItemSelected(MenuItem item) { s w i t c h (item.getItemId()) { // We have only one menu option c a s e R.id.preferences: // Launch Preference activity Intent i = n e w Intent(OverviewActivity.t th i s s, MyPreferencesActivity.c cl a s s s); startActivity(i); // Some feedback to the user Toast.makeText(OverviewActivity.t th i s s, "Enter your user credentials.", Toast.LENGTH_LONG).show(); break k; } } r e t u r n true; 11.2 Run Run your application Press the "menu" hardware button and then select your menu item "Preferences" You should be able to enter your user settings then press the back hardware button to return to your main activity The saved values should be displayed in a small message windows (Toast) if you press your first button If you press the second button the username should be reversed 12 Dialogs via the AlertDialog We have already used a "Toast" which is a small message window which does not take the focus In this chapter we will use the class "AlertDialog" AlertDialog is used to open a dialog from our activity This modal dialog gets the focus until the user closes it An instance of this class can be created by the builder pattern, e.g you can chain your method calls You should always open a dialog from the class onCreateDialog(int) as the Android system manages the dialog in this case for you This method is automatically called by Android if you call showDialog(int) Create a new Android project "de.vogella.android.alertdialog" with the activity "ShowMyDialog" Maintain the following layout for "main.xml" Change the code of your activity to the following p a c k a g e de.vogella.android.alertdialog; import import import import import import import import android.app.Activity; android.app.AlertDialog; android.app.AlertDialog.Builder; android.app.Dialog; android.content.DialogInterface; android.os.Bundle; android.view.View; android.widget.Toast; p u b l i c c l a s s ShowMyDialog e x t e n d s Activity { /** Called when the activity is first created */ @Override p u b l i c v o i d onCreate(Bundle savedInstanceState) { super r.onCreate(savedInstanceState); setContentView(R.layout.main); } p u b l i c v o i d openMyDialog(View view) { showDialog(10); } @Override p r o t e c t e d Dialog onCreateDialog(i i n t id) { s w i t c h (id) { c a s e 10: // Create out AlterDialog Builder builder = n e w AlertDialog.Builder(t th i s s); builder.setMessage("This will end the activity"); builder.setCancelable(true); builder.setPositiveButton("I agree", n e w DialogInterface.OnClickListener() { p u b l i c v o i d onClick(DialogInterface dialog, i n t which) { ShowMyDialog.t th i s s.finish(); } }); builder.setNegativeButton("No, no", n e w DialogInterface.OnClickListener() { p u b l i c v o i d onClick(DialogInterface dialog, i n t which) { Toast.makeText(getApplicationContext(),"Activity will continue",Toast.LENGTH_LONG ).show(); } }); AlertDialog dialog = builder.create(); dialog.show(); } return super r.onCreateDialog(id); } } If you run your application and click your button you should see your dialog More on dialogs can be found on Android Dialogs standard documentation 13 Layouts Android supports different default layout manager LinearLayout puts all its child elements into a single column or row depending on the orientation attribute Other types are FrameLayout, RelativeLayout and TableLayout All layouts allow to defined attributes Childs can also define attributes which may be evaluated by their parent layout For example the 14 TableLayout 14.1 Overview In earlier chapter we have used the LinearLayout which allows you to stack widgets vertical or horizontal LinearLayout can be nested to achieve nice effects This chapter will demonstrate the usage of "TableLayout" This layout allows you to organize a view into a table format You specify via the view group "TableRow" rows for your table Afterwards you put widgets into the individual rows On the "TableLayout" you can define which column should take additional space via the "android:stretchColumns" attribute If several columns should take the available space you can specify them as a comma-separated list Similar you can use the attribute "android:shrinkColumn", which will try to word-wrap the content of the specified widgets and the attribute "android:collapseColums" to try to word-wrap the content of the specified widgets and the attribute "android:collapseColums" to define initially hidden columns Via Java you can display / hide these columns via the method setColumnVisible() Columns will be automatically created based on the maximum number of widgets in one row Per default each widgets creates a new column in the row You can specific via "android:layout_column" the column a widget should go and via "android:layout_span" how many columns a widget should take You can also put non TableRows in a table This way you can for example add dividers between your columns 14.2 Example Create the project "de.vogella.android.layout.table" with the activity "DemoTableLayout" Change "main.xml" to the following Change the activity "DemoTableLayout" to the following to use the button to hide the second column in the table p a c k a g e de.vogella.android.layout.table; import import import import import android.app.Activity; android.os.Bundle; android.view.View; android.widget.Button; android.widget.TableLayout; p u b l i c c l a s s DemoTableLayout e x t e n d s Activity { p r i v a t e TableLayout layout; p r i v a t e TableLayout layout; p r i v a t e Button button; /** Called when the activity is first created */ @Override p u b l i c v o i d onCreate(Bundle savedInstanceState) { super r.onCreate(savedInstanceState); setContentView(R.layout.main); layout = (TableLayout) findViewById(R.id.tableLayout1); button = (Button) findViewById(R.id.collapse); } } p u b l i c v o i d toggleHiddenRows(View view) { // Second row has index layout.setColumnCollapsed(1, !layout.isColumnCollapsed(1)); i f (layout.isColumnCollapsed(1)) { button.setText("Show second column"); } else { button.setText("Hide second column"); } } 15 ContentProvider 15.1 Overview ContentProvider are used to provide data from an application to another ContentProvider not store the data but provide the interface for other applications to access the data The following example will use an existing context provider from "Contacts" 15.2 Create contacts on your emulator For this example we need a few maintained contacts Select the home menu and then the menu entry "People" to create contacts The app will ask you if you want to login Either login or select "Not now" Press ""Create a new contact" You can create local contacts Finish adding your first contact Afterwards the app allow you to add more contacts via the + button.As a result you should have a few new contacts in your application 15.3 Using the Contact Content Provider Create a new Android project "de.vogella.android.contentprovider" with the activity "ContactsView" Rename the id of the existing TextView from the example wizard to "contactview" Delete the default text Also change the layout_height to "fill_parent" The resulting main.xml should look like the following Access to the contact content provider require a certain permission as not all applications should have access to the contact information Open the AndroidManifest.xml, and select the Permissions tab On that tab click the "Add" button, and select "Uses Permission" From the drop-down list select the entry "android.permission.READ_CONTACTS" Change the coding of the activity p a c k a g e de.vogella.android.contentprovider; i m p o r t android.app.Activity; import import import import import import android.app.Activity; android.database.Cursor; android.net.Uri; android.os.Bundle; android.provider.ContactsContract; android.widget.TextView; p u b l i c c l a s s ContactsView e x t e n d s Activity { /** Called when the activity is first created */ @Override p u b l i c v o i d onCreate(Bundle savedInstanceState) { super r.onCreate(savedInstanceState); setContentView(R.layout.main); TextView contactView = (TextView) findViewById(R.id.contactview); Cursor cursor = getContacts(); w h i l e (cursor.moveToNext()) { } } String displayName = cursor.getString(cursor getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); contactView.append("Name: "); contactView.append(displayName); contactView.append("\n"); p r i v a t e Cursor getContacts() { // Run query Uri uri = ContactsContract.Contacts.CONTENT_URI; String[] projection = n e w String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + ("1") + "'"; String[] selectionArgs = null; String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; } r e t u r n managedQuery(uri, projection, selection, selectionArgs, sortOrder); } Typically you would display such data in a ListView 16 ScrollView ScrollViews can be used to contain one view that might be to big to fit on one screen If the view is to big the ScrollView will display a scroll bar to scroll the context Of course this view can be a layout which can then contain other elements Create an android project "de.vogella.android.scrollview" with the activity "ScrollView" Create the following layout and class yout_height="wrap_content"> p a c k a g e de.vogella.android.scrollview; import import import import android.app.Activity; android.os.Bundle; android.view.View; android.widget.TextView; p u b l i c c l a s s ScrollView e x t e n d s Activity { /** Called when the activity is first created */ } @Override p u b l i c v o i d onCreate(Bundle savedInstanceState) { super r.onCreate(savedInstanceState); setContentView(R.layout.main); TextView view = (TextView) findViewById(R.id.TextView02); String s=""; f o r (i i n t i=0; i < 100; i++) { s += "vogella.de "; } view.setText(s); } The attribute "android:fillViewport="true"" ensures that the the scrollview is set to the full screen even if the elements are smaller then one screen and the "layout_weight" tell the android system that these elements should be extended 17 DDMS perspective and important views 17.1 DDMS - Dalvik Debug Monitor Server Eclipse provides a perspective for interacting with your Android (virtual) device and your Android application program Select Window → Open Perspective → Other → DDMS to open this perspective It includes several views which can also be used independently and allows to place calls and send SMS to the device It also allow to set the current geo position and to perform a performance trace of your application 17.2 LogCat View You can see the log (including System.out.print() statements) via the LogCat view 17.3 File explorer The file explorer allows to see the files on the android simulator 18 Shell 18.1 Android Debugging Bridge - Shell You can access your Android emulator also via the console Open a shell, switch to your "androidsdk" installation directory into the folder "tools" Start the shell via the following command "adb shell" adb shell You can also copy file from and to your device via the following commands // Assume the gesture file exists on your Android device adb pull /sdcard/gestures ~/test // Now copy it back adb push ~/test/gesture /sdcard/gestures2 This will connect you to your device and give you Linux command line access to the underlying file system, e.g ls, rm, mkdir, etc The application data is stored in the directory "/data/data/package_of_your_app" If you have several devices running you can issue commands to one individual device # Lists all devices adb devices #Result List of devices attached emulator-5554 attached emulator-5555 attached # Issue a command to a specific device adb -s emulator-5554 shell 18.2 Uninstall an application via adb You can uninstall an android application via the shell Switch the the data/app directory (cd /data/app) and simply delete your android application You can also uninstall an app via adb with the package name adb uninstall 18.3 Emulator Console via telnet Alternatively to adb you can also use telnet to connect to the device This allows you to simulate certain things, e.g incoming call, change the network "stability", set your current geocodes, etc Use "telnet localhost 5554" to conntect to your simulated device To exit the console session, use the command "quit" or "exit" For example to change the power settings of your phone, to receive an sms and to get an incoming call make the following # connects to device telnet localhost 5554 # set the power level power status full power status charging # make a call to the device gsm call 012041293123 # send a sms to the device sms send 12345 Will be home soon sms send 12345 Will be home soon # set the geo location geo fix 48 51 For more information on the emulator console please see Emulator Console manual 19 Deploy your application on a real device Turn on "USB Debugging" on your device in the settings Select in the settings Applications > Development, then enable USB debugging You also need to install the driver for your mobile phone For details please see Developing on a Device Please note that the Android version you are developing for must be the installed version on your phone To select your phone, select the "Run Configurations", select "Manual" selection and select your device 20 Thank you Please help me to support this article: 21 Questions and Discussion Before posting questions, please see the vogella FAQ If you have questions or find an error in this article please use the www.vogella.de Google Group I have created a short list how to create good questions which might also help you 22 Links and Literature 22.1 Source Code Source Code of Examples 22.2 Android Resources Android (German Book) Android ListView and ListActivity Android SQlite Database Android Widgets Android Live Wallpaper Android Services Android Location API and Google Maps Android Intents Android and Networking Android Homepage Android Developer Homepage Android Issues / Bugs Android Google Groups Android Live Folder 22.3 vogella Resources Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel Android Tutorial Introduction to Android Programming GWT Tutorial Program in Java and compile to JavaScript and HTML Eclipse RCP Tutorial Create native applications in Java JUnit Tutorial Test your application Git Tutorial Put everything you have under distributed version control system

Ngày đăng: 14/12/2016, 10:25

Tài liệu cùng người dùng

Tài liệu liên quan