1 / 101

Android Basics

Android Basics. Mobile Application Development Selected Topics – CPIT 490. Overview. Review Android Activities Android Intents User Interface / Views User Notifications. Developing for Android. Eclipse Android SDK Android Development Tools (ADT)

garlandg
Télécharger la présentation

Android Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Android Basics Mobile Application Development Selected Topics – CPIT 490

  2. Overview • Review • Android Activities • Android Intents • User Interface / Views • User Notifications

  3. Developing for Android • Eclipse • Android SDK • Android Development Tools (ADT) • Android Virtual Devices (AVD) & SDK Manager • The Android Emulator • Dalvik Debug Monitor Services (DDMS) • The Android Debug Bridge (ADB)

  4. Android Software Stack

  5. Android Project Structure • src/ - Java packages. Each package can have multiple .java files representing different classes. • res/layout/ - XML files that specify the layout of each screen. • main.xml defines the layout of the application. Default view is Layout view. • res/values/ - XML files used as references by other files. • res/drawable-hdpi/ , res/drawable-mdpi/ , and res/drawable-ldpi/ - high, medium, and low dots-per-inch resolution pictures. • res/color, res/menu, res/anim • assets/ - additional non-media files. Assets used by application. Ex. HTML, database, etc • AndroidManifest.xml specifies the project to the Android OS. Permissions and other features are specified here. • Auto-generated files (do not modify): • gen/ contains auto-generated code. Class R.java generated by Android Asset Packaging Tool (aapt).). If you delete R.java, it will auto-generated again. R.java is based on AndroidManifest.xml file. • default.properties contains project settings.

  6. Android Application Components • i) Activity: Activity is a visual screen for interaction of user with the application. Depends upon design, an application may consists of one or more activities • Fragments: "miniature" activities that could be grouped to form an activity • ii) Views: The User interface of an Activities is build with widgets. • iii) Service: Service do not have a visual interface, it runs in the back ground, like play back music and fetching data from the network. • iv) Broadcast Receiver: Broadcast receiver receive broadcast announcements and response to them according to the situation. • v) Content Provider: Content provider is a SQLite database, which supports the sharing and accessing of data among applications. • vi) Intents: Asynchronous messages which allow the application to request functionality from other services or activities. • vii) Others parts are Android widgets / Live Folders and Live Wallpapers.

  7. Android Activity • http://developer.android.com/reference/android/app/Activity • An "activity" is an application component that provides a screen with which users can interact • Activity is usually a single screen • Implemented as a single class extending Activity • Displays user interface controls (views) • Reacts on user input / events • An application typically consists of several activities • Each screen is typically implemented by one activity • Each activity can then start another activity (new screen) • An activity may return a result to the previous activity • "main" activity is presented to the user when launching the application for the first time. • Each activity receives callbacks due to a change in its state during its lifecycle — whether the system is creating it, stopping it, resuming it, or destroying it.

  8. Activity Lifecycle

  9. Activity Lifecycle • Foreground Lifetime is until onPause() • Visible Lifetime is until onStop() • Entire Lifetime is until onDestroy() • Create an activity by extending Activity base class

  10. Activity Example • extends Activity base class • UI from res/layout folder • R.layout.main refers to main.xml • AndroidManifest.xml must declare all activities in the application • @string refers to strings.xml in res/values folder • onCreate() is involved when the activity is loaded

  11. Activity Callbacks • public class Activity extends ApplicationContext { • protected void onCreate(Bundle savedInstanceState); • // Called when the activity is first created. Provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart(). • protected void onStart(); • // Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.  • protected void onRestart(); • // Called after your activity has been stopped, prior to it being started again. Always followed by onStart()

  12. Activity Callbacks • protected void onResume(); • // Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause(). • protected void onPause(); • // Called when the system is about to start resuming a previous activity. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() or onStop(). • protected void onStop(); • // Called when the activity is no longer visible to the user. Followed by either onRestart() if this activity is coming back to interact with user, or onDestroy() if this activity is going away. • protected void onDestroy(); • // The final call you receive before your activity is destroyed. This can happen either because the activity is finishing or someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method. • }

  13. Activity Life cycle • Activity is destroyed when the back button is pressed. So, if you want to preserve the state, we need to store the information before the application is destroyed • onPause() is called when the application is send to background or when the application is killed • onCreate() is invoked when the activity is loaded for the first time • onStart() and onResume() are invoked when an activity is started, either from background or newly started • Use the onCreate() method to create and instantiate the objects that you will be using in your application • Use the onResume() method to start any services or code that needs to run while your activity is in the foreground. • Use the onPause() method to stop any services or code that does not need to run when your activity is not in the foreground. • Use the onDestroy() method to free up resources before your activity is destroyed.

  14. Utilizing Activity Lifecycle Functions • Simple exercise to see the activity lifecycle in action • each overridden function is explicit and a Toast command is added to show on screen when the function is entered • Run it on an Android device and try various cases: • Changing the screen orientation destroys and recreates the activity from scratch. • Pressing the Home button pauses the activity, but does not destroy it. • Pressing the Application icon might start a new instance of the activity, even if the old one was not destroyed. • Letting the screen sleep pauses the activity and the screen awakening resumes it. (This is similar to taking an incoming phone call.)

  15. Activity Lifecycle Samples • Turn Display • onCreate(null) -> onStart -> onResume() -> [Turn Display] > onSaveInstanceState() -> onPause() -> onStop() -> onDestroy() -> onCreate() -> onStart() -> onRestoreInstanceState() -> onResume() • Home • onCreate(null) -> onStart -> onResume() -> [Home Button] > onSaveInstanceState() -> onPause() -> onStop() -> [Start App] > onRestart() -> onStart() -> onResume() • Phone Call Interrupt • onCreate(null) -> onStart -> onResume() -> [Phone Call] > onSaveInstanceState() -> onPause() -> onStop() -> [Hang Up or press Back] > onRestart() -> onStart() -> onResume()

  16. Notes on Activity • Starting Activity: • void startActivity (Intent intent) • void startActivityForResult (Intent intent, intrequestCode) • void onActivityResult (intrequestCode, intresultCode, Intent data) • Shutting Down Activity: • void finish () • void finishActivity (intrequestCode) • Saving Activity Status • void onSaveInstanceState (Bundle outState) • void onRestoreInstanceState (Bundle savedInstanceState) • Activity A starts Activity B: • A's onPause() • B's onCreate() , onStart() , and onResume() (Activity B now has user focus.) • A’s onStop() , if A is no longer visible

  17. Starting Activity

  18. Saving Activity’s State

  19. Back Stack Tasks and Activities Multiple Activity Instances Multiple Tasks

  20. Activity and AndroidManifest.xml • Any new activity must be defined in AndroidManifest.xml file

  21. AndroidManifest.xml and main.xml • versionCode: used to indicate the version number of the application • versionNumber: Represented as <major>.<minor> version numbers. This is displayed to the user • Minimum, target and maximum SDK versions are specified here • Icon of the application is provided via @drawable, which refers to the res/drawable folder • The name of the main activity is provided. Also, the package name is provided • android.intent.action.MAIN means that the current activity is the first activity that will be loaded when the application runs • Under intent-filter <action android:name="a.b.c.d" /> means this specific activity could be invoked using a.b.c.d as the name • android:windowSoftInputMode="stateHidden" is used to disable soft keyboard from appearing automatically for EditText • main.xml • android:onClick="onClick" is used to say which method to call when the view is clicked. The one in the quotes indicate the name of the method. This method is to be implemented in the java program.

  22. Notes on Activity Contd… • Killing an activity does not remove the application from memory, even if the application has only one activity • Context class is used to provide references to your application. Activity class is a subclass of Context class. • To draw progress dialogs, you could use progressDialog class. • Applying dialog themes to an activity (in AndroidManifest.xml) (BAAD Pg 41) • android:theme="@android:style/Theme.Dialog"> • Hides a feature (in *.java file) – Hide the title based on a state (BAAD Pg 42) • import android.view.Window; • //---hides the title bar--- • requestWindowFeature(Window.FEATURE_NO_TITLE); • Dialog box (BAAD Pg 42) • Creating multiple activities and linking them using Intent (BAAD Pg 54) • Passing parameters through intents (BAAD Pg 63)

  23. Intents • http://developer.android.com/reference/android/content/Intent.html • Intents are used as a message-passing mechanism within your application and between applications. Intents are used to call built-in applications like Map, Browser, etc. • Explicit start Activity/Service using its class name • Start Activity/Service for an action with specific data • Broadcast that an event has occurred • Consists of • Component name (name of component/activity to handle the intent) • Action to be performed (MAIN / VIEW / EDIT / PICK / DELETE) • Data to act on (expressed as URI) or Bundle • Categories • Extras (primitives / Strings / Serializable) • Flags

  24. Component Name Field • Specifies the name of the component (name of the activity if the component is activity) that should handle the intent • Class name of the target component (for example "FirstActivity") • <activity android:name =".FirstActivity" android:labe l="@string/app_name"> • <intent-filter > • <action android:name = "edu.odu.examples.IntentActivity" /> • <category android:name = "android.intent.category.LAUNCHER" /> • </intent-filter > • </activity > • Setting component name is optional • Explicit Intent: If it is set, the Intent object is delivered to an instance of the designated class. • Intent intent = new Intent (this, FirstActivity.class); • Implicit Intent: If it is not set, Android uses other information (i.e., action field) in the Intent object to locate a suitable target - this is called "intent resolution" • Intent intent = new Intent ("edu.odu.examples.IntentActivity");

  25. Launching Activity • Intent Invocation • Launch new activity (without receiving a result) • Launch new activity and expect result • requestCode is simply an integer value that identifies an activity you are calling. This is to used to identify the activity that returns • For example, you may be calling multiple activities at the same time, and some activities may not return immediately (for example, waiting for a reply from a server) • requestCode of -1 is like startActivity(intent) • When activity exits, onActivityResult() method is called with given requestCode (int > 0) • onActivityResult(intrequestCode, intresultCode, Intent result)

  26. Intents and Intent Filters • Intent Filters • Description of what intents an activity can handle • Activities publish their intent filters in a manifest file • <intent-filter > • <action android:name="android.intent.action.VIEW"/> • <category android:name="android.intent.category.DEFAULT"/> • <category android:name="android.intent.category.BROWSABLE"/> • <data android:scheme="geo"/> • </intent-filter> • Upon invocation of startActivity(intent) the system looks at the intent filters of all installed applications • Candidate activity that owns the filter must pass matching tests for action, category, and data fields • http://developer.android.com/guide/topics/intents/intents-filters.html

  27. .MAIN Action & .LAUNCHER Category • Activities that can initiate applications have filters with "android.intent.action.MAIN" specified as the action • This is a way an application gets started fresh, without a reference to any particular data. • If they are to be represented in the application launcher, they also specify the "android.intent.category.LAUNCHER" category: • <intent-filter . . . > • <action android:name="code android.intent.action.MAIN" /> • <category android:name="code android.intent.category.LAUNCHER" /> • </intent-filter> • The Android system populates the application launcher by finding all the activities with intent filters that specify the "android.intent.action.MAIN" action and "android.intent.category.LAUNCHER" category. It then displays the icons and labels of those activities in the launcher.

  28. Action Field • In Android, intents usually come in pairs: action and data. The action describes what is to be performed, such as editing an item, viewing the content of an item, and so on. The data specifies what is affected, such as a person in the Contacts database. The data is specified as an Uri object. • Intent Resolution: Android OS looks for the activities which could satisfy the given request. For ex., when we specify Intent i = new Intent("android.intent.action.VIEW"); the appropriate activity should be used to view. • A string naming the action to be performed • The Intent class defines a number of predefined action constants, including • ACTION_CALL, ACTION_EDIT, ACTION_MAIN, ACTION_SYNC, ACTION_BATTERY_LOW, etc. • You can also define your own action strings for activating the components in your application • The action largely determines how the rest of the intent is structured - particularly the data and extras fields - much as a method name determines a set of arguments and a return value.

  29. Intent Actions • Note that Actions’ "Constant" could be replaced with an equivalent String constant. • e.g.,: ACTION_CALL = "android.intent.action.CALL"

  30. Data Field • The URI of the data to be acted on and the MIME type of that data. Use Uri.parse to convert string to an uri object • Different actions are paired with different kinds of data specifications. • If the action field is ACTION_EDIT, the data field would contain the URI of the document to be displayed for editing. • If the action is ACTION_CALL, the data field would be a tel: URI with the number to call. • If the action is ACTION_VIEW and the data field is an http: URI, the receiving activity would be called upon to download and display whatever data the URI refers to. • Examples of Action/Data Pairs • ACTION_VIEW content://contacts/people/ -- Display a list of people to browse through. • ACTION_VIEW content://contacts/people/1 – Display information about person whose id is "1". • ACTION_DIAL content://contacts/people/1 – Display the phone dialer with the person filled in. • ACTION_VIEW tel:123 -- Display the phone dialer with the given number filled in. • ACTION_DIAL tel:123 -- Dial the phone dialer with the given number filled in.

  31. Example of Actions • Starting Activity: • void startActivity (Intent intent) • Intent i = new Intent (this, OtherActivity.class); • startActivity(i); • void startActivityForResult (Intent intent, intrequestCode) • void onActivityResult (intrequestCode, intresultCode, Intent data) • Shutting Down Activity: • void finish() • Intent intent = new Intent (this, FirstActivity.class); • startActivity (intent);

  32. Notes on Activity and Intents • use the putExtra() method of an Intent object to add a name/value pair • Two parameters in putExtra(): one of type string and one of type integer • you can also create a Bundle object and then attach it using the putExtras() method • getIntent() method is used to get Intent object • When a fragment is being created, it goes through the following states: onAttach(), onCreate(), onCreateView(), onActivityCreated() • When the fragment becomes visible, it goes through these states: onStart(), onResume() • When the fragment goes into the background mode, it goes through these states: onPause(), onStop() • When the fragment is destroyed (when the activity it is currently hosted in is destroyed), it goes through the following states: onPause(), onStop(), onDestroyView(), onDestroy(), onDetach() • Like activities, you can restore an instance of a fragment using a Bundle object, in the following states: onCreate(), onCreateView(), onActivityCreated()

  33. Notes on Activity and Intents • onAttached() — Called when the fragment has been associated with the activity • onCreateView() — Called to create the view for the fragment • onActivityCreated() — Called when the activity’s onCreate() method has been returned • onDestroyView() — Called when the fragment’s view is being removed • onDetach() — Called when the fragment is detached from the activity • <category android:name="android.intent.category.DEFAULT" /> should be used if you want an activity to be invoked by others • Intents can be specified with categories in AndrodManifest.xml file. You could specify the category in the code using addCategory(). If no category is specified in the java code, the DEFAULT category is invoked. If the category specified in the java code is not matched, then a runtime exception is generated and the activity will not be started • Creating multiple activities and linking them using Intent (BAAD Pg 54) • Passing parameters through intents (BAAD Pg 63)

  34. Notes on Activity and Intents • Using intents to start a second activity • Remember to add new Activity(s) to AndroidManifest.xml ! • Intent intent = new Intent(Context packageContext, Class<?> class); • packageContext = the activity we’re coming from • Class: the Activity in our app we’re going to • Intent intent = new Intent(this, AnotherActivity.class); • startActivity(i); • Requesting and starting another application’s activity • Intent intent = new Intent(<action>, <data>); • ACTION_VIEW, ACTION_EDIT, ACTION_DIAL • scheme://host/data/segments • Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(“tel:1234567890”));

  35. Notes on Activity and Intents • Activity Results • startActivityForResult(intent) allows us to “return” data to the calling Activity • onActivityResult(int requestCode, int resultCode, Intent data); • requestCode: unique integer to determine what Activity returned • resultCode: RESULT_OK, RESULT_CANCELED • data: Intent to receive additional data • setResult(int resultCode, Intent data); • resultCode: RESULT_OK, RESULT_CANCELED • data: Intent to pass additional data • finish() pops from stack and sends control back to previous Activity

  36. Notes on Activity and Intents • Bundle objects store key and value pairs via the put<type> methods and get<type> methods • Basic data types: boolean, byte, char, double, float, int, long, etc. • Non-primitives: String, Serializable, Arrays • Can get size() and keySet() • intent.putExtras(Bundle bundle); • Associate a bundle with an intent • getIntent().getExtras(); • Get bundle associated with an intent • intent.putExtra(String key, value); • intent.getExtra(String key);

  37. Fragments • Fragments are mini-activities • Fragments contain views as like Activities • Fragments are contained within an activity. Fragments could be dynamically added or removed from the activity • the FragmentManager class is used to add fragments to an activity. • the FragmentTransaction class is used to perform fragment transactions in your activity (such as add, remove or replace) • the WindowManager to determine whether the device is currently in portrait mode or landscape mode • android.R.id.content refers to the content view of the activity • commit() method is to make changes to effect • Add frames at run-time (BAAD Pg 74) • When an activity goes background, it is moved to back state automatically. For fragments, moving to back state has to be done usingaddToBackStack(). • Call inbuilt applications using Intent (BAAD Pg 85)

  38. Fragments • Three subclasses of fragments: ListFragment, DialogFragment, and PreferenceFragment • A list fragment is a fragment that contains a ListView, displaying a list of items from a data source such as an array or a Cursor • In the onCreate() event, you use the setListAdapter() method to programmatically fill the ListView with the content of the array • The ArrayAdapter object manages the array of strings that will be displayed by the ListView

  39. User Interfaces and Views • Views are loaded from res/layout/main.xml file in the onCreate() method handler in your Activity class, using the setContentView() method of the Activity class • Sometimes, you need to code the views in the java code itself because you need to generate the views at runtime. Ex. Games • http://developer.android.com/guide/topics/ui/index.html • Views and View Groups • Views (Widgets) • Layouts • Events • Menus • Dialogs • Styles and themes

  40. Fundamental UI Design • Views • Visual interface element (controls or widgets) • A view derives from the base class android.view.View • ViewGroup • Contains multiple widgets. Layouts inherit the ViewGroup class. Ex LinearLayout, AbsoluteLayout (deprecated), TableLayout, FrameLayout, etc • A ViewGroup derives from the base class android.view.ViewGroup • Activities • Screen being displayed to the user. • Assign a View or layout to an Activity

  41. Layouts • http://developer.android.com/guide/topics/ui/declaring-layout.html • Layout contains Views • FrameLayout • Each child view is in reference to the top left corner. Use if only one View in screen at a time. • LinearLayout • Views in line, either vertically or horizontally. Single column or single row. Elements appear in order they are specified in the file • RelativeLayout • Define positions of each other child view relative to each other and screen boundaries • TableLayout • Rows and Columns • Web View • Display web pages

  42. Layout Examples Grid Layout Tab Layout Linear Layout Relative Layout dp or dip — Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen. Recommended for layout dimensions. sp — Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes. pt — Point. A point is defined to be 1/72 of an inch, based on the physical screen size. px — Pixel. Corresponds to actual pixels on the screen. Not recommended.

  43. Android Specifications • Nexus S has a 4-inch screen (diagonally), with a screen width of 2.04 inches. Its resolution is 480 (width) 800 (height) pixels. With 480 pixels spread across a width of 2.04 inches, the result is a pixel density of about 235 dots per inch (dpi). The pixel density of a screen varies according to screen size and resolution. • Android defines and recognizes four screen densities: • Low density (ldpi) — 120 dpi • Medium density (mdpi) — 160 dpi • High density (hdpi) — 240 dpi • Extra High density (xhdpi) — 320 dpi • Nexus S is in hdpi as its dpi is close to 240 dpi. • Actual pixels = dp * (dpi / 160), where dpi is either 120, 160, 240, or 320.

  44. Defining Layout • Using the dpunit ensures that your views are always displayed in the right proportion regardless of the screen density • Portrait mode: • res/layout/main.xml • Landscape mode: • res/layout-land/main.xml • The default orientation layout is horizontal • Each Activity can have it's own layout

  45. Handling Orientation Changes • Anchoring • Anchor your views to the corners (edges of the screen) • Achieved using RelativeLayout using options like • android:layout_alignParentTop="true" • android:layout_alignParentRight="true" • Resizing and repositioning • Resizing every view according to the orientation • Write two main.xml files. One in res/layout folder and the other in res/layout-land folder • Changing orientation kills an activity and recreates it. Only views that are named with android:id will persist orientation changes • When an activity is killed, onPause() and onSaveInstanceState() methods are invoked • Unlike the onPause() method, the onSaveInstanceState() method is not fired when an activity is being unloaded from the stack (such as when the user pressed the back button), because there is no need to restore its state later • Preserve the state of your activity, such as using a database, internal or external file storage, and so on

  46. Handling Orientation Changes • Easier way to save state: onSaveInstanceState() method provides a Bundle object as an argument so that you can use it to save your activity’s state • Information can only be saved in Bundle object and thus complex data structures cannot be stored • @Override • public void onSaveInstanceState(Bundle outState) { • //---save whatever you need to persist--- • outState.putString(“ID”, “1234567890”); • super.onSaveInstanceState(outState); • } • @ Override • public void onRestoreInstanceState(Bundle savedInstanceState) { • super.onRestoreInstanceState(savedInstanceState); • //---retrieve the information persisted earlier--- • String ID = savedInstanceState.getString(“ID”); • }

  47. Handling Orientation Changes • onRetainNonConfigurationInstance() method is fired when an activity is about to be destroyed due to a configuration change (such as a change in screen orientation, keyboard availability, etc.) • @Override • public Object onRetainNonConfigurationInstance() { • //---save whatever you want here; it takes in an Object type--- • return(“Some text to preserve”); • } • To extract the saved data, you can extract it in the onCreate() method, using the getLastNonConfigurationInstance() method: • @Override • public void onCreate(Bundle savedInstanceState) { • super.onCreate(savedInstanceState); • setContentView(R.layout.main); • Log.d(“StateInfo”, “onCreate”); • String str = (String) getLastNonConfigurationInstance(); • }

  48. Detecting Orientation Changes • Use WindowManager class • //---get the current display info--- • WindowManagerwm = getWindowManager(); • Display d = wm.getDefaultDisplay(); • if (d.getWidth() > d.getHeight()) { • //---landscape mode--- • Log.d(“Orientation”, “Landscape mode”); • } • else { • //---portrait mode--- • Log.d(“Orientation”, “Portrait mode”); • } • Also, you could add android:screenOrientation=”landscape” to activity in AndroidManifest.xml • If you wish to keep your application displayed in certain orientation, specify the below in onCreate() • //---change to landscape mode--- • setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); • For Portrait: ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

  49. Example of Layout • fill_parent fills the entire width or height of the parent • wrap_content make the width or height to the content

  50. Common Attributes • Refresh your Java programming The layout_gravity attribute indicates the positions the views should gravitate towards, while the layout_weight attribute specifies the distribution of available space

More Related