Anda di halaman 1dari 51

Programming with Mobile

Applications
Chapter 5: Google Android:
Motorola MOTODEV Studio

In Chapter 5, You Learn to


Distinguish between Eclipse and
MOTODEV Studio
Use MOTODEV Studio to create Android
apps
Create Android Services and Broadcast
Receivers
Create a standard Hello World app
that displays an alert message
Handle click and touch events
Programming with Mobile Applications

In Chapter 5, You Learn to


(continued)
Write a basic game program that draws
onscreen
Use Java Timer and TimerTask classes
Create context menus
Store and retrieve app data
Play sounds in code
Use the Location API
Send and receive text (SMS) messages
Programming with Mobile Applications

Why MOTODEV Studio?


It uses the latest version of the
Eclipse IDE.
It integrates the Android SDK.
It allows you to choose the Android
version, including the latest version,
your app supports.
A single installation includes
everything you need.
Programming with Mobile Applications

Android Components

Activities
Services
Broadcast Receivers
Content Providers

Programming with Mobile Applications

The Anatomy of a Java Class


Packages
Imports
Class Declaration
Extends
Implements

Variables
Methods
Constructors
Programming with Mobile Applications

MOTODEV Studio for Android


Perspective
Figure 5-2 The MOTODEV Studio for Android
perspective

Programming with Mobile Applications

Hello Android!
Figure 5-5 The main.xml file in the Graphical
Layout view

Programming with Mobile Applications

Hello Android! (continued)


MainActivity.java
package com.helloandroid;
import
import
import
import
import

android.app.Activity;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.*;

Programming with Mobile Applications

Hello Android! (continued)


MainActivity.java (continued)
public class MainActivity extends
Activity implements OnClickListener{
private Button btn;
private EditText edit;
private TextView view;

Programming with Mobile Applications

10

Hello Android! (continued)


MainActivity.java (continued)
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit = (EditText)findViewById(R.id.editText1);
view = (TextView)findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
}
Programming with Mobile Applications

11

Hello Android! (continued)


MainActivity.java (continued)
@Override
public void onClick(View v) {
if(btn==v){
String msg = "Welcome to Android, " + edit.getText()+
"!";
Toast toast =
Toast.makeText(this,msg,Toast.LENGTH_SHORT);
toast.show();
view.setText(msg);
}
}
}
Programming with Mobile Applications

12

Hello Android! (continued)

Figure 5-14 Hello Android after entering text and pressing the button

Programming with Mobile Applications

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

Programming with Mobile Applications

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.*;

Programming with Mobile Applications

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;
}

Programming with Mobile Applications

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
}

Programming with Mobile Applications

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;
}

Programming with Mobile Applications

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;
}

Programming with Mobile Applications

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;
}

Programming with Mobile Applications

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.*;

Programming with Mobile Applications

24

DotSmasher (continued)
MainActivity.java (continued)
public class MainActivity extends Activity {
private Timer timer;
private DotSmasherCanvas canvas;
private DotSmasherTimerTask task;

Programming with Mobile Applications

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

Programming with Mobile Applications

30

Packaging and Deployment


File > Export
Expand Android node
Export Android application using
MOTODEV Studio for Android
Sign the package
Create a new, self-signed certificate

Programming with Mobile Applications

31

Packaging and Deployment


(continued)
Figure 5-28 Creating a self-signed certificate

Programming with Mobile Applications

32

Deploying to the Android


Market
1. Sign up for the Android Market at
http://market.android.com/publish/sign
up
.
2. Create a developer profile.
3. Pay a $25 registration fee with a credit
card, using Google Checkout.
4. Agree to the Android Market developer
distribution agreement.
5. Upload your .apk file.

Programming with Mobile Applications

33

Wheres My Phone?
Figure 5-29 The Wheres My Phone UI

Programming with Mobile Applications

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;

Programming with Mobile Applications

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);
}

Programming with Mobile Applications

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;
}

Programming with Mobile Applications

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;
}
}
}

Programming with Mobile Applications

39

Wheres My Phone?
(continued)
Figure 5-32 The
New Android Broadcast Receiver Wizard

Programming with Mobile Applications

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;

Programming with Mobile Applications

41

Wheres My Phone?
(continued)
WheresMyPhoneReceiver.java (continued)
public class WheresMyPhoneReceiver
extends BroadcastReceiver implements
LocationListener{
String loc = "Location unknown";
LocationManager mgr;
String provider;

Programming with Mobile Applications

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)

// Get the messages - PDU = protocol description unit


Bundle bundle = intent.getExtras();
Object[] pdusObj = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdusObj.length];
for (int i = 0; i<pdusObj.length; i++) {
messages[i] = SmsMessage.createFromPdu ((byte[])pdusObj[i]);
}
for (SmsMessage msg : messages) {
// Make sure it's a findme message
if (msg.getMessageBody().contains("findme:" + password)) {
String to = msg.getOriginatingAddress();
SmsManager sm = SmsManager.getDefault();
sm.sendTextMessage(to, null, loc, null, null);
Toast.makeText(context,"Location sent to: " + to + " using provider: " + provider,
Toast.LENGTH_LONG).show();
MediaPlayer mp = MediaPlayer.create(context, R.raw.keys1);
mp.start();
}
}

Programming with Mobile Applications

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();
}

Programming with Mobile Applications

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

Programming with Mobile Applications

47

Wheres My Phone?
(continued)
Figure 5-38 Wheres
My Phone running in the emulator

Programming with Mobile Applications

48

Wheres My Phone?
(continued)

Programming with Mobile Applications

49

Wheres My Phone?
(continued)
Figure 5-42 Sending a findme message to Wheres My Phone from a second
emulator

Programming with Mobile Applications

50

Wheres My Phone?
Figure(continued)
5-43 The Wheres My Phone
response

Programming with Mobile Applications

51

Anda mungkin juga menyukai