Applications
Chapter 5: Google Android:
Motorola MOTODEV Studio
Android Components
Activities
Services
Broadcast Receivers
Content Providers
Variables
Methods
Constructors
Programming with Mobile Applications
Hello Android!
Figure 5-5 The main.xml file in the Graphical
Layout view
android.app.Activity;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.*;
10
11
12
Figure 5-14 Hello Android after entering text and pressing the button
13
DotSmasher
1. Create a custom canvas that draws the
dot and score onscreen.
2. Subclass the TimerTask class that
supplies instructions to run repeatedly
until the game ends.
3. Implement a MainActivity that
instantiates the apps objects.
4. Provide a way to restart and end the
game.
Programming with Mobile Applications
14
DotSmasher (continued)
Figure 5-22 The DotSmasherCanvas class
15
DotSmasher (continued)
DotSmasherCanvas.java
package com.dotsmasher;
import java.util.Random;
import
import
import
import
import
import
android.content.Context;
android.util.AttributeSet;
android.view.MotionEvent;
android.view.View;
android.view.View.OnTouchListener;
android.graphics.*;
16
DotSmasher (continued)
DotSmasherCanvas.java (continued)
public class DotSmasherCanvas extends View implements OnTouchListener {
int dotX, dotY, score;
public int getDotX() {
return dotX;
}
public void setDotX(int dotX) {
this.dotX = dotX;
}
public int getDotY() {
return dotY;
}
public void setDotY(int dotY) {
this.dotY = dotY;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
17
DotSmasher (continued)
DotSmasherCanvas.java (continued)
public DotSmasherCanvas(Context context) {
super(context);
moveDot();
setOnTouchListener(this);
}
public DotSmasherCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public DotSmasherCanvas(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
18
DotSmasher (continued)
DotSmasherCanvas.java (continued)
@Override
public boolean onTouch(View v, MotionEvent event)
{
if(detectHit((int)event.getX(),(int)event.getY())){
score += 1;
invalidate();
}
return false;
}
19
DotSmasher (continued)
DotSmasherCanvas.java (continued)
protected void moveDot(){
// create two random numbers
// assign random numbers to dotX, dotY
Random generator = new Random();
generator.setSeed(System.currentTimeMillis());
int w = getWidth()-20; // to avoid covering score
int h = getHeight()-40; // to avoid covering score
float f = generator.nextFloat();
dotX = (int)(f*w)%w;
f = generator.nextFloat();
dotY = (int)(f*h)%h;
}
20
DotSmasher (continued)
DotSmasherCanvas.java (continued)
protected boolean detectHit(int x, int y){
if((x>=dotX && x<=dotX+20) &&
(y>=dotY && y<=dotY+20)){
// You have a hit
return true;
}
return false;
}
21
DotSmasher (continued)
DotSmasherCanvas.java (continued)
protected void onDraw(Canvas canvas){
canvas.drawColor(Color.BLACK);
Paint dotPaint = new Paint();
dotPaint.setColor(Color.RED);
canvas.drawRect(dotX,dotY,dotX + 20,dotY
+ 20,dotPaint);
canvas.drawText("Score: " +
score,20,20,dotPaint);
}
}
Programming with Mobile Applications
22
DotSmasher (continued)
DotSmasherTimerTask.java
package com.dotsmasher;
import java.util.TimerTask;
import com.dotsmasher.DotSmasherCanvas;
public class DotSmasherTimerTask extends TimerTask {
DotSmasherCanvas canvas;
public DotSmasherTimerTask(DotSmasherCanvas canvas){
this.canvas = canvas;
}
@Override
public void run() {
canvas.moveDot();
canvas.postInvalidate();
}
}
Programming with Mobile Applications
23
DotSmasher (continued)
MainActivity.java
package com.dotsmasher;
import
import
import
import
android.app.Activity;
android.os.Bundle;
java.util.Timer;
android.view.*;
24
DotSmasher (continued)
MainActivity.java (continued)
public class MainActivity extends Activity {
private Timer timer;
private DotSmasherCanvas canvas;
private DotSmasherTimerTask task;
25
DotSmasher (continued)
MainActivity.java (continued)
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
setTitle("DotSmasher");
canvas = new DotSmasherCanvas(getBaseContext());
timer = new Timer();
task = new DotSmasherTimerTask(canvas);
timer.schedule(task, 0, 1500);
setContentView(canvas);
}
Programming with Mobile Applications
26
DotSmasher (continued)
MainActivity.java (continued)
@Override
public boolean
onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu,
menu);
return true;
}
Programming with Mobile Applications
27
DotSmasher (continued)
MainActivity.java (continued)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
newGame();
return true;
case R.id.item2:
quit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Programming with Mobile Applications
28
DotSmasher (continued)
MainActivity.java (continued)
void newGame(){
canvas.setScore(0);
}
void quit(){
timer.cancel();
task = null;
timer = null;
canvas = null;
finish();
}
}
Programming with Mobile Applications
29
DotSmasher (continued)
Figure 5-25 DotSmasher running in the emulator
30
31
32
33
Wheres My Phone?
Figure 5-29 The Wheres My Phone UI
34
Wheres My Phone?
(continued)
MainActivity.java
package com.wheresmyphone;
import android.app.Activity;
import android.os.Bundle;
import
android.content.SharedPreferences.Editor;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
Programming with Mobile Applications
35
Wheres My Phone?
(continued)
MainActivity.java (continued)
public class MainActivity extends Activity
implements OnClickListener{
private Button start;
private EditText pword;
private EditText confirm;
36
Wheres My Phone?
(continued)
MainActivity.java (continued)
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button)findViewById(R.id.button1);
pword = (EditText)findViewById(R.id.editText1);
confirm = (EditText)findViewById(R.id.editText2);
start.setOnClickListener(this);
}
37
Wheres My Phone?
(continued)
MainActivity.java (continued)
@Override
public void onClick(View v) {
String pass = pword.getText().toString();
String conf = confirm.getText().toString();
// Check that user typed a password
if(pass.length()==0){
Toast.makeText(this, "Please enter a
password",Toast.LENGTH_SHORT).show();
pword.requestFocus();
return;
}
38
Wheres My Phone?
(continued)
MainActivity.java (continued)
// Make sure two fields match
if(pass.equals(conf)){
// Fields match, store password in shared preferences
Editor passwdfile = getSharedPreferences("passwd", 0).edit();
passwdfile.putString("passwd",pass);
passwdfile.commit();
finish();
}else{ // password mismatch - start over
Toast.makeText(this, "Passwords must match",Toast.LENGTH_SHORT).show();
pword.setText("");
confirm.setText("");
pword.requestFocus();
return;
}
}
}
39
Wheres My Phone?
(continued)
Figure 5-32 The
New Android Broadcast Receiver Wizard
40
Wheres My Phone?
(continued)
WheresMyPhoneReceiver.java
package com.wheresmyphone;
import
import
import
import
import
import
import
import
import
android.content.BroadcastReceiver;
android.content.Intent;
android.content.Context;
android.content.SharedPreferences;
android.os.Bundle;
android.telephony.*;
android.widget.Toast;
android.location.*;
android.media.MediaPlayer;
41
Wheres My Phone?
(continued)
WheresMyPhoneReceiver.java (continued)
public class WheresMyPhoneReceiver
extends BroadcastReceiver implements
LocationListener{
String loc = "Location unknown";
LocationManager mgr;
String provider;
42
Wheres My Phone?
(continued)
WheresMyPhoneReceiver.java
(continued)
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences passwdfile = context.getSharedPreferences("passwd", 0);
String password = passwdfile.getString("passwd",null);
mgr =
(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setCostAllowed(true);
provider = mgr.getBestProvider(criteria,true);
mgr.requestLocationUpdates(provider,0,0,this);
Location lastLocation = mgr.getLastKnownLocation(provider);
if(lastLocation!=null)
loc = "Findme Latitude: " + lastLocation.getLatitude() + " Longitude: " +
lastLocation.getLongitude();
Programming with Mobile Applications
43
Wheres My Phone?
(continued)
WheresMyPhoneReceiver.java
(continued)
44
Wheres My Phone?
(continued)
WheresMyPhoneReceiver.java (continued)
@Override
public void onLocationChanged(Location location)
{
// Get location and store in loc
if(location == null){
location = mgr.getLastKnownLocation(provider);
}
loc = "Findme Latitude: " + location.getLatitude()
+ "\nLongitude: " + location.getLongitude();
}
45
Wheres My Phone?
(continued)
WheresMyPhoneReceiver.java (continued)
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle
extras) {
// TODO Auto-generated method stub
}
}
Programming with Mobile Applications
46
Wheres My Phone?
(continued)
Figure 5-33 The Permissions
tab for the AndroidManifest.xml file
47
Wheres My Phone?
(continued)
Figure 5-38 Wheres
My Phone running in the emulator
48
Wheres My Phone?
(continued)
49
Wheres My Phone?
(continued)
Figure 5-42 Sending a findme message to Wheres My Phone from a second
emulator
50
Wheres My Phone?
Figure(continued)
5-43 The Wheres My Phone
response
51