1 mobile computing java, android, and eclipse copyright 2015 by janson industries
TRANSCRIPT
1
Mobile Computing
Java, Android, and Eclipse
Copyright 2015 by Janson Industries
Copyright 2015 by Janson Industries2
Objectives▀ Explain
Application organization in Eclipse
Basic Java concepts
How to code and run an Android app in the emulator
Controlling the emulator
The Android app life cycle
Copyright 2015 by Janson Industries3
Eclipse▀ Has a variety of perspectives
Java, Debug, DDMS
▀ Each perspective consists of a unique set of functions and views of the application resources Java shows source code and allows the
programmer to edit it
Debug shows the stack trace (logic flow) of a running app
DDMS allows access to the device/emulator’s file system
Copyright 2015 by Janson Industries4
Perspective indicated in upper right hand corner
Java Perspective window initially consists of 6 panes – only need 4. Can close Task List and Connect Mylyn
Resize panes by clicking and dragging bordersDouble click view tab to expand view and fill perspective
window
Panes contain viewsViews indicated by tabs at top of pane, switch view by
clicking tab
Copyright 2015 by Janson Industries5
Can have multiple perspectives open but only one is active
Copyright 2015 by Janson Industries6
Open a new perspective by clicking Window, Open Perspective, then choose a perspective
Switch between perspectives by clicking perspective button
Copyright 2015 by Janson Industries7
Eclipse▀ All of an application’s
resources are stored in a project Source code
Images
XML
▀ The resources can be further organized into folders and packages
Copyright 2015 by Janson Industries8
Project
Package Folder Package Folder File
Eclipse
▀ Packages and folders hold the majority of an application’s resources Source code Images XML
▀ Java source code must go into a package
Copyright 2015 by Janson Industries9
Android Java
▀ An Android application’s programs are called activities
▀ Files with an extension of .java hold an activity’s source code
▀ To create an activity you have to have a project and a package to put it in
Copyright 2015 by Janson Industries10
Creating an Application▀ Click File, New and then Project
▀ Select Android Project
▀ Specify:
Project, package, activity and application names
A build target
Copyright 2015 by Janson Industries11
Click File, New, and Project then expand Android, select Android Application Project and click Next
Copyright 2015 by Janson Industries12
Give names to the Application (Howdy), Project (MyFirstProject) , Package (my.first.pkg), specify 2.1, click
Next
Copyright 2015 by Janson Industries13
Click Next
Creating an Application
Copyright 2015 by Janson Industries14
Can create a unique icon
We’ll accept default and click Next
Creating an Application
Copyright 2015 by Janson Industries15
Will create a Hello World activity for us
Click Next
Creating an Application
Copyright 2015 by Janson Industries16
Change activity name to HowdyActivity
Click Finish
Creating an Application
Copyright 2015 by Janson Industries17
Creating an Application Eclipse will create the
Project Packages and folders Files
It even creates a working application In a file called HowdyActivity.java File stored in a package called
my.first.pkg in source folder src
Copyright 2015 by Janson Industries18
To Run an Application In Package Explorer, expand
MyFirstProject, src, & my.first.pkg
Right click HowdyActivity and select Run As then Run Configurations
Select Android Application and click the New button
Copyright 2015 by Janson Industries19
Copyright 2015 by Janson Industries20
Give the configuration a name and specify the ProjectClick Apply and Run
Copyright 2015 by Janson Industries21
To Run an Application First time will take a while
Emulator must configure itself and will launch
The emulator is displayed
You have to click and drag the lock icon to see the results of the activity
Copyright 2015 by Janson Industries22
Click and drag the lock icon to the right
Copyright 2015 by Janson Industries23
If app doesn’t start, rerun in Eclipse
Copyright 2015 by Janson Industries24
Console should show that app was installed just not run
Copyright 2015 by Janson Industries25
Voila!
Copyright 2015 by Janson Industries26
To Run an Application Once emulator is running, results will
be shown must faster
To close emulator:
Right click Android button in the System Tray
Select Close Window
Or click the Close Window button
Can control the size of the emulator
Copyright 2015 by Janson Industries27
Control Emulator Size Run emulator before running an
activity. Click: Window (in the command bar)
AVD Manager
Select the AVD
Click Start
Click Scale display to real size
Specify screen size
Click Launch
Copyright 2015 by Janson Industries28
1
2
3
4
5
Copyright 2015 by Janson Industries30
New size fits on the screen better
Need to go back and close AVD Manager window
Copyright 2015 by Janson Industries31
How Does It Work The generated application is
pretty complicated and requires a lot of Java knowledge
Let’s first learn some Java (then some XML) and then generate our own application
Later we will cover the workings of the generated application
Copyright 2015 by Janson Industries32
Java Java programs are called classes
Classes are stored in files that have an extension of .java
Classes are comprised of a header and a body
Copyright 2015 by Janson Industries33
Java Class Class header defines:
The source code as a class (e.g. “class” keyword is used)
Access allowed (e.g. “public”)
The name of class Must begin with an upper case letter Is case sensitive Cannot contain spaces Must match .java file name prefix
• I.e. a class named Customer must be in a file named Customer.java
Copyright 2015 by Janson Industries34
Java Class The class body is enclosed in braces
{} and comprised of class/global variables and methods
Simple class example: public class ClassName {
global variable definition
global variable definition
method{}
method{}
}
Copyright 2015 by Janson Industries35
Java Method Comprised of a header and body
Header definition comprised of: Modifiers (e.g. “private”, “public”,
“static”) Return value (e.g. “void”, “String”) Method name
Begins with a lower case letter (e.g. getMailingLabel, main)
Parameter(s)/received value(s) in parenthesis (e.g. (String name), (int age), () means no params)
Copyright 2015 by Janson Industries36
Java Method Header Method header/definition examples:
public void setName(String custName)
public String getMailingLabel()
public static void main(String[ ] args) A static method can be run all by itself’
• It is self sufficient/stand alone
If multiple values passed/received simply separate by commas
(String itemName, int itemPrice)
Copyright 2015 by Janson Industries37
Java Method Header Private methods:
Can only be accessed/run by other methods within the class
Public methods: Can be accessed by objects
external to the class
Are considered the class “interface” This is how other classes/objects can
interface with this class
Copyright 2015 by Janson Industries38
Java Method Body Enclosed in braces { }
Comprised of:
Local variable definitions
Executable statements
Variable definition comprised of:
The variable type
The variable name
A semicolon (;)
Copyright 2015 by Janson Industries39
Java Method Body Variable definition examples
int age;
String customerName;
double salary;
String street, city, state, zip;
In addition, variable definitions can
Specify access modifiers
Initialize the variable
Copyright 2015 by Janson Industries40
Java Method Body Variable definition examples
private int age = 22;
String customerName = new String( “Joe”) ;
double salary = 1123.54;
public String street, city, state, zip;
Executable statements also must end in semicolons
System.out.println(“Howdy”);
Copyright 2015 by Janson Industries41
Java Method Body Example
public void onCreate(Bundle aBundle) {
super.onCreate(aBundle);
String greeting = new String(“******Hello*******”);
System.out.println(“A print of static text");
System.out.println(“The value of greeting is: ” + greeting);
}
statementsvariabledefinitio
n
Copyright 2015 by Janson Industries42
Classes If a class is stored in a package,
the class must have a package statement at the very beginning of the source code
So for example, the HowdyActivity class has the following:
package my.first.pkg;
Copyright 2015 by Janson Industries43
Activity Classes Activity classes are executable
Some special requirements The class must be defined as an
acitivty When first run, the activity’s
onCreate method will be executed onCreate must
accept a Bundle objectcall it’s superclass’ onCreate
method and pass the bundle
Copyright 2015 by Janson Industries44
Superclass All classes are related in a
hierarchy
This parent/child relationship is called a superclass/subclass relationship for java classes
Just like in real life the child/subclass inherits all the parent/superclass’ variables and methods
Copyright 2015 by Janson Industries45
Superclass For example, an EditText class is
a visual component that a user can enter text into
This is it’s lineage:
Object
View
TextView
EditText
Copyright 2015 by Janson Industries46
Import Statements All the java classes in the SDK are
stored in packages
To use these classes you can specify the location (i.e. the package(s) that hold them android.app.Activity
android.os.Bundle
This is called a fully qualified file reference
Copyright 2015 by Janson Industries47
Import Statements Fully qualified file references
mean extra typing and more errors
If import statements are added we can use non-fully qualified file references for the classes (Activity, Bundle )
import android.app.Activity;
import android.os.Bundle;
Copyright 2015 by Janson Industries48
Import Statements The import statements come after
the package statement but before the class header
Now if we want to use the Bundle class we can type Bundle
Instead of android.os.Bundle
Copyright 2015 by Janson Industries49
Import Statements So you can use fully qualified file
references like this :
Or use import statements and non-fully qualified file references like this :
public void onCreate(Bundle aBundle) {
public void onCreate(android.os.Bundle aBundle) {
Copyright 2015 by Janson Industries50
Activity Classes To define the class as an activity (I.e. a subclass of the
Activity class) an extends clause must be included in the class header as follows:
Comments (non-executable statements) preceded by //
public class HowdyActivity extends Activity {
Copyright 2015 by Janson Industries51
Putting It All Togetherpackage my.first.pkg; //Identifies the package the class is in
import android.app.Activity; //Identifies the location of classes import android.os.Bundle; //this class will be using
public class HowdyActivity extends Activity { //Class header
//Method header public void onCreate(Bundle savedInstanceState) { //Superclass’ onCreate method invoked super.onCreate(savedInstanceState); //String variable defined and initialized String greeting = new String("******Hello*******"); //Two lines of text are displayed System.out.println("A print of static text"); System.out.println("The value of greeting is: " + greeting); }}
Copyright 2015 by Janson Industries52
Putting It All Together So in HowdyActivity:
Comment out the one setContentView statement Precede the statement with // Keystroke short cut:
• Select the statement• Click Ctrl+/
After the commented out statement, add the three statements from the previous slide that
Create the String variable Display the two lines of text
Copyright 2015 by Janson Industries53
Putting It All Together Code should look like this
Copyright 2015 by Janson Industries54
Running the New App In the Package Explorer view, select the MyFirstProject
Click the Run button (green circle with white arrow head) You’ll be prompted to save the changes
Click Yes
Nothing happened!?! This gives us the opportunity to introduce LogCat
Copyright 2015 by Janson Industries55
LogCat LogCat holds all the system generated msgs and any println statements run in
the code
If LogCat not displayed at bottom of window, display by clicking: Window Show View Other Android (to expand it) LogCat OK
Copyright 2015 by Janson Industries56
LogCat If your LogCat has no msgs (as
below) it is because the emulator doesn’t have “focus”
Copyright 2015 by Janson Industries57
Switch to DDMS perspective (Window, Open Perspective) and click on the emulator in
the Devices view
Copyright 2015 by Janson Industries58
If nothing appears, click the down arrow and select Reset adb
Emulator will be redisplayed
Copyright 2015 by Janson Industries59
Go back to the Java perspective and scroll to the right in LogCat to display all the text
Common mistake: looking at the console not LogCat
Copyright 2015 by Janson Industries60
If app rerun, info will not be redisplayed because app is already created
Prove by clearing LogCat and rerunning
Copyright 2015 by Janson Industries61
New system msgs will be there but not the text from the app
This brings up the Android application life cycle!
Copyright 2015 by Janson Industries62
Application Life Cycle▀ There are 4 states that an application
can be in Active: the activity can be used by the user
Paused: The activity is partially obscured (a new non-full screen or transparent activity is active)
Stopped: The activity is totally obscured (a new full screen activity is active)
Finished: the activity has been closed.
Copyright 2015 by Janson Industries63
Application Life Cycle▀ Based on changes in the application’s
“state”, several other methods will be called : protected void onStart(){}
protected void onRestart(){}
protected void onResume(){}
protected void onPause(){}
protected void onStop(){}
protected void onDestroy(){}
Copyright 2015 by Janson Industries64
Application Life Cycle▀ An application’s “state” can be
changed by user actions like:
Starting a new application
Closing an application
▀ What the new state will be will vary by what is being run Does new app take up the whole
screen?
Is there enough MM for new app?
Copyright 2015 by Janson Industries65
Application Life Cycle▀ For example, when an app is
first run it means the following methods will be run:
onCreate()
onStart()
onResume()
▀ Let’s prove it!
Copyright 2015 by Janson Industries66
Application Life Cycle▀ We’ll add the following two new
methods:
▀ And change onCreate a little
protected void onStart(){super.onStart();System.out.println("*****onStart was run");
}
protected void onResume(){super.onStart();System.out.println("*****onResume was run");
}
Copyright 2015 by Janson Industries67
Here’s all the new code
Copyright 2015 by Janson Industries68
Application Life Cycle▀ Need a new emulator with the
buttons enabled
▀ Need to clone a definition Only user defined emulators can
be edited
▀ Start the AVD manager
Copyright 2015 by Janson Industries69
Click Device Definitions tab then Double click Galaxy
Nexus definition
Edit definition, click Clone
Device
Copyright 2015 by Janson Industries70
▀ Define new AVD
▀ Select the first Galaxy Nexus listed
▀ If correct one selected, RAM will be 512
▀ Fill in rest of info
Copyright 2015 by Janson Industries71
Select and Start the new emulator
Copyright 2015 by Janson Industries72
Run app and LogCat shows the msgs
Copyright 2015 by Janson Industries73
In emulator, click home button to stop the app
Run the app again
Copyright 2015 by Janson Industries74
Scroll up and notice onCreate was not run, that’s because app was already created but
stopped
Copyright 2015 by Janson Industries75
The Whole Thing
Active
ActivityStarted
onStart
onResume
onCreate
onPause
Paused Stoppedon
Stop
onRestart
Finished
onDestroy
Whoa! Maybe we should go step by
step
Copyright 2015 by Janson Industries
In the Beginning
76
Active
ActivityStarted
onStart
onResume
onCreate
▀ When the application is first run…
Copyright 2015 by Janson Industries
From an Active State
77
▀ The application can go to any of the other three states…
Activeon
Pause Paused
onStopActive
onPause Finishe
d
onDestroy
Activeon
Pause Stoppedon
Stop
Copyright 2015 by Janson Industries
From an Paused State
78
▀ The application can go Active or Stopped states…
Paused
Stopped
Active
onResume
onStop
Copyright 2015 by Janson Industries
From an Stopped State
79
▀ The application can go to Finished or Active states…
Activeon
Restart
Finished
onDestroy
Stopped
onStart
onResume
Copyright 2015 by Janson Industries80
Android App Life Cycle▀ Why all the different methods?
▀ You might want the app to do different functions when the state is changed When closed, free up resources
When restarted, refresh info on screen
When paused, stop playing music
Copyright 2015 by Janson Industries81
Emulator Glitches▀ When emulator run, message that says
something like:
Image is used by another emulator
▀ Need to go out and delete these two files in the emulator definition
▀ Substituting for username and emulator name
C:/Users/username/.android/avd/EmulatorName/cache.img
C:/Users/username/.android/avd/EmulatorName/userdata-qemu.img
Copyright 2015 by Janson Industries82
Emulator Glitches▀ If it starts running slowly or if logcat isn’t
working well
Not displaying msgs quickly
Not allowing msg deletions
▀ Restart Eclipse
▀ Gives Eclipse a chance to clean up internally
Copyright 2015 by Janson Industries83
Emulator Glitches▀ If you get this msg:
ADB server didn't ACK, failed to start daemon
▀ Start Task Manager and kill the adb.exe process
▀ Close and restart Eclipse
Copyright 2015 by Janson Industries84
Points to Remember▀ Java classes stored in a project's
package
▀ Java class consists of global level variables and methods
▀ Java method consists of local level variables and executable statements
▀ Activity classes are executable
Copyright 2015 by Janson Industries85
Points to Remember▀ LogCat displays system and
program msgs
▀ An app can be in four states Active
Paused
Stopped
Finished
▀ Changes in state will result in different methods being executed