47767738-android-day1-1
DESCRIPTION
android-day1-1TRANSCRIPT
-
Android Development
Day1
-
Agenda Day1
Introduction Activity Basics Intent Filters Activities & Sub-Activities Content Provider Services Threads, Services, Receivers & Alerts
-
INTRODUCTION
-
Introduction
In 2005 Rubin (Danger, Software service company) and his minions began developing a Linux-based operating system for cell phones and other mobile devices. Their main marketing targets were handset makers and carriers.
In December 2006, rumors surfaced of Google's entry into the cell phone market, soon followed by rumors of a new handset, branded by Google.
-
Introduction
Andy Rubin
-
Introduction
Open Handset Alliance (OHA) a business alliance of 79 firms for developing open standards for mobile devices.
-
Introduction
Because OHA members have its own industry, so Android is not even limited to phones
Android could be build a Set-top box, a handheld GPS, an MP3 player, etc.
-
What is Android? Android came from 3 other places 1. First lets talk about the inter process communication
(IPC). The Android OS is a non-RTOS OS based on a Linux Kernel. Because the OS apps are non RTOS they have to communicate states and etc to other OS process and this is where IPC comes in the picture. Its a Palm invention as applied to mobile operating systems.
-
What is Android? 2. The second technology borrowed is from the Apache
Harmony Project which is an open source java stack including the classes found in a normal desktop jdk and the VM machinery found in a JRE. while the VM was replaced by a register VM to perform better in a mobile environment, most of JavaSE classes were kept and thus Android Java is closer to JavaSE than JavaME CDC.
-
What is Android?
3. The third technology borrowed is form Java Swing itself, in that a data/view relationship is maintained in the interaction between the UI and data layers
-
What is Android?
Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.
-
Android Version
Many version and still improve 1.5 Cupcake 1.6 Donut 2.1 Eclair 2.2 Froyo 2.3 Gingerbread 3.0 Honeycomb mid-2011 Ice Cream Sandwich
-
Usage Share Platform API Level Distribution
Android 2.2 (Froyo) 8 43.4%
Android 2.1 (Eclair) 7 39.6%
Android 1.6 (Donut) 4 10.6%
Android 1.5 (Cupcake) 3 6.3%
-
Androids Advantage over iPhone
1. Multitasking - The Android has the ability of letting more than one application run at the same time whether the apps are system apps or apps downloaded from the Android Marketplace.
-
Androids Advantage over iPhone
2. The way apps are driven to the Android Marketplace exceeds the Apple App Store. With the Apple App Store, app submissions can be denied simply because the app doesnt meet Apples standards or a similar app already exists in the store.
-
Androids Advantage over iPhone
3. With the iPhone, you can integrate with online websites via a third party app. But with the Android, downloading pictures to Flickr, connecting to Facebook and Twitter, and reading your Gmail can be automatically synchronized to the phone. If you take a picture, it can be uploaded directly to Flickr and you can connect with your Facebook friends instantly.
-
Android Architecture
-
Android Architecture
Linux Kernel Linux Version 2.6.x for core system services Android uses only Kernel portion in Linux
-
Android Architecture
Libraries & Android Runtime
-
Android Architecture
Core Libraries Provides the functionality of the JAVA Programming
Language Android Application runs in its own process, with its own
instance of the Dalvik virtual machine Dalvik VM: Java based license free VM Register based VM, optimization for low memory requirements Executes files in the Dalvik Executable (.dex) format DX tool converts classes to .dex format
-
Android Architecture Libc: c standard lib.SSL: Secure Socket LayerSGL: 2D image engine OpenGL|ES: 3D image engine Media Framework: Core part of Android multi-media SQLite: Embedded database WebKit: Kernel of web browser FreeType: Bitmap and Vector Sufrace Manager: Manage difference windows for different
applications
-
Android Architecture
No limited application Equality of each apps. Easy to embedded web browser Parallel running
-
Android Architecture The Design goal of Android: Openness
Be as flexible as possible How it handles access to data: Mash up on the internet and
everything else
Rapid development (XML, Java) Develop Language
App: Java Framework: Java Libraries: C/C++ OS & Driver: C
-
Installation
1. Android SDK http://developer.android.com/sdk/index.html
2. Eclipse 3.5 Galileo http://www.eclipse.org/downloads/packages/eclipse-
classic-350/galileo
3. ADT Plug-in for Eclipse Add Software update site - https://dl-ssl.google.com/
android/eclipse/
-
Set eclipse to use Android SDK
window>preferences>Android
-
Install some more packages
-
Project Structure
Here's a quick primer on the project structure
-
Project Structure Root Contents - When you create a new Android project
(e.g., via activityCreator.py), you get 5 key items in the project's root directory
AndroidManifest.xml describing the application being built and what components activities, services, etc. are being supplied by that application
build.xml - Ant script for compiling the application and installing it on the device
bin/, the application once it is compiled src/, Java source code for the application assets/, which hold other static files you wish packaged with
the application for deployment onto the device
-
Project Structure
src
AndroidManifest.xml
assets
-
Project Structure
res: res stands for resources. Here is where you put your resources (images, files, etc). drawable: This is where the images youre going to use go.
Android supports a variety of image files, including .jpg, .gif (static), png, etc.
layout: This is where the .xml files describing your program layouts go. Ill spend a post on those later.
values: This is where .xml files defining values can be stored. An example is a network topography program I worked on.
-
Project Structure
gen: It will automatically update itself as necessary.This is the package holding automatically generated code R.java is an automatically created and maintained file that
keeps up with the resources your project utilizes. In a lot of your Android programming, youre going to use static variables that really translate into numerical (usual hex) values. R.java makes the translation between these variables and their numerical values.
-
Project Structure
R.java
res
-
AndroidManifest.xml
Here is where you declare what all is inside your application the activities, the services, and so on. You also indicate how these pieces attach themselves to the overall Android system; for example, you indicate which activity (or activities) should appear on the device's main menu (a.k.a., launcher).
-
AndroidManifest.xml
1. Package Declaration (manifest element)
! ... !!
-
AndroidManifest.xml
2. More declaration (Underneath manifest element) uses-permission elements, to indicate what permissions your
application will need in order to function properly permission elements, to declare permissions that activities or
services might require other applications hold in order to use your application's data or logic
instrumentation elements, to indicate code that should be invoked on key system events, such as starting up activities, for the purposes of logging or monitoring
an application element, defining the guts of the application that the manifest describes
-
AndroidManifest.xml
-
AndroidManifest.xml
3. Application element real meat of the manifest file
+ Receivers, Services, Content Providers
-
Basic Concepts
Activities Content Providers Intents Services
-
Basic Concepts
Activities - The building block of the user interface is the activity. You can think of an activity as being the Android analogue for the window or dialog in a desktop application. While it is possible for activities to not have a user interface, most likely your "headless" code will be packaged in the form of content providers or services.
-
Basic Concepts
Content Providers - Content providers provide a level of abstraction for any data stored on the device that is accessible by multiple applications. The Android development model encourages you to make your own data available to other applications, as well as your own building a content provider lets you do that, while maintaining complete control over how your data gets accessed.
-
Basic Concepts
Intents - Intents are system messages, running around the inside of the device, notifying applications of various events, from hardware state changes (e.g., an SD card was inserted), to incoming data (e.g., an SMS message arrived), to application events (e.g., your activity was launched from the device's main menu)
-
Basic Concepts
Services - Activities, content providers, and intent receivers are all short-lived and can be shut down at any time. Services, on the other hand, are designed to keep running, if needed, independent of any activity. You might use a service for checking for updates to an RSS feed, or to play back music even if the controlling activity is no longer operating.
-
APPLICATION BASICS
-
Application Basic
Every Application is made up of one or more of these
-
Activities Every screen is called Activity Application flow Each activity is a class
-
More Things to Know
All activities extend the abstract class Activity or one of its subclasses.
The entry point to each activity is the onCreate() method.
It is almost always overridden to initialize the activity, such as setting up the UI, creating button listeners, initializing parameters, and starting threads
-
Activity Class Overview
An activity is a single, focused thing that the user can do the Activity class takes care of creating a window for you
in which you can place your UI with setContentView(View)
There are two methods almost all subclasses of Activity will implement onCreate(Bundle) onPause()
-
Activity Lifecycle
-
Activity Lifecycle
There are three key loops you may be interested in monitoring within your activity: The entire lifetime onCreate(Bundle), onDestroy() The visible lifetime onStart(), onStop() The foreground lifetime onResume(), onPause()
-
Intents & Intent Filters
Think of Intents as a verb and object; a description of what you want done Examples: VIEW, CALL, PLAY, etc.
System matches Intent with Activity that can best provide that service
Activities and BroadcastReceivers describe what Intents they can service in their IntentFilters (via AndroidManifest.xml)
-
Implicit Intents
public void onClick(View v) { Intent contacts = new Intent();
contacts.setAction(android.content.Intent.ACTION_VIEW); contacts.setData(People.CONTENT_URI); startActivity(contacts);
}
-
Implicit Intents
-
Content Provider
Every application has its own sandbox and cannot access data from other applications. If access to functions not provided by its own sandbox is required, the application must explicitly declare permission upfront before installation
Android provides an interface called ContentProvider to act as a bridge between applications, enabling them to share and change each others data
-
Content Provider
Content providers offer data encapsulation using Uri instances as handles
The data could be stored in a SQLite database, or in flat files, or retrieved off a device, or be stored on some far-off server accessed over the Internet
content://contacts/people
Base URI
-
Native Resource as Content Provider
BrowserRead or modify bookmarks, browser history, or web searches
CallLogView or update the call history ContactsRetrieve, modify, or store the personal
contacts LiveFoldersA special folder whose content is provided
by a ContentProvider MediaStoreAccess audio, video, and images SettingView and retrieve Bluetooth settings, ring
tones, and other device preferences
-
Native Resource as Content Provider
SearchRecentSuggestionsCan be configured to operate with a search suggestions provider
SyncStateContractContentProvider contract for associating data with a data array account
Providers that want to store this data in a standard way can use this
UserDictionaryProvides user-defined words used by input methods during predictive text input
-
Native Resource as Content Provider
To access a content provider, the application needs to get a contentResolver instance to query, insert, delete, and update the data from the content provider, as shown in the following example:
-
Example
-
Custom Content Provider just extends the Android ContentProvider class, which
contains six methods to optionally override: query()Allows third-party applications to retrieve content insert()Allows third-party applications to insert content update()Allows third-party applications to update content delete()Allows third-party applications to delete content getType()Allows third-party applications to read each of
URI structures supported
onCreate()Creates a database instance to help retrieve the content.
-
Custom Content Provider
Content Provider
Ac8vity A
Ac8vity B
query()!insert()!update()!deleted()!getType()!
-
Example Content Provider
package com.cookbook.datastorage;!
import android.content.ContentProvider; !import android.content.ContentValues; !import android.content.UriMatcher; !import android.database.Cursor;!import android.database.sqlite.SQLiteQueryBuilder; !import android.net.Uri;!import com.cookbook.data.Constants;!import com.cookbook.data.MyDB;!
-
Example Content Provider
public class DiaryContentProvider extends ContentProvide{!private MyDB dba; !private static final UriMatcher sUriMatcher; //the code returned !//for URI match to components !private static final int DIARIES=1;!public static final String AUTHORITY =
"com.cookbook.datastorage";!
static {! sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);! sUriMatcher.addURI(AUTHORITY, ! Constants.TABLE_NAME,DIARIES);!} !
-
Example Content Provider
public int delete(Uri uri, String selection, String[] selectionArgs) { return 0;} !
public String getType(Uri uri) {return null;}!public Uri insert(Uri uri, ContentValues values) !{return null;}!public int update(Uri uri, ContentValues values, String
selection,String[] selectionArgs) {return 0;}!public boolean onCreate() {!! dba = new MyDB(this.getContext()); !! dba.open(); !! return false;!}!
-
Example Content Provider public Cursor query(Uri uri, String[] projection, String
selection,String[] selectionArgs, String sortOrder) { !! Cursor c=null;!! switch (sUriMatcher.match(uri)) { !! !! case DIARIES:c = dba.getdiaries();!! !! ! ! ! ! break; !! !! ! default:throw new IllegalArgumentException
( "Unknown URI " + uri);!! } !! c.setNotificationUri(getContext().!! !! ! ! ! ! ! getContentResolver(), uri); !return c;!}!}!
-
AndroidManifest.xml !!
!
!
! !! !! !! ! ! !! !
! !!
-
How to use
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); !
! setContentView(R.layout.main); !! tv = (TextView) findViewById(R.id.output); !! String myUri = "content://com.cookbook.datastorage/
diaries"; !! Uri CONTENT_URI = Uri.parse(myUri);!! //get ContentResolver instance !! ContentResolver crInstance = getContentResolver(); !! Cursor c = crInstance.query(CONTENT_URI, null, null,
null, null); !! startManagingCursor(c); !! StringBuilder sb = new StringBuilder(); !
-
How to Use
if(c.moveToFirst()){!! do{!! !! sb.append(c.getString(1)).append("\n"); !! }while(c.moveToNext());!}!tv.setText(sb.toString());}
-
THREADS, SERVICES, RECEIVERS & ALERTS
-
Threads, Services, Receivers and Alerts
Every Application runs a single process Always hanging the user interface e.g. network downloads, intensive calculations, time-
consuming tasks Launching a Secondary Thread
-
Threads, Services, Receivers and Alerts
Ring-tone song is played when button is pressed
Play
-
Play
Threads, Services, Receivers and Alerts
In the following, calling the play_music() function without specifying a separate thread blocks the application during music playback
play_music()
-
Threads, Services, Receivers and Alerts
Button startButton = (Button) findViewById(R.id.trigger); startButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view){ // BAD USAGE: function call to time-consuming // function play_music(); } });causes main thread to hang
-
Threads, Services, Receivers and Alerts
This means Button are not registered until play_music() finished
Resolved by calling secondary Thread to run
-
Threads, Services, Receivers and Alerts
1.Create Thread Thread initBkgdThread = new Thread( //insert runnable object here );
2.Create Runnable Object new Runnable() { public void run() { play_music(); } }
-
Threads, Services, Receivers and Alerts
3. Then start initBkgdThread.start();
-
Threads, Services, Receivers and Alerts
Side effect? Even though main activity stopped, the music keep
playing
So, we need functions to check a playing flag
-
Threads, Services, Receivers and Alerts public class PressAndPlay extends Activity {
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
Button startButton = (Button) findViewById(R.id.trigger);
startButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view){ //standalone play_music() function call causes //main thread to hang. Instead, create //separate thread for time-consuming task Thread initBkgdThread = new Thread(new Runnable() { public void run() { play_music(); } });
-
Threads, Services, Receivers and Alerts initBkgdThread.start(); } }); } int[] notes = {R.raw.c5, R.raw.b4, R.raw.a4, R.raw.g4}; int NOTE_DURATION = 400; //millisec MediaPlayer m_mediaPlayer;
-
Threads, Services, Receivers and Alerts
private void play_music() { for(int ii=0; ii
-
Threads, Services, Receivers and Alerts
boolean paused = false; @Override protected void onPause() { paused = true; super.onPause(); } @Override protected void onResume() { super.onResume(); paused = false; } }
-
Threads, Services, Receivers and Alerts
Setting Thread priority A new Thread starting with priority = 5 Note: 1 is min priority, 10 is max priority Thread.MIN_PRIORITY, Thread.MAX_PRIOPRITY Set by calling myThread.setPriority
(Thread.MAX_PRIOPRITY);
-
Threads, Services, Receivers and Alerts
Canceling a Thread Make it a daemon Thread
Daemon Thread : are like aservice providersfor other threads or objects
running in the same process as the daemon thread.. If normal threads are not running and remaining threads are daemon threads then the interpreter exits.
setDaemon(true/false) This method is used to specify that a thread is daemon thread.
-
Threads, Services, Receivers and Alerts
Canceling a Thread Send interrupt(); myThread.stop()
//use to stop the thread myThread if(myThread != null) { Thread dummy = myThread; myThread = null; dummy.interrupt(); }
-
Threads, Services, Receivers and Alerts
Sharing the Thread between 2 Applications Converse case from last slide if two applications need to communicate between each
other, they can do so using binders rather than the more complicated inter-process communication (IPC) protocol
-
Threads, Services, Receivers and Alerts
The steps are 1. Make sure each applica8on, when packaged for release, is signed with the same key for security reasons.
2. Make sure each applica8on is run with the same user ID.This is done by declaring the same aKribute android:sharedUserId="my.shared.userid" in the Ac8vityManifest.xml for each applica8on.
3. Declare each relevant ac8vity or component to be run in the same process.This is done by declaring the same aKribute android:process="my.shared.process- name" in the Ac8vityManifest.xml for each component.
-
Threads, Services, Receivers and Alerts
Communication between Thread: Handler Here are some examples:
A main thread serves time-critical information and passes messages to the back-ground time-consuming thread to update.
A large computation completes and sends a message back to the calling thread with the result.
-
Threads, Services, Receivers and Alerts
Like this;
Main Thread
BG Thread
1 mainThread.heavyWork();
3 mainThread.workFin(re
sult);
-
Threads, Services, Receivers and Alerts
This can be accomplished with handlers, which are objects for sending messages between threads
Each handler is bound to a single thread, delivering messages to it and executing commands from it.
-
Threads, Services, Receivers and Alerts Handler private Handler mHandler = new Handler(); mHandler.postDelayed(mUpdateTimeTask, 100); mHandler.removeCallbacks(mUpdateTimeTask);
private Runnable mUpdateTimeTask = new Runnable() { public void run() { final long start = mStartTime; long millis = SystemClock.uptimeMillis() - start; int seconds = (int) (millis / 1000); int minutes = seconds / 60; seconds = seconds % 60; mTimeLabel.setText("" + minutes + ":" + String.format("%02d",seconds)); mHandler.postDelayed(this, 200); } };
-
Threads, Services, Receivers and Alerts
Services
-
Threads, Services, Receivers and Alerts
A service is an Android component that runs in the background without any user interaction
It can be started and stopped by any component
-
Threads, Services, Receivers and Alerts
Some illustrative scenarios are An activity provides the user a way to select a set of music
files, which then starts a service to play back the files An activity starts a service to upload a set of pictures to a
website A broadcast receiver receives a message that a picture was
taken and launches a service to upload the new picture to a website
-
Threads, Services, Receivers and Alerts
-
Threads, Services, Receivers and Alerts
An aside on the third scenario: Any background task within a component will be killed when the component is killed.
Therefore, tasks that are meaningful to continue even after the component stops should be done by launching a service.
This ensures the operating system is aware active work is still being done by the process.
-
Threads, Services, Receivers and Alerts
Creating a Self-Contained Service 1. Create class extend Service 2. Declare the service in the AndroidManifest.xml file (Eclipse
automatically do it)
3. Override the onCreate() and onDestroy() methods 4. Override the onBind() method for cases when a new
component binds to this service after it has already been created
5. Activate the service from an external trigger
-
Threads, Services, Receivers and Alerts
Class
public class SimpleService extends Service { @Override public IBinder onBind(Intent arg0) { //code here return null; }
-
Threads, Services, Receivers and Alerts
@Override public void onCreate() { super.onCreate(); Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show(); paused = false; Thread initBkgdThread = new Thread(new Runnable() { public void run() { play_music(); } }); initBkgdThread.start(); }
-
Threads, Services, Receivers and Alerts
@Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show(); paused = true; }
AndroidManifest.xml
-
Threads, Services, Receivers and Alerts
To Start Service startService(new Intent
(SimpleActivity.this,SimpleService.class));
To Stop Service stopService(new Intent(SimpleActivity.this, SimpleService.class));
-
Receivers Broadcast
-
Threads, Services, Receivers and Alerts
A broadcast receiver listens for relevant broadcast messages to trigger an event
Some examples of broadcasted events already sent from the OS are
The camera buKon was pressed. The baKery is low. A new applica8on was installed.
-
Threads, Services, Receivers and Alerts
broadcast receiver normally initiates a separate component or sends a notification to the user in its onReceive() method
If a broadcast receiver needs to do something more time-consuming, it should start a service instead of spawn a thread because an inactive broadcast receiver might be killed by the system
-
Threads, Services, Receivers and Alerts
SimpleBroadcastReceiver intentReceiver = new SimpleBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CAMERA_BUTTON); intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED); registerReceiver(intentReceiver, intentFilter);
unregisterReceiver(intentReceiver);
Ini8alize
onCreate()
onDestroy()
-
Threads, Services, Receivers and Alerts
public class SimpleBroadcastReceiver extends BroadcastReceiver { @Override
public void onReceive (Context rcvContext, Intent rcvIntent) { String action = rcvIntent.getAction(); if(action.equals(Intent.ACTION_CAMERA_BUTTON)){ rcvContext.startService(new Intent(rcvContext, SimpleService2.class)); } } }
-
Alerts
-
Threads, Services, Receivers and Alerts
Alerts provide a quick message to the user outside of the application s main UI
It can be in an overlay window such as a Toast or AlertDialog box
It can also be in the notification bar at the top of the screen
-
Threads, Services, Receivers and Alerts
Toast
-
Threads, Services, Receivers and Alerts
Toast tst = Toast.makeText(this, "text", Toast.LENGTH_LONG);
ImageView view = new ImageView(this); view.setImageResource(R.drawable.my_figure); tst.setView(view); tst.show();
Toast tst = Toast.makeText(this, "text", Toast.LENGTH_SHORT); tst.show();
Text Message
Image View
-
Threads, Services, Receivers and Alerts
Status Bar Notification
-
Threads, Services, Receivers and Alerts
String ns = Context.NOTIFICATION_SERVICE; mNManager = (NotificationManager) getSystemService(ns); final Notification msg = new Notification(R.drawable.icon,"New event of importance",System.currentTimeMillis());
Dene how it displays
-
Threads, Services, Receivers and Alerts
Context context = getApplicationContext(); CharSequence contentTitle = "ShowNotification Example"; CharSequence contentText = "Browse Android Cookbook Site";
Intent msgIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.pearson.com")); PendingIntent intent = PendingIntent.getActivity( ShowNotification.this, 0, msgIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Dene message & ac8on
-
SAMPLE PROJECT
-
Before Create Project
Need to create new project 1. In Eclipse, choose File New Android Project.This
displays a New Android Project creation screen.
2. Fill in the Project name, such as SimpleActivityExample. 3. Select a Build Target from the choices provided.These
choices are based on the Software Development Kit (SDK) versions that are installed on the development computer.
4. Fill in all the blanks
-
Here is Sample
-
Parameters
Project Name the name of the directory that will contain the project files
Application Name the name that will appear on the Android device
Package Name the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under
-
Parameters
Create Activity This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work.
Min SDK Version This value specifies the minimum API Level required by your application.
-
How to Create Project?
1. Create a class to extend Activity. (In Eclipse, this can be done by right-clicking on the project, choosing New Class, and then specifying android.app. Activity as the super class.)
2. Override the onCreate() function. (In Eclipse, this can be done by right-clicking on the class file, choosing Source Override/Implement Methods..., and then checking the onCreate() method.)
-
How to Create Project?
3. As with most overridden functions, it must invoke the super class method, too; otherwise, an exception may be thrown at run-time. Here, the super.onCreate() should be called first to properly initialize the activity.
-
Like This
-
How to Create Project?
4. If a UI is used, specify the layout in an XML file in the res/layout/ directory. Here it is called main.xml
5. Set the layout of the activity using the setContentView() function and passing it the resource ID for the XML layout file. Here, it is R.layout.main
6. Declare the properties of the activity in the AndroidManifest.xml
7. Dont forget to define stuffs in res/
-
main.xml
-
Stuffs in res/values
-
Run Application
-
Q&A