Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Android App Development Android Architecture Linux kernel Libraries Android Runtime Application Framework Applications Application Components Activities Services Broadcast Receivers Content Providers Additional Components Hello World Example Create Android Application Anatomy of Android Application The Main Activity File The Manifest File The Strings File The R File The Layout File Running the Application Accessing Resources ACCESSING RESOURCES IN CODE ACCESSING RESOURCES IN XML Activities Services Broadcast Recievers Creating the Broadcast Receiver Registering Broadcast Receiver Broadcasting Custom Intents Content Providers Content URIs Create Content Provider Fragments Fragment Life Cycle How to use Fragments? Example Intents and Filters Intent Objects ACTION Android Layout Types Linear Layout RelativeLayout GridView UI Controls Android UI Controls TextView TextView Attributes EditText EditText Attributes AutoCompleteTextView AutoCompleteTextView Attributes Button Button Attributes ImageButton ImageButton Attributes CheckBox CheckBox Attributes ToggleButton ToggleButton Attributes WebView Menus Android Database, SQLite Sockets & How App can interact with server Custom Titlebar Portrait and Landscape Screens GPS & LocationListener, Bluetooth Nested Layouts Layouts and resources fitting different Screen sizes Capture Swipe gestures Launch Screen How to launch Activity of other Apps AlarmManager Threading Notifications How to upload your app to Google Play and steps involved Examples will be shown on Real Device / Emulator Practical Classes Sample Project Work guidance Android Platform Architecture Java C/C++ Below are the Software Tools required to develop an Android App 1. JDK & JRE 2. Android SDK 3.IDE(Integrated Development Kit) like IntelliJ, Android Studio, Eclipse. 4.To connect IDE to your device, your Device specific drivers are required. Activity Life Cycle Activity Life Cycle call backs • onCreate()This is the first callback and called when the activity is first created. • onStart()This callback is called when the activity becomes visible to the user. • onResume()This is called when the user starts interacting with the application. • onPause()The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. • onStop()This callback is called when the activity is no longer visible. • onDestroy()This callback is called before the activity is destroyed by the system. • onRestart()This callback is called when the activity restarts after stopping it. XML Layouts • Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses. • Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically. Building & running Android app Components of Android App App Component Purpose Activities UI and handle the user interaction to the smartphone screen(Generally each Screen of an App is an Activity) Services handle background processing associated with an application(For eg. Downloading or uploading to network) Broadcast Receivers handle communication between Android OS and applications. (For eg. Battery low notification from Android to Apps) Content Providers handle data and database management issues (to store Contacts, SMS, etc…) Anatomy of Android App An android App consists of • Source Code(.java files) to handle events of Activity, Service, etc… • Layouts(xml files) to display Activity • Resources(images, Strings) [optional] • Android Manifest XML file(AndroidManifest.xml) App Manifest Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code. This manifest file has below details of App • List of Activity classes • List of Service classes • BroadcastReceivers • Permissions, for eg. Using Network, read/write SMS,etc… • Also specifies Android Platform API compatibility. App cannot be installed if underlying device has incompatible API level with that of AndroidManifest file. Specifying above details in Manifest file is mandatory, if you miss any details, it throws an Exception, during runtime, and does not execute related functionality. Android Application Components Activity: Each screen is an Activity in Android App. For eg. An E-mail App, can have one Activity for inbox, another Activity for Sent mails, another Activity for Settings,etc… An Activity should be a sub class of Activity class. Service: A service is a component that runs in the background to perform long-running operations. For example uploading or downloading huge file. A Service should be a sub class of Service class. Intent: Intent can be defined as a simple message objects which is used to communicate from 1 activity to another. Intents define intention of an Application . They are also used to transfer data between activities. Broadcast Receiver: A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. A broadcast receiver is implemented as a subclass of BroadcastReceiver Support for different Screen sizes and Resolution As known different Android devices have screens with different width and height, screen resolutions, dpi, etc… An Android application need to consider this, to provide best User Experience to the users. Below are the folders provided • • • • • px Pixels - point per scale corresponds to actual pixels on the screen. in Inches - based on the physical size of the screen. mm Millimeters - based on the physical size of the screen. pt Points - 1/72 of an inch based on the physical size of the screen. dp Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp". • sp Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference. Lets take an example of two screens that are the same physical size but one has a screen density of 160 dpi (dots per inch, i.e. pixels per inch) and the other is 240 dpi. What is a Layout? A Layout is used to arrange Views/Widgets(like TextView, EditText, etc…) on a screen. Below are different possible Layouts in Android. LinearLayout FrameLayout TableLayout AbsoluteLayout AbsoluteLayout • AbsoluteLayout is based on the simple idea of placing each control at an absolute position. You specify the exact x and y coordinates on the screen for each control. This is not recommended for most UI development (in fact AbsoluteLayout is currently deprecated) since absolutely positioning every element on the screen makes an inflexible UI that is much more difficult to maintain. Consider what happens if a control needs to be added to the UI. You would have to change the position of every single element that is shifted by the new control. • FrameLayout • FrameLayout is designed to display a single item at a time. You can have multiple elements within a FrameLayout but each element will be positioned based on the top left of the screen. Elements that overlap will be displayed overlapping. • FrameLayout can become more useful when elements are hidden and displayed programmatically. You can use the attribute android:visibility in the XML to hide specific elements. You can call setVisibility from the code to accomplish the same thing. • The three available visibility values are visible, invisible (does not display, but still takes up space in the layout), and gone (does not display, and does not take space in the layout). • LinearLayout • LinearLayout organizes elements along a single line. You specify whether that line is verticle or horizontal using android:orientation in Layout XML file. Nested Layouts: Layout within a Layout. Nested Layouts are valid • TableLayout • TableLayout organizes content into rows and columns. The rows are defined in the layout XML, and the columns are determined automatically by Android. This is done by creating at least one column for each element. So, for example, if you had a row with two elements and a row with five elements then you would have a layout with two rows and five columns. • You can specify that an element should occupy more than one column using android:layout_span. This can increase the total column count as well, so if we have a row with two elements and each element has android:layout_span=”3″ then you will have at least six columns in your table. • By default, Android places each element in the first unused column in the row. You can, however, specify the column an element should occupy using android:layout_column • RelativeLayout • RelativeLayout displays child views in relative positions. The position of each view can be specified as relative to sibling elements (such as to the left-of or below another view) or in positions relative to the parent RelativeLayout area (such as aligned to the bottom, left or center). • RelativeLayout • RelativeLayout displays child views in relative positions. The position of each view can be specified as relative to sibling elements (such as to the left-of or below another view) or in positions relative to the parent RelativeLayout area (such as aligned to the bottom, left or center). Packages which can be used 1. All Java Standard packages, except 2. Android specific packages. Below are android specific packages available for all Android apps import android.app.Activity; import android.content.*; import android.os.*; import android.util.Log; import android.view.*; import android.widget.*; • A radio button is a two-states button that can be either checked or unchecked. When the radio button is unchecked, the user can press or click it to check it. A radio button cannot be unchecked by the user once checked. Radio buttons are normally used together in a RadioGroup. When several radio buttons live inside a radio group, checking one radio button unchecks all the others. RadioGroup is used to create a multiple-exclusion scope for a set of radio buttons. Checking one radio button that belongs to a radio group unchecks any previously checked radio button within the same group. Intially, all of the radio buttons are unchecked. While it is not possible to uncheck a particular radio button, the radio group can be cleared to remove the checked state. • AlertDialog: Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It is used to get confirmation from the user, before performing an action, like deleting a message, etc… An AlertDialog has Title part, Message part and action Buttons. • WebView: This Widget is used to render and display HTML content. HTML content can be either given directly or can be loaded from an online URL. • Menu: Menu gets displayed with multiple options, to let user select one of them. Menu gets displayed when the menu hard button(provided with most of Android Mobile devices) is selected by user. To provide Menu, below methods need to be overridden by your Activity onCreateOptionsMenu(Menu menu):This method need to be overridden, to specify menu options onOptionsItemSelected(MenuItem item):This method gets called, when the user selects an item from the menu Android Widgets Below are most commonly used android widgets ButtonLet's learn how to perform event handling on button click. ToastDisplays information for the short duration of time. ToggleButtonIt has two states ON/OFF. CheckBoxLet's see the application of simple food ordering. AlertDialogAlertDialog displays a alert dialog containing the message with OK and Cancel buttons. SpinnerSpinner displays the multiple options, but only one can be selected at a time. AutoCompleteTextView Using this widget it is possible to automatically fill the content, by entering one or more characters RatingBarRatingBar displays the rating bar. DatePickerDatepicker displays the datepicker dialog that can be used to pick the date. TimePickerTimePicker displays the timepicker dialog that can be used to pick the time. ProgressBarProgressBar displays progress task. Below are XML Attributes, which can be used with any UI widget android:textColor="@android:color/" android:background="@android:color/background_l ight“ String constants All String constants need to be read from strings.xml file For eg. android:text="@string/lst_txt" Hardcoding Strings, directly in source code is not good practice. becoz xml can be changed dynamically, for eg. to support different langs like eng, japanese,etc... in the UI, and source code need not be recompiled Below are the steps to provide Button listener code. Method 1 1. Add Button to XML Layout file 2. implements View.OnClickListener 3. Button btn = (Button)findViewbyId(R.id.btnId); 4. btn.setOnClickListener(this); 5. Provide body for onClick() method. Method 2 1. Add Button to XML Layout file 2. Provide onClick attribute to Button element in Layout file. Eg. android:onClick="btnclick“ 3. Provide body for public void btnClick(View vw) method in Activity java file. Method 3 (by using Inner class) 1. Add Button to XML Layout file. 2. In Activity java file create Anonymous inner class of View.onClickListener, and override onClick() method Notification Difference between Intent and PendingIntent • down voteaccepted • Intent • An Android Intent is an object carrying an intent ie. message from one component to another component with-in the application or outside the application. The intents can communicate messages among any of the three core components of an application - activities, services, and broadcast receivers. • The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed. Notification Flags • A PendingIntent is a token that you give to a foreign application (e.g. NotificationManager, AlarmManager, Home Screen AppWidgetManager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code. • By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself (with the same permissions and identity). As such, you should be careful about how you build the PendingIntent: almost always, for example, the base Intent you supply should have the component name explicitly set to one of your own components, to ensure it is ultimately sent there and nowhere else. Service A service is a component that runs in the background to perform long-running operations without needing to interact with the user and it works even if application is destroyed. A service can essentially take two states − Started : A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Bound : A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). Each Android app may have zero or more Service component, based on the requirement. Each Service in Android App need to have an entry( like below) in AndroidManifest.xml <service android:name=".MyService" /> A service has life cycle callback methods that you can implement to monitor changes in the service's state and you can perform work at the appropriate stage. The following diagram on next slide shows the life cycle when the service is created with startService() and the diagram on the right shows the life cycle when the service is created with bindService() START_STICKY and NOT_STICKY difference Above constants are returned by onStartCommand() call back method of Service. These constants are to tell the android system what action you want to perform when the device memory gets back stable and when it is ready to re launch the services. The simplest explanation of these could be, • START_STICKY- tells the system to create a fresh copy of the service, when sufficient memory is available, after it recovers from low memory. Here you will lose the results that might have computed before. • START_NOT_STICKY- tells the system not to bother to restart the service, even when it has sufficient memory. • START_REDELIVER_INTENT- tells the system to restart the service after the crash and also redeliver the intents that were present at the time of crash. A Service need to have an entry in AndroidManifest.xml Every Service need to inherit from android.app.Service class, and override appropriate life cycle call back methods. To stop a started Service stopService() need to be called from Activity, or stopSelf() need to be called from Service itself Bound Service A bound service is similar to a started service with the exception that a started service does not generally return results or permit interaction with the component that launched it. A bound service, on the other hand, allows the launching component to interact with, and receive results from, the service. An activity might, for example, start a service to handle audio playback. The activity will, in all probability, include a user interface providing controls to the user for the purpose of pausing playback or skipping to the next track. Similarly, the service will quite likely need to communicate information to the calling activity to indicate that the current audio track has completed and to provide details of the next track that is about to start playing. A bound service must include an implementation of the onBind() method which is called both when the service is initially created and when other clients subsequently bind to the running service. The purpose of this method is to return to binding clients an object of type IBinder containing the information needed by the client to communicate with the service. A component (also referred to in this context as a client) starts and binds to a bound service via a call to the bindService() method and multiple components may bind to a service simultaneously. When the service binding is no longer required by a client, a call should be made to the unbindService() method. When the last bound client unbinds from a service, the service will be terminated by the Android runtime system. It is important to keep in mind that a bound service may also be started via call to startService(). Once started, components may then bind to it via bindService() calls. When a bound service is launched via a call to startService() it will continue to run even after the last client unbinds from it. Context • • • • • • • • • • Toast and Intent, both requires reference to context. And getApplication, getApplicationContext,LoginActivity.this and getBaseContext, they all offer reference to the context. Now the thing confuses is the declaration of different contexts and their specific-usage. To make things simple, you should count two types of context available in the Android framework. Application Context Activity Context Application context is attached to the application's life-cycle and will always be same throughout the life of application. So if you are using Toast, you can use application context or even activity context (both) because a toast can be raised from anywhere with in your application and is not attached to a window. Activity context is attached to the Activity's life-cycle and can be destroyed if the activity's onDestroy() is raised. If you want to launch a new activity, you must need to use activity's context in its Intent so that the new launching activity is connected to the current activity (in terms of activity stack). LoginActivity.this though its referring to your own class which extends Activity class but the base class (Activity) also extends Context class, so it can be used to offer activity context. getApplication() though its referring to Application object but the Application class extends Context class, so it can be used to offer application context. getApplicationContext() offers application context. getBaseContext() offers activity context. Storage in Android All Android devices have two file storage areas: "internal" and "external" storage. Built-in non-volatile memory (internal storage), plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into "internal" and "external" partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not. Characteristics of Internal storage: • It's always available. • Files saved here are accessible by only your app by default. • When the user uninstalls your app, the system removes all your app's files from internal storage. • Internal storage is best when you want to be sure that neither the user nor other apps can access your files Characteristics of External storage: • It's not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device. • It's world-readable, so files saved here may be read outside of your control. • When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from getExternalFilesDir(). • External storage is the best place for files that don't require access restrictions and for files that you want to share with other apps or allow the user to access with a computer. • Generally pictures, audio, video files are stored in this area. • • To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file: <manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... </manifest> By default an app can read from files, but to add that explciity, below can be added to Manifest file <manifest ...> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ... </manifest> What are Notifications in Android? Notification Area is the area, which is shown on top of Device screen. An app displays an icon in this Notification Area to indicate that there is a message or Alert, etc…, which needs user attention. User need to slide down this notification Area, to view more details of this, after which user can click on this notification, for further Action like displaying Activity, etc… Below are the steps required, programmatically to show notification, Step 1: Get the NotificationBuilder instance. This is required to set various properties, to the Notification. NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this); Step2: Set various Notification Properties like icon, title, text, etc, to the Notification Builder instance, created in step 1. mBuilder.setSmallIcon(R.drawable.image_name); mBuilder.setContentTitle(“This is Title"); mBuilder.setContentText(“This is Notification Text"); AsyncTask AsyncTask is an abstract class provided by Android which helps to perform time consuming tasks in the background and keeps the UI thread light thus making the application more responsive. • Android application runs on a single thread when launched. Due to this single thread model tasks that take longer time to fetch the response can make the application non-responsive. To avoid this we use AsyncTask to perform time consuming tasks in background on a dedicated thread and passing the results back to the UI thread. Hence use of AsyncTask keeps the UI thread responsive at all times. • Below are the methods in AsyncTask, which need to be overridden 1. doInBackground() : This method contains the code which needs to be executed in background. In this method we can send results multiple times to the UI thread by publishProgress() method. To notify that the background processing has been completed we just need to use the return statements 2. onPreExecute() : This method contains the code which is executed before the background processing starts 3. onPostExecute() : This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method 4. onProgressUpdate() : This method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update the UI thread How to start an AsyncTask • To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask bgrnd= new MyTask(); bgrnd.execute(); • In the above snippet we’ve used a sample class MyTask that extends AsyncTask and execute method is used to start the background thread. Database SQLite is built in database provided with Android. Package which need to be imported to connect to database is android.database. Below is method used to open an existing DB or to create a new DB openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null); Logging in Android Logging is a mechanism to display the flow of execution of an Application, along with Exceptions or problems occurred during execution. Generally Logging is used for debugging purpose. The package which need to be imported for Logging is android.util.Log Log.d(“App or Module Name”, “Example log here"); //debug mode logs Log.e(“App or Module Name”, “Example log here");//error mode logs Log.i(“App or Module Name”, “Example log here");//info mode logs Log.v(“App or Module Name”, “Example log here");//verbose mode logs How to Launch External Apps? Display Activity in Landscape or Portrait Reading and writing from and to files Interacting with database Gestures Launch Camera GPS co ordinates Accessing inbuilt content providers, such as SMS, Book marks, etc… HTTP Networking