ANDROID MOBILE APPLICATION FOR TRACKING YOUR TIME AND DISTANCE TRAVELLED A Project

advertisement
ANDROID MOBILE APPLICATION FOR TRACKING YOUR TIME AND
DISTANCE TRAVELLED
A Project
Presented to the faculty of the Department of Computer Science
California State University, Sacramento
Submitted in partial satisfaction of
the requirements for the degree of
MASTER OF SCIENCE
in
Computer Science
by
Sudhir Pandiri
FALL
2012
ANDROID MOBILE APPLICATION FOR TRACKING YOUR TIME AND
DISTANCE TRAVELLED
A Project
by
Sudhir Pandiri
Approved by:
__________________________________, Committee Chair
Dr. Jinsong Ouyang
__________________________________, Second Reader
Dr. Ying Jin
____________________________
Date
ii
Student: Sudhir Pandiri
I certify that this student has met the requirements for format contained in the University
format manual, and that this project is suitable for shelving in the Library and credit is to
be awarded for the Project.
__________________________, Graduate Coordinator
Dr. Nikrouz Faroughi
Department of Computer Science
iii
________________
Date
Abstract
of
ANDROID MOBILE APPLICATION FOR TRACKING YOUR TIME AND
DISTANCE TRAVELLED
by
Sudhir Pandiri
Nowadays as the technology is growing fast, people are occupied with lots of things and
want to manage the time efficiently. This is the location aware application that helps in
knowing the time spent at different locations, which helps users to track their time and
manage. This application is more attractive in its way of displaying the data in charts in a
way that is easily comprehensible for the human. It also keeps track of the number of
miles the user has travelled to and from his desired locations. User need not worry about
turning on application each time; once it’s turned on it runs in background until the user
stops the service manually. It is developed using Android API’s and implemented in
JAVA language.
_______________________, Committee Chair
Dr. Jinsong Ouyang
_______________________
Date
iv
ACKNOWLEDGEMENTS
I would like to thank Dr. Jinsong Ouyang, my project advisor for providing me a
wonderful opportunity to work on this project, which provided a great exposure to the
field of Mobile Application Development. I thank him for providing all the help, support
and necessary resources to complete the project successfully. Dr. Ouyang helped me in
understanding the project in detail and provided knowledge and expertise in the field to
understand the project and completing it successfully.
In addition, I would like to thank Dr. Ying Jin for her willingness to serve on the
committee.
Lastly, I would like to thank the entire faculty and staff of the Department of Computer
Science Engineering at California State University, Sacramento.
v
TABLE OF CONTENTS
Page
Acknowledgements………………………………………………………………………..v
List of Figures…………………………………………………………………………….ix
Chapter
1.INTRODUCTION…….………………………………………………………………...1
2.PROJECT REQUIREMENTS….………………………….……………………………2
2.1 User Requirements .................................................................................................... 2
2.1.1. Save Locations ................................................................................................... 3
2.1.2. View and Edit Locations ................................................................................... 3
2.1.3 Delete Locations ................................................................................................. 4
2.1.4 Start Service ........................................................................................................ 5
2.1.5 Stop Service ........................................................................................................ 5
2.1.6 Parameters .......................................................................................................... 5
2.1.7 Time Tracked ...................................................................................................... 6
2.1.8 Miles Tracked ..................................................................................................... 7
2.2 Operating Requirements ............................................................................................ 8
3.ANDROID FRAMEWORK AND SOFTWARE ENVIRONMENT……………….…..9
vi
3.1 Main Components of Android................................................................................... 9
3.1.1 Activity ............................................................................................................... 9
3.1.2 Service .............................................................................................................. 11
3.1.3 Broadcast Receiver ........................................................................................... 12
3.2 Activating and Deactivating Components............................................................... 12
3.3 Manifest file ............................................................................................................ 12
3.4 Layout File .............................................................................................................. 15
3.5 Data Storage ............................................................................................................ 16
3.6 Architecture of Android Application Processing .................................................... 18
3.7 Tools Required ........................................................................................................ 18
3.8 Android SDK Installation........................................................................................ 19
3.9 Install ADT Plugin for Eclipse ................................................................................ 20
3.10 Configure ADT Plugin for Eclipse........................................................................ 22
3.11 Creating Android Project ...................................................................................... 23
3.12 Directories and Files in Android Project ............................................................... 25
3.13 Running Android Application ............................................................................... 26
3.13.1 Running on Emulator...................................................................................... 26
3.13.2 Running on a Device ...................................................................................... 27
vii
3.14 Coding for Application that Displays Hello World .............................................. 27
3.15 Debugging the Application ................................................................................... 28
4.ANDROID APPLICATION FOR TRACKING TIME AND MILES TRAVELLED..32
4.1 Save, Edit, Delete and View Favorite Locations .................................................... 32
4.2 Implementation of Tracking Time .......................................................................... 42
4.3 Implementation of Tracking Miles Travelled ......................................................... 44
4.4 Launching the Application on Startup .................................................................... 46
4.5 Android Plot for Generating Charts ........................................................................ 47
4.5.1 Set the Format for Line and Points ................................................................... 47
4.5.2 Create Series to be Plotted on Chart ................................................................. 48
4.5.3 Add Series to the Chart ..................................................................................... 48
4.5.4 Setting the Axis Values .................................................................................... 48
4.6 Time Activity .......................................................................................................... 49
4.7 Monthly Raw Data Time ......................................................................................... 50
4.8 Data Charts .............................................................................................................. 55
4.9 Summary and Future Work ..................................................................................... 59
5. CONCLUSION……………………………………………………………….……….60
References………………………………………………………………………………..61
viii
LIST OF FIGURES
Figures
Page
Figure 1 USE Case Diagram for Application ..................................................................... 2
Figure 2 Android Activity Life Cycle .............................................................................. 10
Figure 3 Android Service Life Cycle ............................................................................... 11
Figure 4 XML File for Text View and Button. ................................................................. 16
Figure 5 Code Snippet for Shared Preferences ................................................................. 16
Figure 6 Architecture of Android Application.................................................................. 18
Figure 7 Android SDK Manager Screenshot .................................................................... 19
Figure 8 Install ADT Plugin Screenshot 1 ........................................................................ 20
Figure 9 Install ADT Plugin Screenshot 2 ........................................................................ 21
Figure 10 Install ADT Plugin Screenshot 3 ...................................................................... 21
Figure 11 Configure ADT Plugin ..................................................................................... 22
Figure 12 Creating Android Project .................................................................................. 23
Figure 13 Creating Android Project Select Build Target.................................................. 24
Figure 14 Create Android Project Form ........................................................................... 25
Figure 15 Android Virtual Device Manager ..................................................................... 26
Figure 16 Code Snippet of HelloWorldActivity.java ....................................................... 27
Figure 17 Code Snippet for main.xml............................................................................... 28
Figure 18 LogCat Screenshot............................................................................................ 30
ix
Figure 19 Error Log Screenshot ........................................................................................ 31
Figure 20 Code Snippet of XML File for Button ............................................................. 33
Figure 21 Code Snippet of Activity Class ........................................................................ 33
Figure 22 Save Location Activity ..................................................................................... 34
Figure 23 Calculating the Distance between Latitude and Longitude Points ................... 38
Figure 24 View Locations Activity................................................................................... 39
Figure 25 Delete Location Activity .................................................................................. 41
Figure 26 Code Snippet for Deleting Elements from List …. .......................................... 42
Figure 27 Code Snippet for Launching Application on Startup ....................................... 46
Figure 28 Code Snippet for Formatting Axis Values ....................................................... 49
Figure 29 Time Tracked Activity ..................................................................................... 50
Figure 30 Monthly Raw Data Spinner .............................................................................. 51
Figure 31 View Locations Data Activity .......................................................................... 54
Figure 32 Data Charts Monthly ........................................................................................ 56
Figure 33 Data Charts Weekly.......................................................................................... 57
Figure 34 Expandable List for Weekly Activity ............................................................... 58
x
1
Chapter 1
Introduction
As the technology is advancing rapidly people are involved in many things, they are
required to do lots of things simultaneously. In the developed era of computing it is
highly required to manage the time efficiently. This application serves the purpose by
letting user to track their time spent at their favorite locations.
Users can save their favorite location when they visit the place for the first time, when the
user visits the same place again the tracking starts automatically. There is no need of user
intervention.
It also tracks the miles travelled to the favorite locations which helps the user to also
manage the miles travelled.
Charts are designed using Android plot library which are easily human comprehensible
2
Chapter 2
Project Requirements
2.1 User Requirements
The main purpose of this application is to track the time spent by user at the favorite
locations and the miles travelled between favorite locations. It lessens burden to the user
as there is no need of user interruption when the person goes to the favorite place, it
automatically starts tracking data.
Figure 1 USE Case Diagram for
Application
3
2.1.1. Save Locations
This function allows users to save favorite locations. On saving location as favorite it will
be added to track list. Application starts tracking when user goes to the favorite place.
User Sequence

User clicks the button save locations

Click current location, gets the location using GPS signal. type user preferred
alias name and then click save location

User can also manually input the address and alias and click save button

Click save button saves the location in the database
Functional Requirements

Current location uses GPS signal, Network provider and location used by other
applications.

It sorts out the best and displays the location address to user

Better signal strength determines the accuracy of the location obtained.
2.1.2. View and Edit Locations
This functionality allows the user to view and edit the locations already saved.
User Sequence

User clicks the View and Edit locations button, displays the locations already
saved

Click the location to edit, displays the form which was used for saving the
location
4

User can edit the details in the form and click save button
Functional Requirements

View locations is the list of locations

Edit location generates the form populated with the location details to be altered

On click save button updates the entry in the database
2.1.3 Delete Locations
This functionality allows the user to delete already saved locations.
User Sequence

User clicks the button delete location

Click on the list to select any location to be deleted

On selecting the location displays a pop up box asking user if he is sure he wants
to delete the location.

On click “OK” will delete the location

On click “Cancel” will not make any changes to the existing locations
Functional Requirements

On selecting a particular location to deleted it pops up box for confirmation from
user

On selecting delete will execute delete query and particular row will be deleted
from the database

On selecting can will not make any changes to the database
5
2.1.4 Start Service
This functionality will allow user to start service which tracks the data for user.
User Sequence

User clicks the button start service
Functional Requirements

On click start service will start the android service

Android service will be running in background continuously

Services are used for long running operations which does not require any user
interruption
2.1.5 Stop Service
This functionality stops the background service that is already running
User Sequence

Click the stop service button
Functional Requirements

On click stop service will stop the running android service
2.1.6 Parameters
This functionality allows users to set the time and distance parameters for getting the
location updates from the location provider
6
User Sequence

Click parameter button will generate the form displaying fields for time and
distance

User can fill the distance in meters and time in minutes

Click the save button
Functional Requirements

User can save the parameters distance and time to get the location updates

Location updates from network provider are obtained only when the parameters
are met

Setting values to low will get the location updates frequently which drains the
battery but gets the data accurately

Parameter values should be set based on user preference
2.1.7 Time Tracked
This functionality gives you the data for the time spent at the favorite locations in terms
of charts and also generates raw data in the form of list for monthly and weekly analysis
User Sequence

Click the button time tracked will generate four buttons

On selecting monthly raw data time, displays the spinner list of months. Selecting
month will display data for that month

On selecting monthly charts time, displays the spinner list of months. Selecting
month will display charts for that month
7

On selecting button weekly time raw data will display expandable list of months,
on selecting the month will display options to select the week of the month. Once
the week is selected the data will be displayed for that particular month and week.

On selecting button weekly time chart will display expandable list of months, on
selecting the month will display options to select the week of the month. Once the
week is selected the charts will be displayed for that particular month and week.
Functional Requirements

User can view only required data

On selecting particular month will filter the data pertaining to the month selected

On selecting month and week will filter the data accordingly
2.1.8 Miles Tracked
This functionality gives you the data for the miles travelled to the favorite locations in
terms of charts and also generates raw data in the form of list for monthly and weekly
analysis
User Sequence

Click the button miles tracked will generate four buttons

On selecting monthly raw data miles, displays the spinner list of months.
Selecting month will display data for that month

On selecting monthly charts miles, displays the spinner list of months. Selecting
month will display charts for that month
8

On selecting button weekly miles raw data will display expandable list of months,
on selecting the month will display options to select the week of the month. Once
the week is selected the data will be displayed for that particular month and week.

On selecting button weekly miles chart will display expandable list of months, on
selecting the month will display options to select the week of the month. Once the
week is selected the charts will be displayed for that particular month and week.
Functional Requirements

User can view only required data

On selecting particular month will filter the data pertaining to the month selected

On selecting month and week will filter the data accordingly
2.2 Operating Requirements

Android operating system mobile

Operating system version should be 2.2 (Froyo) and above

Should have WIFI, GPS and cellular data.
9
Chapter 3
Android Framework and Software Environment
Android operating system is the multi user Linux system. Each application has its own
user ID, so each application is safely secured in a sandbox which prevents unauthorized
access. Application can access other application data by user granting the permissions at
the time of install.
3.1 Main Components of Android

Activity

Service

Broadcast Receiver

Content Provider
3.1.1 Activity is the screen which the user interacts. All the screens displayed in the
application are generated by inheriting the Activity class. User interruption is required for
the activities. User can start different activity from the current activity.
Life Cycle of Activity:
Below is the figure showing the life cycle of activity. “OnCreate()” method is called
when the activity is created. We can override this function in our activity class to
implement the necessary functionality. “OnStart()” and “OnResume()” will be called
after the activity is created. While the activity is being destroyed “OnDestroy()” method
will be called.
10
Figure 2 Android Activity Life Cycle [1]
11
3.1.2 Service is the component that runs in background. There is no need for the user
interruption. Especially service is used for the process like downloading files, playing
music while using other applications. Services are created by inheriting Service class.
Figure 3 Android Service Life Cycle [1]
12
3.1.3 Broadcast Receiver receives the events that are broadcasted. It is generally used as
the trigger to fire some events. For example we can start the application automatically
when the phone is switched on by using this receiver. When phone is restarted the
android operating system broadcasts a message and the broadcast receiver in the
application gets the message and it can be used as trigger to launch the application.
3.2 Activating and Deactivating Components
Activity: this component can be started using “startActivity()” method. This method
takes the intent as an argument.
Service can be started using the “startService()” method. This method takes the intent as
argument. It can be stopped using “stopService()” method.
3.3 Manifest file
Manifest file is the main configuration file for the application. Android system reads the
manifest file first and knows about the application. All the components used by the
application must be declared in the manifest file. If the component is not declared in the
manifest file the application will never make use of that component. It is an xml file so all
the code must be written using tags like shown below.
Declaring components in the manifest file:
Activity:
<activity android:name=".MainActivity" android:label="Main Activity Label">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
13
In the above lines of manifest file we are declaring the activity using the activity tags it
has two parameters “android:name” and “android:label”. Parameter android:name should
be given the name of activity preceding the ‘.’ Symbol. “MainActivity” is the name of the
class that inherits the activity class. “Main Activity Label” is the label that is displayed
on
the
screen
header
when
the
activity
is
launched.
“android.intent.category.LAUNCHER” states the activity to be launched when the
application is started.
Service:
<service android:name=".BackgroundService" android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.learner.tracktime.BackgroundService" />
</intent-filter>
</service>
In the above lines of manifest file we are declaring the service using the service tags.
“android:name” should be given the name of the class that extends service.
“BackgroundService” is the class that extends service. “android:enabled” denotes
whether the android system can instantiate the component. “android:exported” denotes
whether the component can be started by components of other application.
<intent-filter> While starting the component we need to pass the intent. If the intent filter
defined for the component, matches the intent passed then the component is launched.
<receiver android:name=".ServiceManager">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
14
In the above lines of code we are declaring the broadcast receiver. “android:name”
declares the name of the class that extends the BroadcastReciever class. Intent filter in the
above defines the intent as “BOOT_COMPLETED”. So when the android system
broadcasts the message “BOOT_COMPLETED” the following receiver will be enabled.
Manifest file starts and ends with <manifest> tag. Application is defined with in
<Application> tags. <uses-sdk/> tag is used for defining the minimum and target sdk
version of the android system. Below lines show
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />
android:minSdkVersion describes the minimum version on which the application will run
and the android:targetSdkVersion states the platform for which the application is
developed.
When the application is deployed in android market it uses these parameters and displays
the application in the market only if the android version of the mobile meets the
requirements.
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Uses permission tag is used to display the set of permission that needs to be obtained
from the user. The above tag asks the user for permission, if the application can make use
of the location from network provider.
<uses-library android:name="com.google.android.maps" />
Uses-library tag is used to specify if any libraries are used by the application. The above
tag states that the android maps library is used by the application.
15
3.4 Layout File
User interface in android is defined using layout file which is in xml format. We have
two options to define interface

Graphical Layout

Xml file
Graphical layout shows the screen where we can drag and drop required widgets and the
code in xml file is auto generated. Developers can manipulate interface using the
Graphical layout or xml file.
Interface can be defined in different layouts:

Linear Layout

Relative Layout

List View

Grid View
Linear Layout: Organizes its children in horizontal or vertical fashion.
Relative Layout: Organizes its children position relative to other elements
List View: Elements are in the list format, it is scrollable.
Grid View: Elements are in the form of grid with rows and columns.
16
Sample XML file defining the interface:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView android:id="@+id/textView1" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world" tools:context=".MainActivity" />
<Button android:id="@+id/buttonDeleteLocations"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView1"
android:layout_alignParentLeft="true"
android:text="@string/buttonDeleteLocations" /> </RelativeLayout>
Figure 4 XML File for Text View and Button.
3.5 Data Storage
User can store their data in

Shared Preferences

SQLite Database
Shared Preferences:
It stores the data in the format of key and value. It is faster for the data retrieval. Retrieval
requires knowing the key which is the overhead. But if there only few set of key and
values it is efficient to store the data in the shared preference.
SharedPreferences prefer= this.getSharedPreferences(getClass().getSimpleName(),
Context.MODE_PRIVATE);
SharedPreferences.Editor preferEditor= prefer.Edit(); preferEditor.putInt(“flag”,0);
Figure 5 Code Snippet for Shared Preferences
17
Above lines of code shows how to store the integer value in the shared preferences. First
argument to “getSharedPreferences()” is the
name of the preferences
file.
SharedPreferences.Editor should be used to store the values in the shared preferences.
Prefs.getInt(“flag”,1) is used for retrieving the values from shared preferences by giving
the key. In the above line flag is the key and ‘1’ indicates the default value to be assigned
if the particular key is not found.
SQLite Database:
This is the persistent storage and the data is stored in the structured format. Retrieval is
not as fast as shared preferences, but this facilitates the storage of the large data in an
organized format.
Two main tools for using SQLite database are:
SQLite Open Helper
SQLite Database
SQLite Open Helper: this class helps in creating, opening, upgrading the database.
SQLite Database: this is the main class that helps in modifying the contents of the
database.
We need to inherit the “SQLiteOpenHelper” class and implement the onCreate() ,
onUpgrade() methods. We use getWritableDatabase() method to get the database object.
With the database object we can use methods in the SQLite Database to insert, update
columns and rows in the database.
18
3.6 Architecture of Android Application Processing
Below is the architecture the way android application is process and deployed in to
mobile. Finally Android Package (.apk) is deployed on to mobile.
Compiler
Java Source File
(.java)
Tool dx
Dalvik Executable
(.dex)
Java Class Files (.class)
Dalvik Executable (.dex)
Resources (images + xml files)
Android Asset Packaging tool
Android Package (.apk)
Figure 6 Architecture of Android Application
3.7 Tools Required

Android SDK

ADT Plugin 20.0.0 or higher

Eclipse

Using SDK Manager download latest SDK tools

Java SE
19
3.8 Android SDK Installation
Download android SDK from http://developer.android.com/sdk/index.html . Install by
using the install package. Once the SDK is installed you can go to the default android
SDK directory and click SDK Manager.exe which opens android SDK and populates
automatically list of packages.
Figure 7 Android SDK Manager Screenshot
In the above SDK Manager
Tools: this is required to install for the first time. Make sure to keep the latest SDK Tools.
Install the Android SDK Platform-tools
SDK Platform: Users must at least install one package on which they can run their
application
20
3.9 Install ADT Plugin for Eclipse
Start eclipse then click help -> Install New Software
Figure 8 Install ADT Plugin Screenshot 1
21
Click Add displays the below window
Figure 9 Install ADT Plugin Screenshot 2
Click “OK” after entering the name and location as specified above.
Figure 10 Install ADT Plugin Screenshot 3
22
In the above window check the option Developer Tools and click Next and then window
will pop up showing the list of tools to be downloaded, accept the terms and then click
finish and download, after installing the tools restart the eclipse.
3.10 Configure ADT Plugin for Eclipse
In eclipse select window->preferences then select Android tab. Select the SDK Location
by browsing the directory. Click OK.
Figure 11 Configure ADT Plugin
23
3.11 Creating Android Project
Click new Android app project in the tool bar
Figure 12 Creating Android Project
Type the project name click next and select the Build Target
24
Figure 13 Creating Android Project Select Build Target
On click next below window pops up, fill the details.
25
Figure 14 Create Android Project Form
Enter the application name, package name, minimum SDK in which the application
should run. Click finish.
3.12 Directories and Files in Android Project
AndroidManifest.xml: this file has all the project configurations.
src/: All the source files are in this directory.
26
res/: This directory has all the resource files.
res/layout/: This directory has the xml files that define the interface for the application
res/values/: This directory has the values for the resources such as strings to be used in
application.
3.13 Running Android Application
To run android application there are two options:

Running on emulator

Running on Device
3.13.1 Running on Emulator
To run on emulator, new android virtual device needs to be created using android virtual
device manager icon in the eclipse. After creating the virtual device click run, the .apk
file of the project will be installed on the device and application will run.
Figure 15 Android Virtual Device Manager
27
3.13.2 Running on a Device

Plugin the device using the USB cable

Make sure USB debugging is enabled on the phone. Go to Settings ->
Applications -> Development.

Click run on eclipse will install the application on the mobile and will be
launched.
3.14 Coding for Application that Displays Hello World
Below is the code of the activity displaying “Hello World!”
Class HelloWorldActivity must extends Activity and override the required methods from
the parent class. In below code onCreate() method is invoked when the activity is created.
SetContentView(R.layout.main) sets the content of main.xml file which has the code for
the interface
package com.example.HelloWorld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class HelloWorldActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Figure 16 Code Snippet of HelloWorldActivity.java
28
<?xml version="1.0" encoding="utf-8" ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="@color/mycolor" android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"android:text="@string/hello" />
</LinearLayout>
Figure 17 Code Snippet for main.xml
Main.xml file includes string hello resource for the text view. This string resource must
have the text “Hello World!”
3.15 Debugging the Application
Three main perspectives in Eclipse IDE
1. Java
2. DDMS
3. Debug
Java Perspective:
This is used for writing the source code. It shows file architecture for accessing the files
and implementing the source code.
DDMS Perspective:
This perspective shows all the files in the phone that is used for running the application.
If the application is run on the simulator all the files are accessible. This is mainly useful
if your application uses SQLite Database then developers can access all the database
files. Any files created and stored by the application are accessible. Files can be
29
downloaded on to system and the content can be viewed and edited by using SQLite
Database Browser. If the application is run on the real device some of the file contents
are not accessible because of security restrictions imposed by Android.
Debug Perspective:
This perspective is used for debugging the application. Developers can set the break
points in the code and view the values of variable at any point in the code which is useful
for recognizing and fixing the bugs in the code. Developers can use the “Variable”
window to know the values of variables when the break point is reached.
Log Cat window shows all the errors. This is very useful for understanding the errors,
warnings in the code.
30
Figure 18 LogCat Screenshot
31
Figure 19 Error Log Screenshot
32
Chapter 4
Android Application for Tracking Time and Miles Travelled
This application is useful for tracking time spent at, and miles travelled to favorite
locations.
Tracks data automatically without any user intervention, to achieve this
android service needs to be run in the background continuously.
Main objectives to be accomplished to build this application

User should be able to save, edit and delete favorite locations

When user is moving to different location, it should get the location update and
scan for a match with the favorite locations in database

If the location update is with in preferred location, it should start tracking

If location is not with in the preferred location it should discard the location
update

Application should be added to start up, so that if the mobile is switched off and
turned on the application should be started automatically

Tracked data should be displayed as list

Tracked data should be displayed in charts, so that it is easily comprehensible
4.1 Save, Edit, Delete and View Favorite Locations
Interface implementation
Interface is implemented using xml file. All the components like button, text box can be
dragged and dropped on to Graphical layout contained in eclipse. For all the components
in the Graphical layout, xml file is automatically generated. To display components on
33
screen we create an activity and in the “Activity” class we set the content of the xml file
using “setContentView(R.layout.activity_main)” where activity_main is the xml file.
<Button android:id="@+id/buttonMilesTrack"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/buttonStopService"
android:layout_alignBottom="@+id/buttonStopService"
android:layout_alignParentRight="true" android:text="@string/buttonMiles" />
Figure 20 Code Snippet of XML File for Button
In the above code snippet of XML file, <Button> is the tag used to create a button on user
interface. It has attribute width and height, where the value wrap_content denotes that the
width and height of button is determined by the text of the button. Each element of
interface has an id which can later be used to reference the element. Align attributes are
required to determine the position of button relative to other components. Text attribute
denotes the text on the button.
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Figure 21 Code Snippet of Activity Class
34
When the activity is created for the first time onCreate() method is called. This method
takes argument “Bundle savedInstanceState”, for the first time the activity is created the
savedInstanceState is null. When the orientation changes it stores the previous instance
and when the activity is recreated the content is displayed using the saved instance.
Save Locations

Users can save the favorite location by clicking save locations button.

Current location is determined using GPS, WIFI, and Cellular data.

Location from all the providers is compared to determine the accurate location

Click save button will save the location
Figure 22 Save Location Activity
35
Determine Current Location
Location manager needs to be used to get the location updates.
1. Permissions
First main thing is to declare permission in manifest file “AndroidManifest.xml”.
Depending on the provider used for obtaining the location the permissions vary.
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"
/> <uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
ACCESS_COARSE_LOCATION is used to get the location from network provider,
WIFI. For using the network location INTERNET permission must also be declared.
ACCESS_FINE_LOCATION is used to get the accurate location from GPS
ACCESS_NETWORK_STATE allows application to get information about networks.
2. Location Manager
Location manager is the main class required for getting location. Obtain the reference to
location manager using “getSystemService()” method.
LocationManager lm = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
3. Once the reference is obtained check if the provider you are using to get the location is
enabled before requesting location updates from the provider.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}
catch(Exception ex){}
36
//don't start listeners if no provider is enabled
if(!gps_enabled)
return false;
4.“requestLocationUpdates()” method will get the location updates from the specified
provider, specified frequency set by distance and time as shown in the code snippet
below.
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1*60*1000, 2000,
locationListenerGps);
In the above code “1*60*1000” denotes 1 minute and 2000 is the distance to be moved to
get the location update.
5. Set up the location listener that will receive the location updates.
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,
locationListenerGps);
LocationListener locationListenGps = new LocationListener() {
public void onLocationChanged(Location location) {
locationResult(location);
lm.removeUpdates(this);
}
}
Each time the location is obtained “onLocationChanged()” method is called in which you
can make use of the location obtained and pass to any other methods that make use of
location. For getting the location immediately parameters distance and time needs to be
set to 0. Make sure to remove updates from the location manager once the current
location is obtained. Getting the updates continuously with parameters set to zero drains
battery.
37
Compare Accuracy of Location from Different Providers
location.getAccuracy() method gives the accuracy of the location in meters. Determine
the most accurate location and set it as a current location.
Saving Location in Database
Location address is in the form of string it needs to be converted to the object of Location
class using the “Geocoder” class
Geocoder coder = new Geocoder(this);
address = coder.getFromLocationName(strAddress,5);
Use the location.getLatitude(), location.getLongitude() to get the latitude and longitude.
Calculate the distance from the new location to be saved and the existing locations. If the
distance is less than 1000 meters then it should alert the user to enter different location.
Since all the locations within 1000 meters are considered same.
Due to the signal strength the location accuracy can vary up to 1000 meters, so to get the
accurate data 1000 meters is set as constraint.
38
Distance Calculation
Below is the logic through which the distance is calculated
public float distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) *
Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
int meterConversion = 1609;
//dist in metres
// return new Float(dist * meterConversion).floatValue();
return Float.valueOf((float) (dist * meterConversion));
}
Figure 23 Calculating the Distance between Latitude and Longitude Points[11]
Storing Location in Database
To save data in SQLite database, reference of class SQLiteDatabase should be obtained
using
“helper.getWritableDatabase()”
where
helper
is
the
reference
SQLiteOpenHelper. Using the reference of SQLiteDatabase
ID=db.insert(TABLE_NAME, null, values); will insert the values in to database where
values is
ContentValues values = new ContentValues();
values.put(TABLE_ROW_ONE, rowStringOne);
values.put(TABLE_ROW_TWO, rowStringTwo);
of
39
values.put(TABLE_ROW_THREE, rowStringThree);
Content Values store the values in key, value format.
Edit Locations
On selecting locations from list of view locations it displays the activity that was used to
save location data populated with the location details. User can make changes to location
or alias and hit save button will update the entry in the database.
View Locations
Displays the alias and addresses of locations saved. Extracts the data from database and
displays in the form of list.
Figure 24 View Locations Activity
40
cursor = db.query(TABLE_NAME, null, null, null, null, null, null );
Above line will return the cursor which points to beginning of all rows in the database.
Then each row can be displayed in the list using array adapter
final ArrayAdapter<String> arrayAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ss);
v.setAdapter(arrayAdapter);
where “ss” is array list of all the rows, v is the reference of ListView that contains all the
rows to be displayed.
Delete Locations
Allows user to select and delete location from list of favorite locations. When user selects
the particular location to delete, displays the pop box asking user for confirmation. When
user clicks “yes” will delete the location. If user clicks “cancel” the location will remain
unaffected.
41
Figure 25 Delete Location Activity[12]
Logic for window pop up on selecting the location is implemented using
“setOnItemClickListener”.
42
final ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ss);
v.setAdapter(arrayAdapter);
v.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(DeleteLocations.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete ");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteRowbyNumber(positionToRemove);
ss.remove(positionToRemove);
// adm.deleteRow(positionToRemove+1);
arrayAdapter.notifyDataSetChanged();
}});
adb.show();
}
});
Figure 26 Code Snippet for Deleting Elements from List [12]
To delete the row
db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);
Will delete the row in database which have TABLE_ROW_ID = rowID and db is the
reference to SQLite database.
4.2 Implementation of Tracking Time
Location updates are obtained when the time and distance parameters are met. Whenever
the location update is obtained the location is compared against the favorite locations in
43
the data base. If the match occurs then it stores the start time. If the location update is
again obtained it is considered as the end time and the difference in time is the time spent
at the location. In this way the time spent at the favorite location is tracked.
Code should be implemented in the class that extends service. Service is the main
component of Android that runs in background continuously.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,ti
me*60*1000,dist, locationListener);
Above line gets the location updates from the NETWORK_PROVIDER when the time
and distance given by the user are satisfied.
On getting location update OnLocationChanged() method is called with location passed
to the method. On getting location calculate the distance between the location obtained
and the preferred locations. If the distance is less than 1000 meters then consider it as the
favorite location and set the flag and store the start time.
Time and distance in the above method determine the frequency of the location updates.
if(dist<1000)
{
startlongitude = longitude;
startlatitude = latitude;
alias = row.get(3).toString();
myStartDate = myOnlyDate;
startTimepr=currentTimeStamp.getTime();
flag=1;
}
44
Above is the code snippet in onLocationChanged() method. It shows that if the location
obtained is within 1000 meters of the locations saved. variable “startTimepr” will store
the current time stamp and set flag to 1
When the location changed method is called one more time if the flag is set to one then
current time stamp is stored as end time and then the entry is made in to database.
if(flag==1)
admtime.addRow(alias, myStartDate, diffInMin,"null");
To reduce the redundancy we have to check if there is entry to same alias and same date
then update the time spent at that location, there is no need to make a new entry.
if(ColumnStartAliasString.equalsIgnoreCase(startalias)&&ColumnAliasString.equalsIg
noreCase(alias)&& ColumnStartDateString.equalsIgnoreCase(myOnlyDate))
{
admmiles.updateColumnMiles(idRow,Float.toString (miles+(distCalc()/1609)));
}
4.3 Implementation of Tracking Miles Travelled
Location updates are obtained when the parameters are met. Tracking miles is started
when the user visits the favorite location this is determined by comparing the location
update with the list of favorite locations. When user visits the favorite location the
tracking is stopped. All the location points obtained from start to stop tracking are used to
calculate the miles travelled.
On getting location update calculate the distance using the logic in Figure 31. If the
location is determined as preferred location stores the entry in the temporary table. Until
the preferred location is again visited the tracking continues. Once the tracking is stopped
all the miles travelled are calculated using the distance calculation logic and then value is
45
stored in new table. All the entries in the temporary table are deleted to avoid the
overhead of redundant entries in the database.
//add rows alias, lat, long, date
admtempmiles.addRow(alias,Double.toString(latitude),Double.toString(longitude),myOn
lyDate);
Above line stores the latitude, longitude and date in the temporary miles table when the
tracking stops overall distance is calculated and then stored in other table.
admmiles.addRow(startalias,alias,myOnlyDate,Float.toString(distCalc()/1609));
distCalc() in above line adds up all the miles in the table.
public float distCalc()
{
double latitude ;
double longitude;
float dist=0;
final ArrayList<ArrayList<Object>> rowsmiles=
admtempmiles.getAllRowsAsArrays();
if(rowsmiles.size()!=0)
{
ArrayList<Object> rowFirst = rowsmiles.get(0);
latitude= Double.parseDouble(rowFirst.get(2).toString());
longitude= Double.parseDouble(rowFirst.get(3).toString());
for (int i = 1; i < rowsmiles.size(); i++) {
ArrayList<Object> row = rowsmiles.get(i);
Object ColumnLatitude = row.get(2);
Object ColumnLongitude= row.get(3);
dist=dist + distFrom(Double.parseDouble(ColumnLatitude.toString()),
Double.parseDouble(ColumnLongitude.toString()),latitude,longitude);
latitude = Double.parseDouble(ColumnLatitude.toString());
longitude = Double.parseDouble(ColumnLongitude.toString());
}
}
return dist;
}
46
Above code snippet gets all the rows from the data base and then calculate the total miles
travelled by adding the miles between each location.
4.4 Launching the Application on Startup
public class ServiceManager extends BroadcastReceiver {
Context mContext;
private final String BOOT_ACTION =
"android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
//All registered broadcasts are received by this
mContext = context;
String actionboot = intent.getAction();
if (actionboot.equalsIgnoreCase(BOOT_ACTION)) {
//check for boot complete event & start your service
startService();
}
}
private void startService() {
//here, you will start your service
Intent mServiceIntent = new Intent();
mServiceIntent.setAction("com.learner.tracktime.BackgroundService");
mContext.startService(mServiceIntent);
}
}
Figure 27 Code Snippet for Launching Application on Startup[5]
In the above class “android.intent.action.BOOT_COMPLETED” is the message
broadcasted by Android when the mobile is turned on. Once the message is received by
our BroadcastReciever we will start the service that runs in background to track the data.
47
4.5 Android Plot for Generating Charts
4.5.1 Set the Format for Line and Points to be drawn on the charts. Create the object
for the LineAndPointFormatter class and then pass the arguments of the format to the
constructor.
It takes 3 parameters as arguments for linePaint, vertexPaint, fillPaint
Line Paint: defines the color for the lines in the plot
Vertex Paint: defines the color for vertex points in the chart
Fill Paint: fills the chart with color.
LineAndPointFormatter lpFormatter = new LineAndPointFormatter(
Color.rgb(
new Double(Math.random()*255).intValue(),
new Double(Math.random()*255).intValue(),
new Double(Math.random()*255).intValue()),
Color.rgb(
new Double(Math.random()*255).intValue(),
new Double(Math.random()*255).intValue(),
new Double(Math.random()*255).intValue()),
Color.rgb(
new Double(Math.random()*255).intValue(),
new Double(Math.random()*255).intValue(),
new Double(Math.random()*255).intValue()));
48
4.5.2 Create Series to be Plotted on Chart
XYSeries is the class for creating series. Pass the array of numbers to be used for series.
“ArrayFormat.XY_VALS_INTERLEAVED” indicates that the array list has both x and y
values
Series name indicates the name to be given for series.
XYSeries series2 = new SimpleXYSeries(Arrays.asList(series1Numbers),
SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED, seriesname);
4.5.3 Add Series to the Chart
“XYPlot” class has the method addSeries which takes series and format of the series as
the argument.
mySimpleXYPlot.addSeries(series2,lpFormatter);
4.5.4 Setting the Axis Values
“XYPlot” class has setDomainValueFormat method to format the axis values. We need to
format the axis so that it displays the date or month on the X axis. Below is the code
snippet for formatting the axis
49
mySimpleXYPlot.setDomainValueFormat(new Format() {
private SimpleDateFormat dateFormat = new
SimpleDateFormat("dd");//yyyy-MM-dd
@Override
public StringBuffer format(Object object, StringBuffer
toAppendTo,
FieldPosition pos) {
// TODO Auto-generated method stub
// because our timestamps are in seconds and
SimpleDateFormat expects milliseconds
// we multiply our timestamp by 1000:
long timestamp = ((Number) object).longValue();
Date date = new Date(timestamp);
return dateFormat.format(date, toAppendTo, pos);
}
@Override
public Object parseObject(String string, ParsePosition
position) {
// TODO Auto-generated method stub
return null;
}
});
Figure 28 Code Snippet for Formatting Axis Values
4.6 Time Activity
This is the activity to view all the data tracked for the time spent. “Monthly RAW Data
Time” will display the raw data for time tracked monthly. “Monthly Charts Time” will
display charts for the time spent monthly. “Weekly Time Raw data” will display raw data
weekly. “Weekly Time Chart” will display charts weekly
50
Figure 29 Time Tracked Activity
4.7 Monthly Raw Data Time
Displays the spinner, user needs to select month and the data will be displayed
accordingly.
51
Figure 30 Monthly Raw Data Spinner
Interface Implementation
Above screen show the list of months with radio buttons, one month only can be selected.
Spinner is the component that allows to display the below interface.
52
XML Layout File for Spinner
<Spinner
android:id="@+id/spinnerMonthData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
Adding Items to Spinner
List<String> list = new ArrayList<String>();
list.add("Monthly Charts");
list.add("January");
list.add("February");
list.add("March");
list.add("April");
list.add("May");
list.add("June");
list.add("July");
list.add("August");
list.add("September");
list.add("October");
list.add("November");
list.add("December");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_
item);
spinner1.setAdapter(dataAdapter);
Above code snippet shows the process of adding the elements to spinner. First all the
elements should be kept in list and then spinner should be set to data adapter.
53
Spinner should be set “setOnItemSelectedListener”, for responding the input from the
user. When user selects the option the data is passed to onItemSelected() method which
can be used
spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Intent intent = new Intent(getBaseContext(),AndroidPlotExampleActivity.class);
//Create the bundle
Bundle bundle = new Bundle();
String monthly="month";
//Add your data to bundle
bundle.putString(monthly,String.valueOf(spinner1.getSelectedItem()));
//Add the bundle to the intent
intent.putExtras(bundle);
if(String.valueOf(spinner1.getSelectedItem())!=null&&
String.valueOf(spinner1.getSelectedItem())!="Monthly Charts")
startActivity(intent);
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
}
“spinner1.getSelectedItem()” gives the text of the option selected in the spinner.
Depending on the month chosen the action can be performed accordingly.
Below screen shows the data that is displayed for a month
54
Implementation
Depending on the text from the spinner selected, rows from the database can be retrieved
by specifying month or week and then display on the list.
Figure 31 View Locations Data Activity
55
4.8 Data Charts
All the charts displayed use the Android Plot library. Charts are all line charts. They are
used so that the data will be easily comprehensible for humans. There are two types of
charts for time tracked and miles tracked.
Monthly chart shows the data of the selected month. X AXIS represents the Date. Y
AXIS shows time spent in hours at the favorite location.
Figure 30 shows the
expandable list that will pop up for selecting the month. Figure 32 below shows the data
for 3 favorite locations. Series name are at the bottom of the chart. Series indicates the
favorite location. Gym, school, office are the 3 favorite locations of user. Each Series
names have square box which shows the line color of the series and the color of vertex
point.
From the chart user can understand time spent at the favorite location on each date of
selected month. Below is the data from chart, summarized in tabular format.
Favorite Place
Gym
Gym
Gym
School
School
School
Office
Office
Office
Date
1st
2nd
3rd
4th
5th
6th
24th
25th
28th
Time (in hours)
1
1.33
0.66
2
1.5
2.5
0.66
1.16
0.5
56
Figure 32 Data Charts Monthly
57
Figure 33 Data Charts Weekly
Weekly chart shows the dates of selected week. Above chart in Figure 33 shows the data
of the 3rd week. Figure 34 shows the pop up window for selecting the month and week.
Data is available for 21st to 25th of October. Hence the data is shown for the available data
for 3rd week. X AXIS represents the Date. Y AXIS shows time spent in minutes. Below
is the data from chart, summarized in tabular format.
58
Favorite Place
Office
Office
Office
Thai Paradi
Thai Paradi
Thai Paradi
Home
Home
Home
Home
School
Date
21st
22nd
23rd
21st
22nd
23rd
21st
22nd
23rd
25th
23rd
Time (in minutes)
5
1
6
52
20
5
72
72
216
72
48
Weekly Data view:
Below is the screen that displays expandable list. Selecting month displays the weeks of
the month and then the week selected will display the data accordingly.
Figure 34 Expandable List for Weekly Activity
59
4.9 Summary and Future Work
This location aware works perfect in android phone having Jelly Bean version operating
system. “requestLocationUpdates()” method used to get the location updates strictly
follows the distance and time parameters set in the Jelly Bean version, in the previous
versions parameters are just a hint which causes updates more frequently and battery may
drain.
GPS location is accurate when we are outside buildings, but it does drain battery sooner.
As this application gets location updates frequently GPS is not the better choice.
On using Network provider, accuracy of location depends on the network signals. If there
are no proper signals then the location update will have less accuracy which leads to
inaccuracy in data.
Future work can be to implement all the data storage in the cloud, which will be efficient
to store lots of data and data can be viewed from anywhere.
60
Chapter 5
Conclusion
Application is useful for tacking time spent at favorite locations. It is useful for managing
the time efficiently and people can also know the miles travelled. Developing Android
applications is really useful. There are lots of mobile applications in the market and day
today people are relying lot on applications to make their life simpler.
Android applications are implemented in Java language. Learning Android packages and
libraries is really cool stuff. Android has made it easier for the developer to develop
applications. There are lots of tutorials and libraries which can be used readily. Android
SDK tools are for free. Any person having just a computer can develop an application.
Basic applications can be tested on computers; there is no need for android mobile to test
applications.
This application can be used as beginning, there can be done lot of development which
will be useful for the people to track their own life to manage and organize efficiently. To
understand the data tracked, human comprehensible charts are plotted which are
attractive.
61
References
[1] Android Developer guide http://developer.android.com/
[2] Using Android SQLite Database
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/
[3] Getting location http://stackoverflow.com/questions/9460543/get-location-on-clickof-a-button-with-default-provider
[4] Generating Charts using Android Plot http://androidplot.com/wiki/Home
[5] “Android Cookbook” by Ian F. Darwin (April 2012), O’Reilly Media, Inc.
[6] Research on different providers for getting location updates
http://stackoverflow.com/questions/6775257/android-location-providers-gps-or-networkprovider
[7] Using of Android plot library to plot charts against time
http://androidplot.com/wiki/Plotting_Against_Time
[8] Deep Dive in to location Android
http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
[9] Tutorial on getting started with Expandable List View
http://www.dreamincode.net/forums/topic/270612-how-to-get-started-withexpandablelistview/
[10] “Learning Android” by Marko Gargenta (March 2011), O’Reilly Media, Inc.
62
[11] Calculating distance between two points
http://stackoverflow.com/questions/837872/calculate-distance-in-meters-when-youknow-longitude-and-latitude-in-java/837957#837957
[12] Deleting elements from list view
http://stackoverflow.com/questions/2558591/remove-listview-items-in-android
Download