Corporate 2 Template

advertisement
Android development
Jinhua Chen
1.2.2011
Outline
• Introduction
– Android features
– Android architecture
• Android Application Development
– Installing and hello android example
– Android project structure
– Activity and lifecycle
• Android User Interface
– View and View group
• Android Example
– Login system
• MOPSI Related Development
– Camera, location and maps
– MOPSI Android demos
Outline
•
•
•
•
•
Introduction
Android Application Development
Android User Interface
Android Example
MOPSI Related Development
What is Android?
• Android is a mobile operating system initially
developed by Android Inc., a company bought by Google
in 2005
• Open, free mobile platform based on Linux kernel
• Released in Nov. 2007
• Developed by Open Handsets Alliance
• Run on a Dalvik virtual machine
• Applications written in Java
Open Handsets Alliance
Why android?
• Android Dominate the Mobile Market
– 33% worldwide, 44% in US
• More Type and Stronger Sales
– Motorola Droid, HTC Hero, Samsung Gallery, Huawei...
• Larger Space For Different Kinds and Ideas
– Full access to entire platform source for developers
• Easy access to Google applications
– Google Search, Google Maps, Gmail, Google Calendar
Android Market Share
Android Features
•
•
•
•
•
•
•
•
•
•
Application framework enabling reuse and replacement of components
Dalvik virtual machine optimized for mobile devices
Integrated browser based on the open source WebKit engine
Optimized graphics powered by a custom 2D graphics library; 3D graphics
based on the OpenGL ES 1.0 specification (hardware acceleration optional)
SQLite for structured data storage
Media support for common audio, video, and still image formats (MPEG4,
H.264, MP3, AAC, AMR, JPG, PNG, GIF)
GSM Telephony (hardware dependent)
Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
Camera, GPS, compass, and accelerometer (hardware dependent)
Rich development environment including a device emulator, tools for
debugging, memory and performance profiling, and a plugin for the Eclipse
IDE
Android Architecture
Linux Kernel
• Relies on Linux kernel version 2.6
• Acts as an abstraction layer between the hardware and
the rest of the software stack
• Provides core system services:
–
–
–
–
–
Security
Memory management
Process management
Network stack
Driver model
Libraries
• C/C++ libraries used by various Android components
• Developers can user their capabilities through the
application framwork
• Includes:
–
–
–
–
Media Libraries: MPEG4, H.264, MP3, AAC, AMR, JPG…
LibWebCore: Web browser engine
SQLite: Relational database engine
Libraries/engines for 2D and 3D graphics
Android Runtime
• Core libraries provide most functionalities using Java
• Devices can run multiple Dalvik VMs, every Android
application runs with its own instance of Dalvik VM
• Dx-tool transforms compiled Java-files into dex-files
Application Framework/Applications
• Developers have full access to the same framework APIs
used by the core applications including contacts, phone,
browser, maps
• Simplifies the reuse of components
• Any application can publish its capabilities and any other
application may then make use of those capabilities
What are we going to do?
Develop fantastic Android applications!
Outline
•
•
•
•
•
Introduction
Android Application Development
Android User Interface
Android Example
MOPSI Related Development
Installing Android SDK
• Follows the instruction from Android document
– http://developer.android.com/sdk/installing.html
•
•
•
•
JDK 1.6
IDE Eclipse 3.5 or newer
Android SDK including docs, tools and examples
ADT Plugin for Eclipse
Hello Android Ⅰ
• File->New->Android Project
Hello Android Ⅱ
• Fill in the project details with the
following values:
– Project name: HelloAndroid
– Application name: Hello, Android
– Package name: com.example.hello
(or your own private namespace)
– Create Activity: HelloAndroid
• Select Build Target
– Android 2.2 version
• Click on “Finish”
Hello Android Ⅲ
Hello Android Ⅳ
• Run->run
Android Project Structure
Android Manifest
• The manifest presents essential information about the
application to the Android system, information the system
must have before it can run any of the application's code
Android Manifest Permissions
• A permission is a restriction limiting access to a part of
the code or to data on the device.
• Includes
–
–
–
–
Internet
Location using GPS or Network
Writing data
…
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Android Application Components
• Activities
– An activity presents a visual user interface for one focused
endeavor the user can undertake
• Services
– A service doesn't have a visual user interface, but rather runs in
the background for an indefinite period of time
• Broadcast receivers
– A broadcast receiver is a component that does nothing but
receive and react to broadcast announcements.
• Content providers
– A content provider makes a specific set of the application's data
available to other applications.
Activity
• Single, focused thing or task
• An application may have one or more activities
• Refers to a single screen, displays a UI, interacts with
user, responses to events
• Activities managed by activity stack
• New activity put on top of stack
• 3 states: active/running, paused, stopped
• Activated by intent
– Context.startActivity()
– Activity.startActivityForResult()
Activity Lifecycle
Activity Lifetime
• Entire lifetime of an activity happens between the first call
to onCreate() through to a single final call to onDestroy()
– Does initial setup in onCreate()
– Releases all remaining resources e.g. stops thread
• Visible lifetime of an activity happens between a call to
onStart() until a corresponding call to onStop()
– User can see the activity on-screen
– Maintain resources that are needed
• Foreground lifetime of an activity happens between a call
to onResume() until a corresponding call to onPause()
– Activity is in front of all other activities on screen and is interacting
with the user
Outline
•
•
•
•
•
Introduction
Android Application Development
Android User Interface
Android Example
MOPSI Related Development
User Interface/View
• The user interface is built using view and viewgroup
• View objects are the basic units of user interface
expression
• A View object handles its own measurement, layout,
drawing, focus change, scrolling, and key/gesture
interactions
• Read-made views: buttons, text fields, menu items,
scroll bars and check boxes
Programmatic UI Layout
• Construct and build the UI of application directly from
source code
• Drawback: small changes in layout can have a big effect
on the source code
package com.android.hello;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, My Android!");
setContentView(tv);
}
}
Upgrading UI to XML Layout
• Inspired by web development model where the
presentation of the application’s UI is separated from the
logic
• Two files to edit
– Java file: application logic
– XML file: user interface
Upgrading UI to XML Layout
XML Layout
Common Layout Objects
•
•
•
•
FrameLayout
LinearLayout
TableLayout
RelativeLayout
FrameLayout
• Simplest Layout Objects
• Basically a blank space on your screen that you can later
fill with a single object — for example, a picture that you'll
swap in and out
• All child elements of the FrameLayout are pinned to the
top left corner of the screen
• Cannot specify a different location for a child view
LinearLayout
• Aligns all children in a single direction — vertically or
horizontally
• All children are stacked one after the other, so a vertical
list will only have one child per row, no matter how wide
they are, and a horizontal list will only be one row high
(the height of the tallest child, plus padding)
TableLayout
• Positions its children into rows and columns
• Does not display border lines for rows, columns, or cells
• TableRow, a child view, defines a single row in the table
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="@string/table_layout_4_open" android:padding="3dip" />
<TextView
android:text="@string/table_layout_4_open_shortcut"
android:gravity="right" android:padding="3dip" />
</TableRow>
<TableRow>
<TextView
android:text="@string/table_layout_4_save“ android:padding="3dip" />
<TextView
android:text="@string/table_layout_4_save_shortcut"
android:gravity="right" android:padding="3dip" />
</TableRow>
</TableLayout>
RelativeLayout
• Lets child views specify their position relative to the
parent view or to each other (specified by ID)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:background="@drawable/blue“ android:padding="10px" >
<TextView android:id="@+id/label"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="Type here:" />
<EditText android:id="@+id/entry"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_below="@id/label" />
<Button android:id="@+id/ok"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_below="@id/entry" android:layout_alignParentRight="true"
android:layout_marginLeft="10px" android:text="OK" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content“ android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok“ android:text="Cancel" />
</RelativeLayout>
Important View Groups
• Gallery: A horizontal scrolling display of images, from a
bound list
• GridView: Displays a scrolling grid of m columns and n
rows
• ListView: Displays a scrolling single column list
• ScrollView: A vertically scrolling column of elements
• More resources:
– http://developer.android.com/guide/topics/ui/layout-objects.html
Handling UI Events
• Capture the events from the specific View object that the
user interacts with
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}});
}
...
}
Outline
•
•
•
•
•
Introduction
Android Application Development
Android User Interface
Android Example
MOPSI Related Development
Login Example
Login: Create Project
• File->New->Android Project
• Fill in the project details with the
following values:
– Project name: Login
– Application name: Login, Demo
– Package name:
com.example.login
– Create Activity: Login
• Select Build Target
– Android 2.2 version
• Click “Finish”
Login: Create colors.xml
•
•
Create colors.xml to set
color for text,
background, ect
Login->res->values,
right click->New->
Android XML File
Login Example – Create colors.xml
• Fill the file name
– colors.xml
• Select type
– Values
• Click on “Finish”
Login: colors.xml and AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#ffffff</color>
<color name="blue">#3366cc</color>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.login"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Login"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Login: Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/white" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent" >
<TextView android:id="@+id/login_user“ android:layout_width="wrap_content“ android:layout_height="wrap_content“
android:text="@string/username“ android:textColor="@color/blue“ android:gravity="left“
android:layout_marginLeft="12px“ android:layout_marginTop="10px" />
<EditText android:id="@+id/txt_username" android:layout_width="fill_parent“ android:layout_height="wrap_content"
android:hint="Username“ android:singleLine="true" android:textSize="18sp"
android:layout_marginLeft="10px" android:layout_marginRight="10px" />
<TextView android:id="@+id/login_pwd" android:layout_width="wrap_content“ android:layout_height="wrap_content"
android:text="@string/password“ android:textColor="@color/blue"
android:gravity="left“ android:layout_marginLeft="12px" />
<EditText android:id="@+id/txt_password" android:layout_width="fill_parent“ android:layout_height="wrap_content"
android:hint="Password“ android:singleLine="true" android:textSize="18sp" android:password="true"
android:layout_marginLeft="10px" android:layout_marginRight="10px" />
<Button
android:layout_width="100px" android:layout_height="wrap_content"
android:layout_marginTop="10px" android:layout_marginRight="15px"
android:id="@+id/button_login" android:text="Login"
android:layout_gravity="right" />
<TextView android:id="@+id/txt_response" android:layout_width="wrap_content“ android:layout_height="wrap_content"
android:textSize="18sp" android:textColor="@color/blue" android:layout_marginLeft="10px" />
</LinearLayout>
Login: Login.java
public class Login extends Activity {
private static final String TAG = "Login";
private ProgressDialog dialog;
private Thread thrd;
private EditText etxt_user;
private EditText etxt_pass;
private TextView tv_rp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etxt_user = (EditText) findViewById(R.id.txt_username);
etxt_pass = (EditText) findViewById(R.id.txt_password);
tv_rp = (TextView) this.findViewById(R.id.txt_response);
Button loginin = (Button)
findViewById(R.id.button_login);
loginin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog = ProgressDialog.show(Login.this, "",
"Singing in. Please wait...", true);
thrd = new Thread(new Runnable() {
public void run() {
tryLogin(); } });
thrd.start(); }
});
}
Login: Login.java
public void tryLogin() {
Log.v(TAG, "Trying to Login");
String username = etxt_user.getText().toString();
String password = etxt_pass.getText().toString();
Log.v(TAG, "username:" + username + "password:" + password);
String httpQuery = "http://cs.joensuu.fi/paikka/web/inc/mobilelogin.php?username="
+ username + "&password=" + password;
try {
HttpGet request = new HttpGet(httpQuery);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Message login_msg = new Message();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity());
if (!result.equals("incorrect")) { // login success
JSONObject json = new JSONObject(result);
int userid = Integer.parseInt(json.getString("userid"));
username = json.getString("username");
Log.v(TAG, "userid:" + userid + "username:" + username);
login_msg.obj = "SUCCESS";
} else {login_msg.obj = "INCORRECT";}
} else {login_msg.obj = "FAILED";}
handler.sendMessage(login_msg);
} catch (Exception e) {dialog.dismiss();
Log.v(TAG, "login error:"+e.getMessage());}
}
Login: Login.java
/**
* Use Handle to update UI
*/
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// close dialogue
dialog.dismiss();
String loginmsg = (String) msg.obj;
Log.v(TAG, loginmsg);
if (loginmsg.equals("SUCCESS")) {
tv_rp.setText("Success!");
//moving to other screen
} else if (loginmsg.equals("INCORRECT")) {
tv_rp.setText("Account is incorrect!");
} else if (loginmsg.equals("FAILED")) {
tv_rp.setText("No connection!"); }
}
};
}
Login User Interface
Login User Interface
Outline
•
•
•
•
•
Introduction
Android Application Development
Android User Interface
Android Example
MOPSI Related Development
MOPSI Related Development
• Invoke device camera
• Location and maps
Use Device Camera
• android.hardware.Camera
– set image capture settings, start/stop preview, snap pictures, and
retrieve frames for encoding for video
– declare the CAMERA permission in your Android Manifest
• android.provider.MediaStore.ACTION_IMAGE_CAPTURE
– Invokes the camera application in your device
– Returns a small size image If the EXTRA_OUTPUT is not present
– Writes a full size image to the Uri if EXTRA_OUTPUT is present
Camera Hardware and Application
Camera hardware
Camera application
Invoke Camera Application
// Invoke the camera of system and take photo, then go to send photo screen
private void takePhoto() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
//Process the image data from the camera
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap thumbnail = (Bitmap) extras.get("data");
// instantiate Intent, indicate the intent to be invoked
Intent intent = new Intent();
intent.setClass(this, SendPhoto.class);
// instantiate Bundle, set the parameters to be passed
intent.putExtra("image", thumbnail);
// start the new intent without response
this.startActivity(intent);
}
} catch (Exception e) {Log.v(TAG, e.getMessage());}
}
Location and Maps
• Get location
– GPS: accurate, slow, only for outdoors
– Network: using cell tower or Wi-Fi, not very accurate, fast
– Set permission
• <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
• Get Maps
– Maps external library that includes the com.google.android.maps
package
– http://code.google.com/android/add-ons/google-apis
Get Location
private LocationManager mLocationManager;
// Acquire a reference to the system Location Manager
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Register the listener with the Location Manager to receive location updates
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, minTime, minDist, networkListener);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, gpsListener);
// Define a listener that responds to location updates
public final LocationListener networkListener = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude()
double lon = location.getLongitude()
double alt = location.getAltitude()
//doLocationUpdated(location); // do other things
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
MOPSI Android: Main Screen
Login UI
Main UI
Setting UI
MOPSI Android: Taking Photo
Camera
Add description
Photo uploading
MOPSI Android: Tracking Route
Route tracking
Options in tracking
Saved tracking routes
Thank you!
jinhuachen1982@gmail.com
Download