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
HackFest of Android Application
Development
- Md. Nazmul Hoq Salim
Why called HackFest ???
A hackfest (also known as a hack day, hackathon or codefest) is an event in which computer programmers and others involved in software
development and hardware development, including graphic designers, interface designers and project managers, collaborate intensively
on software projects.
The word "hackathon" is a portmanteau (combination) of the words "hack" and "marathon", where "hack" is used in the sense of exploratory
programming, not its alternate meaning as a reference to computer crime.
wiki
Objective & Outline
This will provides an introduction to developing applications for the Android mobile platform. It is divided into 3 parts  Introduction to Android
 Design in Android
 Deployment or Interaction in Android
Materials
What is Android ???
•
•
mobile operating system developed by Open Handset Alliance,
led by Google
– originally purchased from Android, Inc. in 2005
runs on phones, tablets, watches, TVs, etc (Google claims 900,000 Android device
activations )
•
based on Java (dev language) and Linux (kernel)
•
the #1 mobile OS worldwide (52% of U.S. smartphone market )
– and now #1 overall OS worldwide!
•
has over 1 million apps published in Play Store
•
code is released as open source (periodically)
– easier to customize, license, pirate, etc. than iOS
Android version history (link)
Development Requirements
•Java(JDK) - to write Java (and Android) programs
Do not install Java Runtime Environment (JRE). JDK and JRE are different!
Can download the JDK for your OS at http://java.oracle.com
•Android SDK - (download Android SDK from http://developer.android.com)
-
Simplest: download and install Android Studio bundle (including Android SDK) for your OS
-
Alternatives:
-Download/install Eclipse
–Install Android SDK tools by themselves, then install ADT for Eclipse separately (from this site)
We’ll use Android Studio with SDK included •download Android SDK from http://developer.android.com
-
Download & Install Android Studio(link)
•Google's official Android IDE, in v1.0 as of
November 2014
– replaces previous Eclipse-based
environment
– based on IntelliJ IDEA editor; free
to download and use
SDK Manager (Configure AS)
This is found by clicking the following icon in the top toolbar:
Contains
•
•
•
•
Class Library,
Developer Tools
Emulator and System
Images
Documentation and Sample
Code
Virtual Devices (AVDs)
•
allows you to run your project in an emulator
– a software simulation of an entire Android tablet, phone, watch
– when you click the "Run" button in Android Studio. it builds your app, installs it
on the virtual device, and loads it
•
must set up virtual device first in Android Studio - to test and rup apps
•
alternative: install your ap on your actual Android device!
– pro: app will run faster, better test of real execution
– con: requires Android device, must be plugged into dev PC
App build process
Project structure in Android Studio (link)
AndroidManifest.xml (overall project config and settings)
-specifies:
–App’s Activities, Services, etc.
–Permissions requested by app
–Hardware features required, e.g., camera with autofocus
–External libraries to which app is linked, e.g., Google Maps
src/java/…
- source code for your Java classes
res/... = resource files (many are XML)
- drawable/ = images
- layout/ = descriptions of GUI layout
- menu/ = overall app menu options
- values/ = constant values and arrays
- strings = localization data
- styles = general appearance styling
Gradle
- a build/compile management system
- build.gradle = main build config file
Creating a new project (link)
•Creating Android app project in Android Studio:
–Go to File→New Project
–Enter app, project name
–Choose package name using “reverse URL” notation, e.g.,
edu.osu.myapp
–Select APIs for app, then click Next
Creating a new project
•Determine what kind of Activity to create; then
click Next
–We’ll choose a Blank Activity for simplicity
•Enter information about your Activity, then click
Finish
•This creates a “Hello World” app
Application Building Blocks
Activity: A “single screen” that’s visible to user
- can Be faceless, Be in a floating window, Return a value
Service: Long-running Faceless background “part” of app (not separate process or thread)
- E.g. music player, network download etc…
ContentProvider: Manages app data (usually stored in database) and data access for queries
- Enables sharing of data across applications, Provide APIs for querying, insert, update, delete
BroadcastReceiver: Component that listens for particular Android system “events” (broadcast ‘Intents’), e.g., “found wireless device”, and
responds accordingly
- Way to respond to external notification or alarms
DESIGN ANDROID APPS Let's start from designing of an app that
we want to create and then learn the necessary skills to
build that app. We will create a app that will show us
JELA BATAYON
Designing a user interface
- open XML file for your layout (e.g. activity_main.xml)
- drag widgets from left Palette to the preview image
- set their properties in lower-right Properties panel
XML: a language for describing
hierarchical text data.
– Uses tags that consist of elements and
attributes. Tags can be nested.
– Some tags are opened and closed; others
self-close.
– Used to define some of the resourcesLayouts (UI), Strings, Manifest file etc
Example: * XML is case-sensitive!
<!-- this is a comment →
<course name="CS 193A">
<instructor>M</instructor>
<ta>none</ta>
</course>
Android widgets (link)
Widget box model
Layout (link)
How does the programmer specify where each component
appears, how big each component should be, etc.?
A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways:
Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and
subclasses, such as those for widgets and layouts.
Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties)
programmatically.
Layout managers (Java, Android):
– Objects that decide where to position each component based on some general rules or criteria.
– More flexible and general; works better with a variety of devices.
Layout can be nested - a layout could be declared inside another layout.
LinearLayout (link)
Dispose views on a single row or column, depending on
android:layout_orientation
orientation is one of HORIZONTAL (default) or VERTICAL
items do not wrap if they reach edge of screen!
Has two other attributes:
- gravity
- alignment direction that widgets are pulled
- set gravity on the layout to adjust all widgets; set
layout_gravity on an individual widget
weight - gives elements relative sizes by integers
Horizontal
Vertical
LinearLayout example
<LinearLayout …
android:orientation="vertical"
android:gravity="center|right">
<Button ... android:text="Button 1" />
<Button ... android:text="Button 2 Hooray" />
<Button ... android:text="Button 3" />
<Button ... android:text="Button 4 Lon Text" />
<Button ... android:text="Button 5"
android:layout_gravity="left" />
</LinearLayout>
Relative Layout
Disposes views according to the container or according to other views
•
relative to "parent" (the activity itself)
- layout_alignParentTop, Bottom, Left, Right (set these to the ID of another widget in the format
"@id/theID")
•
relative to other widgets/views
- layout_below, above, toLeftOf, toRightOf (et these flags to a boolean value of "true" to enable them)
- layout_centerHorizontal, Vertical, InParent
Useful to align views
intended to reduce the need for nested layouts
RelativeLayout example
Frame Layout
WebView (link)
- If you want to deliver a web application (or just a web page) as a part of a client application, you can do
it using WebView.
•To add a WebView to your Application, simply include the <WebView> element in your activity
layout. For example, here's a layout file in which the WebView fills the screen:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
•To load a web page in the WebView, use loadUrl(). For example:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
Nested layout
to produce more complicated appearance, use a nested layout
– (layouts inside layouts)
what layout(s) are used to create the appearance at right?
– overall activity: __________
– internal layouts: _________
Displaying Toasts
A "Toast" is a pop-up message that appears for a short tim
Useful for displaying short updates in response to events.
Should not be relied upon extensively for important info.
Toast.makeText(this,"This is the Toast message", duration).show();
– where duration is Toast.LENGTH_SHORT or LENGTH_LONG
Deployment
Deployment of Android Application
•
Android application written in Java
•
No single entry point: An application can use elements of other applications (should be permitted by the apps). For this to work, an
application process can be started when any part of it is needed and instantiate the Java objects for that part.Therefore, Android apps
don’t have a single entry point (like main()function). Rather they have essential components that the system can instantiate and run as
needed.
•
Essential components
Activities
Services
Broadcast receivers
Content providers
Any one of them can be act as an entry point of an Android Application.
Activity
•
The basis of android applications
•
A single Activity defines a single viewable screen - the actions, not the layout
•
Can have multiple per application -Each is a separate entity
•
Activities use Views to form GUI.
Each view controls a particular rectangular space within the window.
Views are where the activity’s interaction with the user takes place.
ContentView is the root view object in the hierarchy of views.
Activity.setContentView() method.
•
They have a structured life cycle
Different events in their life happen either via the user touching buttons or programmatically
Adding an Activity
in Android Studio, right click "app" at left: New ->
Activity
creates a new .XML file in res/layouts
creates a new .java class in src/java
adds information to AndroidManifest.xml
about the activity (without this
information, the app will not allow the
activity)
Activity Example
Activity State
●
●
An activity can be thought of as being in one of several states:
○
starting: In process of loading up, but not fully loaded.
○
running: Done loading and now visible on the screen.
○
paused: Partially obscured or out of focus, but not shut down.
○
stopped: No longer active, but still in the device's active memory.
○
destroyed: Shut down and no longer currently loaded in memory.
Transitions between these states are represented by events that you can listen to in your activity code.–
onCreate, onPause, onResume, onStop, onDestroy, ...
Activity lifecycle
Testing activity states (link)
Use the LogCat system for logging messages when your app changes states:
analogous to System.out.println debugging for Android apps
appears in the LogCat console in Android Studio
public void onStart() {
super.onStart();
Log.v("testing", "onStart was called!");}
Multiple Activities
Many apps have multiple activities.
Example: In an address book app, the main activity is
a list of contacts, and clicking on a contact goes to
another activity for viewing details.
An activity A can launch another activity B in
response to an event.
The activity A can pass data to B.
The second activity B can send data back to A when
it is done.
Activities in Manifest
Interacting with widgets
accessing a widget in the Java code:
1. in Design view, give that view a unique ID property value
2. in Java code, call findViewById() to access its View object
- pass it a parameter of R.id.your_unique_ID
- cast the returned value to the appropriate type (Button, TextView, etc.)
public void button1_onclick(View view)
{
TextView tv = (TextView) findViewById(R.id.mytextview);
tv.setText("You clicked it!");
}
View objects & Events
Each widget has an associated Java object you can access
They are subclasses of parent class View
– examples: Button, TextView, EditText, …
View objects have many get and set methods that correspond to the properties in the Design view:
– background, bottom, ID, left, margin, padding, right, text, textAlignment, textSize,
typeface, visibility, … , etc.
– example: for a Button's text property, there will be methods:
public String getText()
public void setText(String text)
– Find list of properties in Design view, or typing ".get" on a button in Java code, or at:
https://developer.android.com/reference/
event: An external stimulus your
program can respond to. Common kinds
of events include: tapping, Keys pressed,
Timers expiring, Network data available
etc.
Image Button / Button (link)
A clickable widget with a Image (Image Button) /text label (Button)
key attributes:
Represented by Button class in Java code
Button b = (Button) findViewById(R.id.theID);
Image View (link)
A clickable widget with a Image (Image Button) /text label (Button)
key attributes:
to set up an image resource:
– put image file in project folder app/src/main/res/drawable
– use @drawable/foo to refer to foo.png
to change the visible image, in Java code:
– get the ImageView using findViewById
– call its setImageResource method and pass R.drawable.filename
EditText (link)
An editable text input box
key attributes:
-
others: capitalize, digits, fontFamily, letterSpacing, lineSpacingExtra, minLines, numeric,
password, phoneNumber, singleLine, textAllCaps, textColor, typeface
Switch/CheckBox (link)
An individual toggleable on/off switch
key attributes:
In Java code:
CheckBox cb = (CheckBox) findViewById(R.id.theID);
cb.toggle();
cb.setChecked(true);
cb.performClick();
AdapterView
A ViewGroup subclass
Its subchilds are determined by an Adapter
•
Used to visualize data
• Make a ViewGroup to interact with data
• Some methods: isEmpty(), getItem(int position), getCount(), getView()
Some subclasses of AdapterView:
Spinner
ListView, ExpandableListView
GridView
Gallery
Spinner (link)
A drop-down menu of selectable choices
key attributes:
also need to handle events in Java code (see later)
– must get the Spinner object using findViewById
– then call its setOnItemSelectedListener method (see example)
Spinner example
Spinner event example
ScrollView
ListView, GridView, Layout and many more Items will discuss later …
ListView (link)
An ordered collection of selectable choices
key attributes:
also need to handle events in Java code (see later)
– must get the Spinner object using findViewById
– then call its setOnItemSelectedListener method (see example)
Static lists
Dynamic lists
List adapters
Handling list events
List views respond to the following events:
setOnItemClickListener(AdapterView.OnItemClickListener)
- Listener for when an item in the list has been
clicked.
setOnItemLongClickListener(AdapterView.OnItemLongClickListener)
- Listener for when an item in the list has been
clicked and held.
setOnItemSelectedListener(AdapterView.OnItemSelectedListener)
- Listener for when an item in the list has been
selected.
Others:
Custom list layouts
If you want your list to look different than the default
appearance (of just a text string for each line), you
must:
Write a short layout XML file describing the
layout for each row.
Write a subclass of ArrayAdapter that overrides
the getView ethod to describe what view
must be returned for each row
Custom list layout example
Intents (link)
intent: a bridge between activities;
a way for one activity to invoke
another
•
the activity can be in the same
app or in a different app
•
can store extra data to pass as
"parameters" to that activity
•
second activity can "return"
information back to the caller if
needed
Creating an Intent
• To launch another activity (usually in response to an event), create an Intent object and call
startActivity with it:
Intent intent = new Intent(this, ActivityName.class);
startActivity(intent);
•
If you need to pass any parameters or data to the second activity, call putExtra on the intent.
It stores "extra" data as key/value pairs, not unlike a Map.
Intent intent = new Intent(this, ActivityName.class);
intent.putExtra("name", value);
intent.putExtra("name", value);
startActivity(intent);
Extracting extra data
In the second activity that was invoked, you can grab any extra data that was passed to it by the calling act.
You can access the Intent that spawned you by calling getIntent.
The Intent has methods like getExtra, getIntExtra, getStringExtra, etc. to extract any data that was stored
inside the intent.
public class SecondActivity extends Activity {
..
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.activity_second);
Intent intent = getIntent();
String extra = intent.getExtra("name");
…
}
}
Implicit Intent (link)
implicit intent: One that launches another app, without naming that specific app, to handle a given
type of request or action.
examples: invoke default browser; load music player to play a song
// make a phone call
Uri number = Uri.parse("tel:5551234");
Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
// go to a web page in the default browser
Uri webpage = Uri.parse("http://www.stanford.edu/");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
// open a map pointing at a given latitude/longitude (z=zoom)
Uri location = Uri.parse("geo:37.422219,-122.08364?z=14");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
Activities and Action Bar
action bar: A top-level menu of actions in an activity.
•
replaces older "menu" button in past versions of Android
•
identifies current activity/app to user
•
make common actions prominent and available
•
make less common actions available through a dropdown menu
●
If your activity is specified to have a "parent" activity on
creation and in AndroidManifest.xml, you will have a "back"
button to return to the calling activity.
●
make activity class extend ActionBarActivity
– write methods: onCreateOptionsMenu,
onOptionsItemSelected
ActionBarActivity
Service
•
No visual interface.
•
Runs in the background of an indefinite period of time.
Examples: Play background music, fetch data over the network.
Each service extends the Service base class
•
Should create a new thread in the service to do work in, since the service runs in
the main thread
•
Can be bound to an application
In which case will terminate when all applications bound to it unbind
Allows multiple applications to communicate with it via a common interface
•
Needs to be declared in manifest file
•
Like Activities, has a structured life cycle