Download Android App Development

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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
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
Services
handle background processing associated with an
application
Broadcast Receivers
handle communication between Android OS and
applications.
Content Providers
handle data and database management issues
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)
• 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
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
• 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. I have created a simple XML layout using
FrameLayout that shows how this works.
• 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.
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
Packages which can be used
1. All JDK packages, except
2. Android specific packages
• 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.
Android Widgets
There are given a lot of android widgets with simplified examples such as Button,
TextView, EditText, AutoCompleteTextView, ToggleButton, DatePicker, TimePicker,
ProgressBar etc.
Android widgets are easy to learn. The widely used android widgets with examples
are given below:
Android ButtonLet's learn how to perform event handling on button click.
Android 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.
AutoCompleteTextViewLet's see the simple example of AutoCompleteTextView.
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 xml file good practice
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
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.
•
•
•
•
•
•
•
•
•
•
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.
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.
•
•
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>
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 no 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");
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