Implementation of Machine Learning on Android

Description
The aim of application is to predict the current environment variable on the basis of training given by a large environment data set consisting of attributes like temperature, pressure, humidity etc. This project is a practical implementation of Machine Learning on Android Devices.

1


Table of Contents


I. INTRODUCTION ........................................................................................................ 2

II. OVERVIEW .................................................................................................................. 3

1. Android Framework .................................................................................................. 3

2. Android History ......................................................................................................... 4

3. Android Architecture ................................................................................................ 4

III. Application Structure ................................................................................................ 6

1. Application Component ........................................................................................... 9

2. Intent definition ........................................................................................................ .10

3. The AndroidManifest file. ..................................................................................... .11

4. Process and thread in Android ............................................................................. 11

5. Activity lifecycle ..................................................................................................... 12

IV. Implementation of Machine Learning on Android ........................................... 16

1. Problem Statement .................................................................................................. 16

2. Naïve Bayes Classifier Algorithm . .................................................................... 16

3. Application Layout ................................................................................................. 20

4. Application Activities............................................................................................. .24

5. SNAPSHOTS .......................................................................................................... 34

V. CONCLUSION .......................................................................................................... 36

VI. REFERENCES ........................................................................................................ 37
2

I. INTRODUCTION




This project is about the developing an android application. Nowadays, the gadgets
are rolling the world. Many people cannot imagine even one day without their favorite
mobile device. We use them for everything: find information, stay connected with our friends
and families, find the way around, decide what to do, and many other things. But very often
we come to the point when we would like to have an application for particular situation or for
certain need, but there is no such one.

The aim of application is to predict the current environment variable on the basis of training
given by a large environment data set consisting of attributes like temperature, pressure,
humidity etc. This project is a practical implementation of Machine Learning on Android
Devices.
3

II. OVERVIEW


1. Android Framework



Android is a software stack for mobile device that includes an operating system,
middleware and applications. Android is powered by Linux kernel, initially developed by
Google and later the Open Handset Alliance. It allows developers to write managed code in
java language, controlling the device via Google developed java library.

Not like other famous rivals such as Microsoft window mobile or Symbian OS,
android use developed java library because java is not just a programming language; it’s a
complete dynamic platform offers powerful support for embedded devices that must maintain
some form of dynamic behavior.

Moreover, java runtime environment can be integrated into almost any embedded
device while java virtual machine includes interfaces that allow it to be readily integrated
with RTOS and other native library. The RTOS supports multi-thread (scheduling), memory
management, networking, and peripheral management for java VM.
4

2. Android History



The actual history of Android starts when Google has had purchased and Android Inc.
in 2005. But the development did not start immediately. The actual progress on android
platform starts when 2007 Open Handsets Alliance has announced the Android as Open
Source platform and year later the Android SDK 1.0. In the same 2008 the G1 phone was
produced by HTC and was retailed within the T-Mobile carrier. In the next two years came
out 4 versions of Android. In 2010 there were at least 60 devices 7 running android and it
becomes second after Blackberry the best spread mobile platform. (Gargenta 2011, 3-6).



3. Android Architecture



Android’s general architecture contains the following parts:

1. Application layer: Android provides a lot of applications which come with its release
including an email client, SMS program, calendar, maps, browser, contacts, and
others. All applications are written using the Java programming language.

2. An application framework layer enabling reuse and replacement of components. Not
like Window mobile which restricts developer from system API, developers have full
access to the same framework APIs used by the core’s applications.

Android provide a set of services and system, including:

Views: is a flexible definition. It can be a list, a grid, text box, button or even an
embedded web browser. View in Android is very different from the definition of
?view? in Symbian OS or Window mobile which often means the container in which
graphic components are organized and displayed to user.

Content provider: store and retrieve data and make it accessible to all applications.
They're the only way to share data across applications; there's no common storage
area that all Android packages can access.

Resource manager: Resources are external files (that is, non-code files such as image,
icon, and string for internationalization) that are used by developer’s code and
compiled into their application at build time. Android supports a number of different
kinds of resource files, including XML, PNG, and JPEG files.

Notification manager that enables all application to display custom alerts in the status
bar notify user of what happen in the back ground.

Activity manager: manages the lifecycle of application and provide common
navigation back stack. An activity focuses on what user can do by interact with user.
5


Activity will for example create a window and place UI component to be displayed to
user.

3. Libraries: They are all written in C/C++ internally, but you’ll be calling them through
Java interfaces. These capabilities are exposed to developers through the Android
application framework.
Some of core libraries are:

System C library - a BSD-derived implementation of the standard C system library
(libc), tuned for embedded Linux-based devices.

Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback
and recording of many popular audio and video formats, as well as static image files,
including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG

Surface Manager - manages access to the display subsystem and seamlessly
composites 2D and 3D graphic layers from multiple applications

LibWebCore - a modern web browser engine which powers both the Android browser
and an embeddable web view

SGL - the underlying 2D graphics engine

3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use
either hardware 3D acceleration (where available) or the included, highly optimized
3D software rasterizer



4. Android Runtime: A set of core libraries provides most the functionality available in
the core library of java programming language. Android runtime includes the Dalvik
Virtual Machine. Dalvik runs dex files, which are coverted at compile time from
standard class and jar files. Dex files are more compact and efficient than class files,
an important consideration for the limited memory and battery powered devices that
Android targets.

5. Dalvik Virtual Machine which is optimized for mobile devices. Dalvik is a major
piece of Google’s Android, runs Java platform applications which have been
converted into a compact Dalvik Excutable format suitable for systems that are
constrained in terms of memory and processor speed. Unlike most virtual machines an
true java virtual machine which are stack machines, Dalvik VM is a register based
architecture.

6. Linux Kernel: Starting at the bottom is the Linux kernel. Android uses it for its device
drivers, memory management, process management and networking. How ever we
will never be programming to this layer directly. Android relies on Linux kernel
version 2.6 for core system services. The kernel also acts as an abstraction layer
between the hardware and the rest of the software stack.
6

III. Application Structure



An android application is developed using Java language. After being compiled it will
be packaged into Android Package (.apk) format which then can be deployed on to mobile
device. Each Android application has its own process and Java virtual machine that mean
application code runs in isolation from the code of all other applications. Each application is
assigned a unique Linux user ID. Permissions are set so that application’s files are visible
only to that user, to the application itself and there are other ways to export them to other
application (through Content Provider).



1. Application Component

An Android application can make use of elements come from other application if it is
permitted to do so. Because of this, system must be able to start an application process when
any part of it is needed, and instantiate the java object for that part. There for an application
here does not have a single entry point rather, they have essential components that system can
instantiate and run as needed.

a. Activity: An activity work like ?view? definition in window mobile which presents a
visual interface to user. Each activity is independent, developer create his/her own activity by
sub classing Activity base class. An application consists at least one activity which is
presented to the user when application is launched. We can move from one activity to another
by calling method startActivity() or startActivityForResult() from current activity. Activity
work like a container and can make use of window which fill the screen or might be smaller
than the screen and float on top of other windows like pop-up dialog. Developer often start
with the call to method

@Override

public void onCreate(Bundle savedInstanceState){}

Where the visual content of views – objects are provided. View objects are derived from
View class and each controls a particular retangular space within window. Developer can
create View object from code or in much easier way using xml file which describes the
hierachical organization of window. Parente views contain and organize the layout of their
children. Views at leaf draw in their retangle and response to user actions directed at that
space. A view hierachy is placed with in an activity’s window by the
Activity.setContentView() method. The code below show normal work done by Activity
when startup.
7


























b. Services: A service does not have a visual user interface and runs in the background for
indefinite period of time. A service play in role such are fetching data over the network or
calculate something and provide the result the result to activities that need it. Each service
extends the Service base class. Service run in the main thread of the application process, to
avoid blocking other components or the user interface they often spawn another thread for
time-consuming task. Android provide Handler class to handle message exchange between
thread and not interfear other GUI thread.



c. Broadcast receiver: is a component that listening and react to broadcast announcements
such as timezone has changed, battery is low, a coming call.etc..Application can also
broadcasts an event to let other applications.

This component do not display to user but they can start another event or use
NotificationManager to alert the user. Developers can implement broadcast receiver by
subclassing BroadcastReceiver base class.



d. Content provider: the onlyway to communicate between application by make a specific
set of application’s data available to others. These data is store in persistence sense by
provider side (the one subclass ContentProvider base class). ContentProvider provide an
interface with methods to store and retrieve data which then can be used by consumer.

Consumers are subclasses of ContentResolver base class which takk to any content provider.
ContentResolver cooperates with the provider to manage any interprocess communication
that’s involved.

Whenever there's a request that should be handled by a particular component, Android makes
sure that the application process of the component is running, starting it if necessary, and that
an appropriate instance of the component is available, creating the instance if necessary. A
content provider is active only while it's responding to a request from a ContentResolver.
8


And a broadcast receiver is active only while it's responding to a broadcast message. So
there's no need to explicitly shut down these components. Activities, on the other hand,
provide the user interface. They're in a long-running conversation with the user and may
remain active, even when idle, as long as the conversation continues. Similarly, services may
also remain running for a long time. So Android has methods to shut down activities and
services in an orderly way:
+ An activity can be shut down by calling its finish() method. One
activity can shut down another activity (one it started with startActivityForResult()) by
calling finishActivity().

+ A service can be stopped by calling its stopSelf() method, or by calling
Context.stopService().












































Components might also be shut down by the system when they are no longer being used or
when Android must reclaim memory for more active components.
9

2. Intent definition




Activities, services and broadcast receiver are activated by asynchronous messages
which Android call ?Intent?s. Intent is an object that holds the content of the message. There
are some pre-defined Intent for system message like Intent.ACTION_INSERT,
Intent.ACTION_SEND… For activities and services, it names the action being requested and
specifies the URI of the data to act on, among other things. For broadcast receivers, the Intent
object names the action

? To activate an activity we by pass an Intent object to method startActivity() or
startActivityForResult(). Intent can contain a lot of type of data: Boolean, String,
Serializable Object..etc..in Extra part Activated activity can get back Intent message
by using getIntent() method and extract sent data by using coresponding getExtra()
method . Snip code below show some example which is used in project.







































One activity often starts the next one. If it expects a result back from the
activity it's starting, it calls startActivityForResult() instead of startActivity(). The
result is returned in an Intent object that's passed to the calling activity's
onActivityResult() method.


10


? A service is started (or new instructions are given to an ongoing service) by passing
an Intent object to Context.startService(). Android calls the service's onStart()
method and passes it the Intent object. Similarly, an intent can be passed to
Context.bindService() to establish an ongoing connection between the calling
component and a target service. The service receives the Intent object in an onBind()
call. (If the service is not already running, bindService() can optionally start it.)

? An application can initiate a broadcast by passing an Intent object to methods like
sendBroadCast(), sendOderedBroadCast(), and sendSticktBroadCast of Context class
in any of their variations. Android delivers the intent to all interested broadcast
receivers by calling their onReceive() methods.



3. The AndroidManifest file:

AndroidManifest file is an XML file declare application’s components, naming any
libraries the application needs to be linked and identifying any permission the application
expected to be granted. Its name is fixed and is the same for every application. This can be
consider the configuration file of application. The snip code below show part of XML file
which is used by My Delicious project and we can see the declaration of activities with
corresponding class, Intent filter which dedicate the component is going to receive the intent
message..etc.
11

4. Process and thread in Android


Android support multi-thread tasking allow developer to spawn additional threads for
any process.

a. Process: The process where a component runs is controlled by the manifest file. The
component elements — <activity>, <service>, <receiver>, and <provider> — each have a
process attribute that can specify a process where that component should run. These attributes
can be set so that each component runs in its own process, or so that some components share
a process while others do not. They can also be set so that components of different
applications run in the same process — provided that the applications share the same Linux
user ID and are signed by the same authorities. The <application> element also has a process
attribute, for setting a default value that applies to all components. All components are
instantiated in the main thread of the specified process, and system calls to the component are
dispatched from that thread. Separate threads are not created for each instance. Consequently,
methods that respond to those calls — methods that report user actions and the lifecycle
notifications always run in the main thread of the process. This means that no component
should perform long or blocking operations (such as networking operations or computation
loops) when called by the system, since this will block any other components also in the
process. You can spawn separate threads for long operations.

Android may decide to shut down a process at some point, when memory is low and required
by other processes that are more immediately serving the user. Application components
running in the process are consequently destroyed. A process is restarted for those
components when there's again work for them to do. When deciding which processes to
terminate, Android weighs their relative importance to the user. For example, it more readily
shuts down a process with activities that are no longer visible on screen than a process with
visible activities. The decision whether to terminate a process, therefore, depends on the state
of the components running in that process.

b. Thread: There will be somtime developers need to spawn a thread to do some background
work. Thread are created in code using standard Java Thread object. Android provides a
number of convenience classes for managing threads like Looper for running a message loop
within a thread, Handler for processing messages, and HandlerThread for setting up a thread
with a message loop. For example in My Delicious project, many time we need to perform
network operation that takes long time to receive data. Solution is to perform that kind of
work in a different thread while displaying a progress bar to user. Progress bar will be
dimissed when sub-thread complete:
12



















































5. Activity lifecycle



Application components have a lifecycle — a beginning when Android instantiates
them to respond to intents through to an end when the instances are destroyed. In between,
they may sometimes be active or inactive,or, in the case of activities, visible to the user or
invisible. Because Activity will be used most oftenly here we only discusses about the
lifecycle of activities including the states that they can be in during their lifetimes, the
methods that notify you of transitions between states, and the effect of those states on the
possibility that the process hosting them might be terminated and the instances destroyed.



13

An activity has essentially three states:
? It is active or running when it is in the foreground of the screen (at the top of the
activity stack for the current task). This is the activity that is the focus for the user's
actions.
? It is paused if it has lost focus but is still visible to the user. A paused activity is
completely alive (it maintains all state and member information and remains attached
to the window manager), but can be killed by the system in extreme low memory
situations.
? It is stopped if it is completely obscured by another activity. It still retains all state and
member information. However, it is no longer visible to the user so its window is
hidden and it will often be killed by the system when memory is needed elsewhere.

If an activity is paused or stopped, the system can drop it from memory either by asking it to
finish, or simply killing its process. When it is displayed again to the user, it must be
completely restarted and restored to its previous state. As an activity transitions from state to
state, it is notified of the change by calls to the following protected methods:


















All activities must implement onCreate() to do the initial setup when the object is first
instantiated. Many will also implement onPause() to commit data changes and otherwise
prepare to stop interacting with the user. Taken together, these seven methods define the
entire lifecycle of an activity. There are three nested loops that you can monitor by
implementing them:

• The entire lifetime : An activity does all its initial setup of "global" state onCreate(),
and releases all remaining resources in onDestroy().

• The visible lifetime : During this time, the user can see the activity on-screen,
though it may not be in the foreground and interacting with the user. Between these
two methods, you can maintain resources that are needed to show the activity to the
user. The onStart() and onStop() methods can be called multiple times, as the activity
alternates between being visible and hidden to the user.

• The foreground lifetime During this time, the activity is in front of all other
activities on screen and is interacting with the user. An activity can frequently
transition between the resumed and paused states.
14

The following diagram illustrates these loops and the paths an activity may take between
states. The colored ovals are major states the activity can be in. The square rectangles
represent the callback methods you can implement to perform operations when the activity
transitions between states.

When the system, rather than the user, shuts down an activity to conserve memory,
the user may expect to return to the activity and find it in its previous state. To capture that
state before the activity is killed, you can implement an onSaveInstanceState() method for the
activity. Android calls this method before making the activity vulnerable to being destroyed
— that is, before onPause() is called. It passes the method a Bundle object where you can
record the dynamic state of the activity as name-value pairs. When the activity is again
started, the Bundle is passed both to onCreate() and to a method that's called after onStart(),
onRestoreInstanceState(), so that either or both of them can recreate the captured state.
15

16

IV. Implementation of Machine Learning on Android



1. Problem Statement:


This application predicts the current environment variable on the basis of training
given with a large dataset using machine learning.
The large dataset comes from the sensors of the android device over a time period of
over six months.
User will get a notification in the device if the environment conditions predicted by
application are unsafe.



2. Naive Bayes Classifier Algorithm:

A naive Bayes classifier assumes that the value of a particular feature is unrelated to
the presence or absence of any other feature, given the class variable. For example, a fruit
may be considered to be an apple if it is red, round, and about 3" in diameter. A naive Bayes
classifier considers each of these features to contribute independently to the probability that
this fruit is an apple, regardless of the presence or absence of the other features.
For some types of probability models, naive Bayes classifiers can be trained very efficiently
in a supervised learning setting. In many practical applications, parameter estimation for
naive Bayes models uses the method of maximum likelihood; in other words, one can work
with the naive Bayes model without accepting Bayesian probability or using any Bayesian
methods.
An advantage of naive Bayes is that it only requires a small amount of training data to
estimate the parameters (means and variances of the variables) necessary for classification.
Because independent variables are assumed, only the variances of the variables for each class
need to be determined and not the entire covariance matrix.
Abstractly, the probability model for a classifier is a conditional model

Over a dependent class variable with a small number of outcomes or classes, conditional
on several feature variables F1 through Fn. The problem is that if the number of features is
large or if a feature can take on a large number of values, then basing such a model on
probability tables is infeasible. We therefore reformulate the model to make it more tractable.
Using Bayes' theorem, this can be written


17

In plain English, using Bayesian Probability terminology, the above equation can be written
as

In practice, there is interest only in the numerator of that fraction, because the denominator
does not depend on and the values of the features are given, so that the denominator is
effectively constant. The numerator is equivalent to the joint probability model

Which can be rewritten as follows, using the chain rule for repeated applications of the
definition of conditional probability:



Now the "naive" conditional independence assumptions come into play: assume that each
feature is conditionally independent of every other feature for , given the
category . This means that
,
,
,
And so on, for . Thus, the joint model can be expressed as

This means that under the above independence assumptions, the conditional distribution over
the class variable is:

where the evidence is a scaling factor dependent only on F1,…., Fn
that is, a constant if the values of the feature variables are known.

18


Constructing a classifier from the probability model:
The discussion so far has derived the independent feature model, that is, the naive
Bayes probability model. The naive Bayes classifier combines this model with a decision
rule. One common rule is to pick the hypothesis that is most probable; this is known as
the maximum a posteriori or MAP decision rule. The corresponding classifier, a Bayes
classifier, is the function defined as follows:




C++ implementation of Naïve Bayes Algorithm on sample Dataset:


#include <bits/stdc++.h>
using namespace std;
int main()
{
ifstream fin;
char c;
fin.open("/home/anant/Desktop/project/adult.data");
vector<string> v[15];
string s="",s1;
int count1=0;
while (getline(fin,s1))
{
int count=0;
for (int i=0; i<s1.size(); i++)
{
if (s1==',')
{
v[count++].push_back(s);
s="";
}
else if (s1!=' ')
s+=s1;
}
v[count].push_back(s);
}
fin.close();
map<string,int> map_x[15],map_y[15];

19

for (int i=0; i<14; i++)
map<string,double> map_ansx[15],map_ansy[15];
for (int i=0; i<14; i++)
{
for(map<string,int>::iterator it=map_x.begin();it!=map_x.end(); ++it)
map_ansx[(it)->first]=log(double((it)->second)/(double)v.size())/log(2.0);

for(map<string,int>::iterator it=map_y.begin(); it!=map_y.end(); ++it)
map_ansy[(it)->first]=log(double((it)->second)/(double)v.size())/log(2.0);
}
fin.open("/home/anant/Desktop/project/adult.test");
int attr_count=0,tuple_count=0;
int correct_count=0;
while (getline(fin,s1))
{
s="";
tuple_count++;
attr_count=0;
double x=0,y=0;
for (int i=0; i<s1.size(); i++)
{
if (s1==',')
{
x+=map_ansx[attr_count];
y+=map_ansy[attr_count];
attr_count++;
s="";
}
else if (s1!=' ')
s+=s1;
}
if (x>y && s=="<=50K")
correct_count++;
else if (x<y && s==">50K")
correct_count++;
}
cout<<correct_count<<" "<<tuple_count<<endl;
fin.close();
cout<<100*(double(correct_count)/double(tuple_count))<<endl;
return 0;
}








20

3. Application Layout



Layout is defined in xml files.

For this application, Layout defined for main activity is in main.xml & list.xml
The respective xml codes are shown below.

Main.xml


<?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:orientation="vertical" >

<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50sp"
android:text=" Time " />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="220dp"
android:text="Temp" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="300dp"
android:text="Accelerometer.X" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
21

android:layout_marginLeft="390dp"
android:text="Accelerometer.Y" />

<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="490dp"
android:text="Accelerometer.Z" />

<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="580dp"
android:text="Gyroscope.X" />

<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="680dp"
android:text="Gyroscope.Y" />

<TextView
android:id="@+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="790dp"
android:text="Gyroscope.Z" />

<TextView
android:id="@+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="900dp"
android:text="Lin_Acc.X" />

<TextView
android:id="@+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1010dp"
android:text="Lin_Acc.Y" />

<TextView
android:id="@+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1120dp"
android:text="Lin_Acc.Z" />

<TextView
android:id="@+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1230dp"
android:text="Mag_Field.X" />

<TextView
22

android:id="@+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1330dp"
android:text="Mag_Field.Y" />

<TextView
android:id="@+id/textView15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1430dp"
android:text="Mag_Field.Z" />

<TextView
android:id="@+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1560dp"
android:text="Rel_Humidity" />

<TextView
android:id="@+id/textView17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1660dp"
android:text="Pressure" />
</RelativeLayout>
</HorizontalScrollView>

</LinearLayout>


List.xml

<?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:orientation="vertical" >

<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID" />

<TextView
23

android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50sp"
android:text=" Time " />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="220dp"
android:text="Temp" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="300dp"
android:text="Accelerometer.X" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="390dp"
android:text="Accelerometer.Y" />

<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="490dp"
android:text="Accelerometer.Z" />

<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="580dp"
android:text="Gyroscope.X" />

<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="680dp"
android:text="Gyroscope.Y" />

<TextView
android:id="@+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="790dp"
android:text="Gyroscope.Z" />

<TextView
android:id="@+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="900dp"
24

android:text="Lin_Acc.X" />

<TextView
android:id="@+id/textView11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1010dp"
android:text="Lin_Acc.Y" />

<TextView
android:id="@+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1120dp"
android:text="Lin_Acc.Z" />

<TextView
android:id="@+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1560dp"
android:text="Rel_Humidity" />

<TextView
android:id="@+id/textView17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1660dp"
android:text="Pressure" />
</RelativeLayout>
</HorizontalScrollView>

</LinearLayout>

4. Application Activities



Activities are defined in java files.

For this application there are total three Activities, Main_Activity being the head one which displays
the content of the database.

Myservice activity is used here to create the dataset of environment variable from sensors and to show
the notification.

Sqlite activity is used to store the dataset.
The respective codes for all activities are shown below:








25

MainActivity.java


package com.example.sensor_project;

import java.util.ArrayList;
import java.util.Calendar;

import android.support.v7.app.ActionBarActivity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

ListView listView;
ArrayList<pojo> arrayList;
sql_db db;
myadapter ma;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView=(ListView) findViewById(R.id.listView1);

db = new sql_db(getApplicationContext(), "sensor_db", null,
1);
arrayList = db.query();

if(arrayList==null)
{
// db.add_value(" Time ",
Float.valueOf("Temp")
,Float.valueOf("Accelerometer.x"),Float.valueOf("Accelerometer.y"),Float.v
alueOf("Accelerometer.z"),Float.valueOf("Gyroscope.x"),Float.valueOf("Gyro
scope.y"),Float.valueOf("Gyroscope.z"),Float.valueOf("Lin_acc.x"),Float.va
lueOf("Lin_acc.y"),Float.valueOf("Lin_acc.z"),Float.valueOf("Mag_field.x")
,Float.valueOf("Mag_field.y"),Float.valueOf("Mag_field.z"),Float.valueOf("
Relative Humidity"),Float.valueOf("Pressure"));
db.add_value("time",
0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f
);
}
26

arrayList = db.query();
ma = new myadapter();
listView.setAdapter(ma);
ma.refresh();

if(arrayList.size()==1)
{
Calendar calendar = Calendar.getInstance();
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(getApplicationContext(),
myservice.class);
PendingIntent pendingIntent =
PendingIntent.getService(getApplicationContext(), 0, i, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 30000 , pendingIntent);
}

}

class myadapter extends BaseAdapter
{

@Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}

@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(int position, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
View v = getLayoutInflater().inflate(R.layout.list,
null);
TextView tv1 = (TextView)
v.findViewById(R.id.textView1);
TextView tv2 = (TextView)
v.findViewById(R.id.textView2);
TextView tv3 = (TextView)
v.findViewById(R.id.textView3);
TextView tv4 = (TextView)
v.findViewById(R.id.textView4);
TextView tv5 = (TextView)
27

v.findViewById(R.id.textView5);
TextView tv6 = (TextView)
v.findViewById(R.id.textView6);
TextView tv7 = (TextView)
v.findViewById(R.id.textView7);
TextView tv8 = (TextView)
v.findViewById(R.id.textView8);
TextView tv9 = (TextView)
v.findViewById(R.id.textView9);
TextView tv10 = (TextView)
v.findViewById(R.id.textView10);
TextView tv11 = (TextView)
v.findViewById(R.id.textView11);
TextView tv12 = (TextView)
v.findViewById(R.id.textView12);
TextView tv13 = (TextView)
v.findViewById(R.id.textView13);
TextView tv14 = (TextView)
v.findViewById(R.id.textView14);
TextView tv15 = (TextView)
v.findViewById(R.id.textView15);
TextView tv16 = (TextView)
v.findViewById(R.id.textView16);
TextView tv17 = (TextView)
v.findViewById(R.id.textView17);

int id=arrayList.get(position).getId();
if(id==1)
{
tv1.setText("Id");
tv2.setText(" Time ");
tv3.setText("Temp(C)");
tv4.setText("Accl.X");
tv5.setText("Accl.Y");
tv6.setText("Accl.Z");
tv7.setText("Gyroscope.X");
tv8.setText("Gyroscope.Y");
tv9.setText("Gyroscope.Z");
tv10.setText("Lin_Acc.X");
tv11.setText("Lin_Acc.Y");
tv12.setText("Lin_Acc.Z");
tv13.setText("Mag_Field.X");
tv14.setText("Mag_Field.Y");
tv15.setText("Mag_Field.Z");
tv16.setText("Rel_Humidity");
tv17.setText("Pressure ");
}

else
{
tv1.setText(id-1+"");
tv2.setText(arrayList.get(position).getTime());
tv3.setText(arrayList.get(position).getS1_x()+"");
tv4.setText(arrayList.get(position).getS2_x()+"");
tv5.setText(arrayList.get(position).getS2_y()+"");
28

tv6.setText(arrayList.get(position).getS2_z()+"");
tv7.setText(arrayList.get(position).getS3_x()+"");
tv8.setText(arrayList.get(position).getS3_y()+"");
tv9.setText(arrayList.get(position).getS3_z()+"");

tv10.setText(arrayList.get(position).getS4_x()+"");

tv11.setText(arrayList.get(position).getS4_y()+"");

tv12.setText(arrayList.get(position).getS4_z()+"");

tv13.setText(arrayList.get(position).getS5_x()+"");

tv14.setText(arrayList.get(position).getS5_y()+"");

tv15.setText(arrayList.get(position).getS5_z()+"");

tv16.setText(arrayList.get(position).getS6_x()+"");

tv17.setText(arrayList.get(position).getS7_x()+"");
}

return v;
}


}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if
it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
arrayList = db.query();
ma.refresh();
return true;
}
}










29

MyService.java

package com.example.sensor_project;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressLint("NewApi")
public class myservice extends Service implements SensorEventListener{

SensorManager sensorManager;
Sensor s1,s2,s3,s4,s5,s6,s7,s8,s9;
sql_db db;
SimpleDateFormat sdf;
Calendar calendar;
int count;
float
s1_x,s2_x,s2_y,s2_z,s3_x,s3_y,s3_z,s4_x,s4_y,s4_z,s5_x,s5_y,s5_z,s6_x,s7_x
;

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
db = new sql_db(getApplicationContext(), "sensor_db", null,
1);
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub

30

sensorManager = (SensorManager)
getSystemService(SENSOR_SERVICE);
s1 =
sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
s2 =
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
s3 = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
s4 =
sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
s5 =
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
s6 =
sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
s7 = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);

List<Sensor> sensors=
sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.v("Sensormanager", "Name : "+sensor.getName());
Log.v("Sensormanager", "Name : "+sensor.getVendor());
Log.v("Sensormanager", "Name :
"+sensor.getMaximumRange());
}

count=0;
sensorManager.registerListener(this, s1,
SensorManager.SENSOR_DELAY_NORMAL);

return Service.START_STICKY;
}

@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float[] v = event.values;

switch (count) {
case 0:
count++;
s1_x = v[0];
sensorManager.unregisterListener(this);
sensorManager.registerListener(this, s2,
SensorManager.SENSOR_DELAY_NORMAL);
break;
case 1:
count++;
s2_x = v[0];s2_y = v[1];s2_z = v[2];
sensorManager.unregisterListener(this);
sensorManager.registerListener(this, s3,
SensorManager.SENSOR_DELAY_NORMAL);
break;
case 2:
count++;
s3_x = v[0];s3_y = v[1];s3_z = v[2];
31

sensorManager.unregisterListener(this);
sensorManager.registerListener(this, s4,
SensorManager.SENSOR_DELAY_NORMAL);
break;
case 3:
count++;
s4_x = v[0];s4_y = v[1];s4_z = v[2];
sensorManager.unregisterListener(this);
sensorManager.registerListener(this, s5,
SensorManager.SENSOR_DELAY_NORMAL);
break;
case 4:
count++;
s5_x = v[0];s5_y = v[1];s5_z = v[2];
sensorManager.unregisterListener(this);
sensorManager.registerListener(this, s6,
SensorManager.SENSOR_DELAY_NORMAL);
break;
case 5:
count++;
s6_x = v[0];
sensorManager.unregisterListener(this);
sensorManager.registerListener(this, s7,
SensorManager.SENSOR_DELAY_NORMAL);
break;
case 6:
count++;
s7_x = v[0];
sensorManager.unregisterListener(this);

calendar = Calendar.getInstance();
sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String strDate = sdf.format(calendar.getTime());

db.add_value(strDate,s1_x,s2_x,s2_y,s2_z,s3_x,s3_y,s3_z,s4_x,s4_y,s4
_z,s5_x,s5_y,s5_z,s6_x,s7_x);
break;
default:
break;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub

}
}




32

Sqlite.java
package com.example.sensor_project;

import java.util.ArrayList;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class sql_db extends SQLiteOpenHelper {

ArrayList<pojo> list;
pojo pojo;

public sql_db(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// TODO Auto-generated method stub

}

public void add_value(String time, float s1_x,float s2_x,float
s2_y,float s2_z)
{
SQLiteDatabase database = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("time", time);
values.put("s1_x", s1_x);
values.put("s2_x", s2_x);
values.put("s2_y", s2_y);
database.insert("sensor_database", null , values);
database.close();
}

public ArrayList<pojo> query()
{
SQLiteDatabase database = getReadableDatabase();
Cursor cursor = database.query("sensor_database", null, null,
null, null, null, null);

33

if(cursor.moveToFirst())
{
list = new ArrayList<pojo>();
do
{
pojo = new pojo();

float s1_x =
cursor.getFloat(cursor.getColumnIndex("s1_x"));
float s2_x =
cursor.getFloat(cursor.getColumnIndex("s2_x"));
float s2_y =
cursor.getFloat(cursor.getColumnIndex("s2_y"));
float s2_z =
cursor.getFloat(cursor.getColumnIndex("s2_z"));
String time=
cursor.getString(cursor.getColumnIndex("time"));
int id =
cursor.getInt(cursor.getColumnIndex("id"));
pojo.setS1_x(s1_x);
pojo.setS2_x(s2_x);
pojo.setS2_y(s2_y);
pojo.setS2_z(s2_z);
pojo.setId(id);
pojo.setTime(time);
list.add(pojo);
}while(cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}















34

5. SNAPSHOTS

The DataSet:









35




Risk Prediction:








36

V. CONCLUSION




?Risk Predictor? is developed to be an innovative application and its main purpose is
to get familiar with Android SDK and Machine Learning. Because of this reason, here we do
not consider much about optimality attitude of application. The next version of this will
concentrate on remaining problem like portability between different kinds of device,
adaptability with the change of API, friendlier interface, and also optimality in network
usage.
37

VI. REFERENCES




? https://api.del.icio.us
? Android A Programmer Guid –McGraw Hill
? Posts on http://androidforums.com/
? http://www.androidmobileforum.com/
? http://androidcommunity.com/forums/
? Android for Java Developers - Dr. Markus Schmall, Jochen Hiller.
? http://en.wikipedia.org/wiki/Naive_Bayes_classifier



doc_617608666.pdf
 

Attachments

Back
Top