Development of tools for the use of Android cell-phones to recognize user activities
Abstract
The goal of this study is developing the fundamental techniques to define activity of the users like walking, running, standing or cycling while the user is using two different type of Network connectivity, GPRS or Wi-Fi by calculating the distance of the user in a period of time by the longitude and latitude of the user´s location which has reached in the location recognizing. Therefore, the main goal of the study to retrieve user’s activity is achieved by requesting location of user for each period of time, from current and previous location of user.
Full text
Final Master Thesis Development of tools for the use of Android cell-phones to recognize user activities Course: Master of Siense in Information communication and Technology Student: Nooshin Abdollah Director: Juan Luis Gorricho Year: December 2015
2 Contents Session 1 ............................................................................................................................................. 7 Introduction .................................................................................................................................... 7 Session 2 ............................................................................................................................................. 9 Android ............................................................................................................................................. 9 Tools need to start ..................................................................................................................... 10 Integrated Development Environment ............................................................................. 10 Android SDK ................................................................................................................................ 12 AVD Manager0 ............................................................................................................................ 14 Emulator ........................................................................................................................................ 15 Summary ....................................................................................................................................... 17 Android Structure ...................................................................................................................... 18 Source packages ......................................................................................................................... 19 Activities ........................................................................................................................................ 19 Services .......................................................................................................................................... 20 Content Providers ...................................................................................................................... 20 Broadcast Receivers ................................................................................................................. 20 Additional Components ........................................................................................................... 21 Fragments ..................................................................................................................................... 21 Intents ............................................................................................................................................ 21 Activities ........................................................................................................................................ 22 Starting state ............................................................................................................................... 23 Running state .............................................................................................................................. 24 Stopped state ............................................................................................................................... 24 Fragment activity ....................................................................................................................... 25 Broadcast Receivers ................................................................................................................. 27 Generated Source Packages ................................................................................................... 28 Resources: .................................................................................................................................... 28 Libraries ........................................................................................................................................ 30 Google-Play-Services-lib ......................................................................................................... 30 Google Play Services ................................................................................................................. 31 Google-Support-v4 .................................................................................................................... 32 Important files ............................................................................................................................ 32
3 Manifest File................................................................................................................................. 32 System Services .......................................................................................................................... 34 Location Services ....................................................................................................................... 34 LocationManager .............................................................................................................. 34 LocationListener ............................................................................................................... 34 LocationProvider .............................................................................................................. 35 Criteria .................................................................................................................................. 35 GeoCoder ............................................................................................................................. 35 Wi-Fi Services .............................................................................................................................. 35 WifiManager ....................................................................................................................... 36 WifiInfo ................................................................................................................................. 36 Connectivity Services ............................................................................................................... 36 ConnectivityManager ...................................................................................................... 36 Google Map ................................................................................................................................... 37 Debugging ..................................................................................................................................... 40 Adb .................................................................................................................................................. 40 Device or Android Virtual Device ........................................................................................ 40 Session 3 ........................................................................................................................................... 41 The Project definition .............................................................................................................. 41 Part 1: Android User Interface.............................................................................................. 44 Two Ways to Create a User Interface ................................................................................. 45 Views and Layouts ..................................................................................................................... 45 LinearLayout ...................................................................................................................... 45 RelativeLayout ................................................................................................................... 45 Building Project’s Activities ................................................................................................... 46 Part 1: Main Activity ................................................................................................................. 46 The Main Activity layout ......................................................................................................... 47 Strings Resource ........................................................................................................................ 49 The MainActivity Java Class ................................................................................................... 49 ExpandableListAdapter Function ........................................................................................ 50 Part 2: c_wifiScanActivity ....................................................................................................... 52
4 The c_wifiScanActivity layout ............................................................................................... 54 Part 2: The c_wifiScanActivity Java Class ......................................................................... 56 Location Service ......................................................................................................................... 60 Location Manager ...................................................................................................................... 62 LocationListener ........................................................................................................................ 63 LocationProvider ....................................................................................................................... 64 Criteria ........................................................................................................................................... 64 Geocoder ....................................................................................................................................... 65 Finding Location Providers by implying Criteria .......................................................... 65 Update Location by LocationListener ................................................................................ 67 UpdateWithNewLocation() method for Finding the Current Location and Previous Location of device ................................................................................................... 68 Public double calculateDistance (double lat1, double lon1, double lat2, double lon2) ................................................................................................................................................ 71 Activity Recognition.................................................................................................................. 72 myDrawLine() function ........................................................................................................... 74 Updating the Manifest File for Internet Permission..................................................... 78 Summary: ...................................................................................................................................... 81 Part 3: d_GsmScanActivity..................................................................................................... 84 The d_ GSMScanActivity Java Class ..................................................................................... 86 show_phone_details () ............................................................................................................. 89 MyPhoneStateListener() ......................................................................................................... 91 Summary: ...................................................................................................................................... 92 Part 4: Broadcast Receiver ..................................................................................................... 96 About Broadcast Receivers .................................................................................................... 97 _connectivityReceiver .............................................................................................................. 97 onReceive() callback Method ................................................................................................ 98 Log ................................................................................................................................................. 100 Registering the _connec tivityReceiver in the Android Manifest File .................. 100 Testing the connectivityReceiver ...................................................................................... 101 Summary ..................................................................................................................................... 101 C_WifiScanReceiver Broadcast Receivers ...................................................................... 102 The Database ............................................................................................................................. 104 About SQLite .............................................................................................................................. 104 MySQLiteHelper ....................................................................................................................... 104 The Database Schema and Its Creation ........................................................................... 105
5 Four Major Operations .......................................................................................................... 106 Cursors ......................................................................................................................................... 106 MySQLiteHelper ....................................................................................................................... 106 Connection.Java ........................................................................................................................ 108 Update C_wifiScanActivity ...................................................................................................... 110 Test the application ................................................................................................................... 111 Session 4 ........................................................................................................................................ 112 Test of Project ........................................................................................................................... 112 Session 5 ........................................................................................................................................ 116 Conclusion .................................................................................................................................. 116 Bibliography .............................................................................................................................. 117
6 Table of Pictures Figure 1. NetBeans IDE environment ........................................................................................ 14 Figure 2. Android SDK manager interface .............................................................................. 15 Figure 3. AVD manger main screen ............................................................................................ 16 Figure 4. The Configure Hardware window when creating a custom device configuration ....................................................................................................................................... 17 Figure 5: Android Emulator ......................................................................................................... 18 Figure 6: creating an android project ....................................................................................... 20 Figure 7: The activity lifecycle ...................................... ¡Error! Marcador no definido.5 Figure 8. The lifecycle of Fragment ............................ ¡Error! Marcador no definido.8 Figure 9: lifecycle of broadcast receivers ................ ¡Error! Marcador no definido.9 Figure 10. Process of Google Play Services.............. ¡Error! Marcador no definido.9 Figure 11: Console of Enable APIs for the application .................................................... 40 Figure 12: Credentials page in the Google Developers Console .................................... 41 Figure 13: The main screen of application ............................................................................. 44 Figure 14: the second activity ....................................................................................................... 44 Figure 15: First snapshot of A_MainActivity .......................................................................... 49 Figure 16: Second snapshot of a_ MainActivity .................................................................... 53 Figure 17. the c_wifiScanActivity screen .................................................................................. 55 Figure 18: First and Second Snapshot of c_wifiScanActivity ........................................... 84 Figure 19: Third and fourth Snapshot of c_wifiScanActivity .......................................... 85 Figure 20: a screen shot of d_GSMScanActivity..................................................................... 87 Figure 21: first snapshot of d_GsmScanActivity .................................................................... 95 Figure 22: First snapshot of d_GsmScanActivity after pressing Show Cell info Button ..................................................................................................................................................... 96 Figure 23: Second snapshot of d_GsmScanActivity to show all the GSM connection .................................................................................................................................................................... 96 Figure 24: Forth snapshot of d_GsmScanActivity ................................................................. 97 Figure 25 – The broadcast Toast message……………..………………………………………….98 Figure 26 : snapshot of database ............................................................................................. 113
7 Session 1 Introduction In this fast pace technology driven world, access to the Internet anywhere and anytime is playing a key role in human’s life, Moreover, most of the businesses attempt to consider the value of internet and its mobility in their provided market. The client architecture of Internet mobility devices includes of smartphones, tablets and laptops. Based on a research in 2012 in EU, using Internet by movable devices such as portable computer was 36% and by tablet 7% and the rest has belonged to the smartphone users. As is mentioned, popularity of access to Internet by smartphones and mobile phones has significant increase over recent years. Meanwhile, based on the “Global Smartphone Market Share 2012” research, 66.6% of smartphone clients use Android operating system devices. [10] The goal of this study is developing the fundamental techniques to define activity of the users like walking, running, standing or cycling while the user is using one of two different types of Network connectivity, GPRS or Wi-Fi. This method is knows as Activity recognition that it is one the new researches and reachable by embedded sensors of the smart phone devices such as GPS sensors, vision sensors, direction sensors and acceleration sensors. Recently this subject of user activities is taken into the consideration of some mobile applications which are used for health care especially for daily lives of older people more than the alarm when the person falls because of the heart attack. “Therefore by analyzing data is possible to define the action or state of the user with simple human activities such as walking, running, driving, bicycling and other classification methods.” [6] This study is not about using accelerometer sensor embedded in device, but calculating the distance of the user in a period of time by the longitude and latitude of the user´s location which has reached in the location recognizing. Therefore, the
8 main goal of the study to retrieve user’s activity is achieved by requesting location of user for each period of time, from current and previous location of user. In order to accomplish the project some steps have to be done. The first step would be identifying if the device is connected to either Wi-Fi or GPRS connection. When the network is Wireless it means the connection is indoor and when the user is outdoor the type of connection would be GPS. The second step would be getting the valid GPS location of the user. When it is outdoor, is needed to track the user location along the time. Afterward, in the third step, the user activity is concluded which is walking, running, driving or standing. When the user is outdoor, it must save the sequences of GPS locations along the daytime, so it will discover the user´s daily pathway.
9 Session 2 Abstract: In the session 2, I have explained Android programming language is used for creating and developing this study. So after an introduction about Android operating system, in the second part, I have sentenced the environment and its necessary tools for creating and developing an android project. In the third part of this session, I have described how to create an android project, then android project content components and entailed of the project. Android Android is a comprehensive and open source operating system framework for intelligent smart phone devices which has been created by Andy Robin, the manager of Android Company, then has been bought by Google Company in 2005. The word of Android means “Humanoid Robot”. In 2007, some proposed groups of producers in electronic equipment like cell phones and wireless equipment beside of some software companies including Google made a consortium with the goal of creation an Open Source Operating System of Cell phones in order to reduce expenses and costs of Mobile’s Applications. Therefore, this consortium with the name of Open Handset Alliance, has published Software Development Kit (Acronym SDK) consists of required software tools of developing Android Applications. The first cell-phone based on Android OS introduced in October of 2008 with the name of T-Mobile G1 by HTC Company. From that year onward, beside of cell-phones, these companies used the OS for other electronic tools such as Tablet, watch, electronic reader and even television. Android software has utilized the power of JAVA for constructing its applications with the format of apk for a package of an application. The most famous development environments of Android are Open Source programing environments named as Android studio, NetBeans IDE and Eclipse beside of ADT and ADK. This operating system has been optimized based on Virtual Machine Linux OS that is embedded as Dalvik for cell-phones devices. This virtual machine has several
16 services of the Android platform to invoke other applications, access the network, play audio and video, store and retrieve data, notify the user, and render graphical transitions and themes. Figure 5: Android Emulator The emulator also includes a variety of debug capabilities, such as a console from which you can log kernel output, simulate application interrupts (such as arriving SMS messages or phone calls), and simulate latency effects and dropouts on the data network. When you run your app from Android Studio, it installs and launches the app on your connected device or emulator (launching the emulator, if necessary). You can specify emulator startup options in the Run/Debug dialog, in the Target tab. When the emulator is running, you can issue console commands. Android Hardware Device Before releasing an application to users, it is important to test on a real device to see its performance clearly. For running, debugging and testing an application any
17 device equipped by android Operating system is suitable. The tools included in the SDK make it easy to install and run your application on the device each time you compile. It is possible to install the application on device by command lines of ADB or using USB drivers to run the application on the device. Android-powered devices have a host of developer options that you can access on the phone, which let you: Enable debugging over USB. Quickly capture bug reports onto the device by help of adb logcat. Show CPU usage on screen. Draw debugging information on screen such as layout bounds, updates on GPU views and hardware layers, and other information. Plus many more options to simulate app stresses or enable debugging options. Summary Setting up a development environment of android basically needs SDK and a java IDE.
18 Android Structure Once we have plugged the SDK in the plug-in and install NetBeans IDE, we are able to start and create an android application, develop it and set it up, run and debug configurations. Now we can start to create a new android project from file/new project, then in the appeared dialog, choose Android project and then click next button. In the new window, it will ask about the project name as the specific name of our project, project location and its folder. Package Name specifies its java package; the field of Activity name is to clarify of our initial and main activity. At end in Target Platform we can choose minimum SDK version that our application will be run on it. Figure 6: creating an android project In this part, a main structure of an android’s package is defined. There are five folders in the left side of environment Source Packages Generated Source Packages Resources Libraries
19 Important Files Source packages The source package of android project contains main Android components to build an application that includes all java source codes of application. In this part we have an overview on these components to understand how they are related to a real-world application. These components embedded in source package are main building blocks of an application. These perceptual components should be put and interact together to make a bigger whole. First we should have a conceptual draw of what we aim to create by lines and circles to have a general view of the idea and how we desire to relate these components together to make sense. Main building blocks of android are upstanding requirement of an application that is broken into conceptual units to work independently on each of them and then by putting they together reach to a complete package. These components are named as activities, Intents, services, broadcast receivers and content providers. In following we have a short overview on each of these components. Activities An activity as one of the distinguishing features of the Android framework is the interface of application that provides a screen for user to see the application in order to do something and interact with the application and user. So we can say they are visible part of application. Usually applications have more than one activity that one of them is the main activity which appears when we launch the application, like the home page of a website, and then we can navigate among other activities.
20 Services Services work like activities with a difference of their interface that services perform in background of device and are hidden from sights of users. They are used in order to run an activity invisibly for a while like playing music while user is working with another application. The point about services is that they have simpler structure than activities because of its requirement methods. Another point is its lifecycle which is handled by developer more than system. But we have to be aware about its shared resource consuming such as CPU or battery. Content Providers Content providers are data stores that facilitate applications to use, share and manage its stored sharable data. Because the nature of each application in android is to be isolated and work separately from other applications, so it means their data is not accessible by other application. In order to solve this, content providers are developed to pass through an application. For example, Contact Data is accessible by other application because of passing content providers through this application. Therefore, this application lets application to use its content by connecting to Contact Data application. The content providers use standard database methods of insert (), update (), delete (), and query () to have relatively simple interface. Broadcast Receivers The broadcast receivers are components of android that they are actively working in memory and background, like services are without interfaces and visual representation. They are mechanism of publish, subscribe, sending notifications in the device like sending notification when a message is received, when a call comes in or when the battery runs low.
21 Additional Components There are some additional components of Android in source packages in the construction of above mentioned components. These are listed below: Fragments They represent a behavior or a portion of user interface in an Activity. It means that when we want to create a multi segment in the user interface of an activity, we need to use fragments to encapsulate UI components and activity behaviors inside of a module to swap into and out of the activity. So we can have a nested activity that each activity has its lifecycle and own layout. Intents Intents are messages that are sent among the major building blocks. They trigger an activity to start up, tell a service to start or stop, or are simply broadcasts. Intents are asynchronous; meaning the code that sends them doesn’t have to wait for them to be completed. Intent could be explicit or implicit. In an explicit intent, the sender clearly spells out which specific component should be on the receiving end. In an implicit intent, the sender specifies the type of receiver. For example, your activity could send an intent saying it simply wants someone to open up a web page. In that case, any application that is capable of opening a web page could “compete” to complete this action. When you have competing applications, the system will ask you which one you’d like to use to complete a given action. You can also set an app as the default. This mechanism works very similarly to your desktop environment, for example, when you downloaded Firefox or Chrome to replace your default Internet Explorer or Safari web browsers. This type of messaging allows the user to replace any app on the system with a custom one. For example, you might want to download a different SMS application or another browser to replace your existing ones.
22 In following of this part, I go through the components in details that I have used in my project. Hitherto I have explained the important components of an android project that they have to be put together for constructing an application and run perfectly. In following, I want to explain more about building block components that I’ve used in my project to have better cognition of these components, how they work together and what they have inside. Activities Usually an application has more than one activity, the visible part of an application that user can flip back and forward among them like websites. An activity could contain one button to start another activity of application like choosing sending message when you are in contacts list then a new activity of composing message appears. The method that is using in activities in order to navigate between activities of an application is “Back Stack” or in another word “last in, first out”, that pushes an element to the collection of elements and pops to remove the last element that was added. Therefore when an application is launched, main activity of the application starts and then it interact with other bounded activities of the application. By starting new activity of application, the previous activity stops but maintains in the stack of the system. And when an activity starts it is pushed onto the back stack. Therefore, when user uses Back button, it will be destroyed and previous activity resumes. An activity has callback methods to perform specific work appropriate to the changed state such as resume, stop, create or destroy. These callback methods are essential in developing a strong and flexible application and managing the lifecycle of the application. For example when the resume method is called, all the necessary resources that were interrupted should be resumed. By these callback methods the lifecycle of application is provided. An activity interface is a subclass of Activity with implemented callback methods for different transitions in the application. The figure 7 lifecycle callbacks are shown:
23 Figure 7: The activity lifecycle Starting state First we have starting state or activity launched when the activity of application does not exist in the memory. When we launch the program, the activity goes through all callback methods of application to run it. This is one of the most expensive operations in terms of computing time and battery’s life. The application leads to “running state” from “starting state” by three different kinds of callback methods. onCreate(): In this method all the essential components of that interface of application such as buttons, textboxes, and views are implemented and called.
24 onStart(): Called when the activity is becoming visible to the user. Followed by onResume (). onResume(): refers to when application is running in foreground lifetime of an activity that starts by this method to interact with user. Running state The state of application that is visible and intractable by user like typing, touching screen or clicking buttons. When application is in this state it is using memory, resources and has to run as quickly as possible. Application can goes to stop state or paused state by onPause method. onPause(): This method is used when user is leaving the application, but it doesn’t mean destroying the application, the application is still running this activity is still visible and alive, partially transparent or doesn’t cover the entire screen. Stopped state The application comes to this state by onPause method that the activity is not visible but is in memory. And activity could be brought back to in front by calling onResume() method or could be destroyed by onStop() callback method and be removed from memory of device. Also Stopped activities can be removed from memory at any point. We can use onResume, onCreate or onStart() methods for backing to Running State or use onDestroy() method to finish the application and go to Destroy State. Destroyed state: The activity could be destroyed by onDestroy() callback method from stopped state then the activity is in background or destroyed when the system needs its memory. A destroyed activity is no longer in memory.
25 Fragment activity This component is responsible to present a behavior or part of user interface like maps in the interface of activity. It is kind of modular section of an activity with its own lifecycle that receive s its input events. Fragments have to be embedded in an activity and their lifecycle depended on the lifecycle of its host activity. This means when activity starts, they can be started too, but when activity is stopped they will be stopped too. The reason that I used fragment activity in the project is for embedding the Google map in an activity. The Google map activity has its own behavior and structure and it needs to be implemented in own activity. Another point about this component is that they have to be imported from extra libraries “google-play-services-lib”, I have explained more about this library in following pages (page 27). For managing the fragments, fragmentManager from the library of Android is utilizing. This should be called from getFragmentManager() from the activity. To define the location of fragment in the application, it uses findFragmentById(), to put take the place of fragment in an activity. The following figure shows lifecycle of fragment activities.
32 Google-Support-v4 The Android Support Library package is a set of code libraries that provide backward-compatible versions of Android framework APIs as well as features that are only available through the library APIs. Each Support Library is backwardcompatible to a specific Android API level. This design means that your applications can use the libraries' features and still be compatible with devices running Android 1.6 (API level 4) and up. Google map needs to be implemented through a separate activity, so the most suitable component to use in an activity to have Google map beside of other elements, is fragment activity. This component should be imported by Google- Support-v4. Important files In this directory one of the most important components of android is placed to configure files of the application. Manifest File Android has dedicated specific permissions for certain dangerous operation; so by this way has possibility of managing security of application installed on device. In addition, the application asks user for grant or ignore all these permissions as soon as application is installed on device. Accessing to system of device needs to define AndroidManifest.xml in the root directory file to declare the activity of the application. This file prepares important information of application like the number of activities of program. Its responsibilities are: Specifying the name of application.
33 Specifying components that are used in application like activity, broadcast and which component is a host of application. The important role is specifying permissions of application. The permission has ability of accessing to protected parts of API and interacting with other applications of the device and the application's components. The system will understand each application is launched under which conditions. Also it can specify the minimum level of API that application requires. The manifest.xml has its unique structure and legal elements. So we are not able to add new attributes or elements in its structure. The manifest file starts with a tag <manifest> and all elements are defined inside of this tag and then <application> tag. They are unique required elements that should be called but the other elements can be used more than one time or not be used. The other elements could be used more than one time or not be used are <activity>, <provider> and <service>. Therefore, inside attributes of each element are defined. Attributes are used to assign properties of an element like defining a theme for an activity. Although attributes are optional, some of them are used for specifying purpose of an element such as android: name to introduce the class name of the activity. One of the important elements of manifest is Permission elements to define limiting access of a part of code to data on the device. They are used for protecting critical data and code of application. Each label of permission demonstrates the restricted feature action. The element to declare a permission is <usespermission> in the manifest. So when the application installed on the device, the installer will check the authorities of the application that if they are signed by the application certificate or not.
34 System Services In this part I go through explaining services and important classes that I needed to use for developing the project. Android has a number of system services that are always on, always running and readily available for developers to tap into. Some notable services are Location service, Sensor service, Wi-Fi service, Alarm service, Telephony service, Bluetooth service, and so on. System services are started at boot time and are guaranteed to be running by the time your application launches. In this part, I’ll explain some of the system services that I used in my project. First, I’ll take a look at the Location service to demonstrate some of the concepts that are applied to most of the location services. Then, I’ll explain Wi-Fi services information to our status updates via the Wi-Fi service. To use Android system services we need to access to their own manager. These managers of each service use getSystemService method for passing in Context of service name. Location Services In order to construct a location-aware application, Google play Services of a standard Android platform provides us to access location data from available location providers by implying classes of location services in Android. Some classes to retrieve information of location are described in following: LocationManager This class provides accessing to other system location services to retrieve periodic updates of geographical locations. This class retrieves data from all local GPS and network location providers of the device’s area. LocationListener It can receive notifications of the updates and changes of the location, which is used in the method of LocationManager, requstLocationUpdatses (String, long,
35 float, LocationListener). So it provides callback methods which call when location is changed. LocationProvider It is an abstract superclass for location providers for periodic reports of geographical position of the devices. Criteria This is the class help to choose the best and suitable Location Provider, and it prepares a set of required properties of the LocationProvider. It can provide accuracy, power stage, ability to report altitude, speed, bearing and monetary cost. GeoCoder It is a class to retrieve geocoding and reverse geocoding to transform the longitude and latitude coordinates to the street address, postal code, city and other information of the location by reverse geocoding. This amount could be different for different location, that means for one location maybe it could show all information and for another just the name of city. In the GeoCoder a java.lang.object class, locale is called to specify language/country/variant combination of the location. And by the getDefault () method, have an appropriate and preferred locale of the user. Wi-Fi Services The service has some classes that provide us information about Wi-Fi connections, monitoring Wi-Fi connectivity and provides the primary API for managing all aspects of Wi-Fi connectivity. The manager element that Wi-Fi services pass through is Wi-Fi Manager.
36 WifiManager WifiManager is a class manger that monitors Wi-Fi connectivity and manages them. Also does broadcast Intents whenever the connectivity status of the Wi-Fi network changes, using an action. For example when an active Wi-Fi connection has been established, we can use the getConnectionInfo method on the Wi-Fi Manager to find information on the connection’s status. Also we can get a list of current network configurations such as ID, SSID and other details. WifiInfo WifiInfo is another sub-class of Wi-Fi Services to provide us all information about device’s active or in process Wi-Fi connection. The features such as Wi-Fi Frequency, return the BSSID and so on. Connectivity Services This service provides us the internet connection of device and its status. This service is used to monitor the states and configure failover settings, and control the network radios and set our preferred network connection. Like other services, this service needs to be implemented by its own manager and pass it in Context.CONNECTIVITY_SERVICE. ConnectivityManager The ConnectivityManager represents the Network Connectivity Service to answer queries about the state of network connectivity. At the other hand, it notifies applications when network connectivity changes. The duties of this manager is monitoring network connections, Send broadcast intents when network connectivity changes, attempt to "fail over" to another network when connectivity to a network is lost, Provide an API that allows applications to query the coarse-
37 grained or fine-grained state of the available networks and Provide an API that allows applications to request and select networks for their data traffic. Google Map The Google map object prepares an object in application to show the Google map in the application with the same appearance of the Google map application and some of its features. But there are some differences between the main application of Google map and its object in an application. One of them is this API is not included personalized contents and icons of places. Another, if it shows, all of them are not clickable. The object of “com.google.android.gms.maps.GoogleMap” implements a main class of Google Map Android API that includes all methods of the map. So it provides automatically access to Google Maps servers, data downloading, map display, and response to map gestures. In order to implement the Google map object, MapFragment or MapView are required to be added in the main threat application. MapView or MapFragment can display the map by the provided objects in location based services of Android. [13] The important is for developing a Google map in the application needs to get a certificate from android and Google map API key and add this key to the application. The point is this key is free and can support an unlimited number of users to use the Map API in their application. Therefore, we have to prepare a Maps API key from the console of Google developers by following link https://console.developers.google.com and then add the key to the AndroidManifest.xml. This key is considered as a specific certificate/package pairs. The application with same certificate can use the same API too. <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyDiNg51xYmg_330JV5aSYxIAJ4rGK4CLb8"/>
38 The Google map API key is a SHA-1 fingerprint key which is a cryptographic hash function to create a key based on the short form of the application digital certificate because of its uniqueness. Therefore, we have to create AN API object in the Google Developer Console. To do that at first needs https://console.developers.google.com/ link to go to which is the Google Developers Console and then after choosing the API project, create the project in this console. To see the list of our enabled APIs, we have to follow APIs & auth/APIs/Enabled APIs that we need Google Map API. Figure 11: Console of Enable APIs for the application
39 Figure 12: Credentials page in the Google Developers Console Then in the Credentials in the left side, we can see the API key of android application that as has been mentioned is a SHA-1 fingerprint code. Thus, the API key of application has to be added in manifest of the application. So, when the application runs, from manifest, Google Maps Android API v2 will read the key of application, and sends it to the servers of the Google Maps to receive confirmation of Google Maps data. This key should be added in the <application> element of manifest, that I have more specified it in the chapter 3. Now that the permission and confirmation of using Google Map API is ready, the developing of a way to draw a line is needed. In this class package are some simple ways to draw a shape in the application’s basic map. The three shape types provided by this class are A Polyline shape draws paths and routs on the Google map by a series of connected lines between points. A Polygon shape is created to have an enclosed shape on the Google map. A Circle is show of a circle on the Earth’s surface.
40 A Polyline provides our need of drawing route on the Google map of the application when the user is outdoor and it is using internet connection of mobile. Debugging The Android SDK provides most of the tools that you need to debug your applications. You need a JDWP-compliant debugger if you want to be able to do things such as step through code, view variable values, and pause execution of an application. If you are using Android Studio, a JDWP-compliant debugger is already included and there is no setup required. If you are using another IDE, you can use the debugger that comes with it and attach the debugger to a special port so it can communicate with the application VMs on your devices. The main components that comprise a typical Android debugging environment are: Adb Adb acts as a middleman between a device and your development system. It provides various device management capabilities, including moving and syncing files to the emulator, running a UNIX shell on the device or emulator, and providing a general means to communicate with connected emulators and devices. Device or Android Virtual Device Your application must run on a device or in an AVD so that it can be debugged. An adb device daemon runs on the device or emulator and provides a means for the adb host daemon to communicate with the device or emulator.
41 Session 3 Abstract: In this chapter, I am going to explain how I have created and developed my project by using android components, tools, methods, classes, libraries and so on. The idea is to define an android tool which recognizes the user’s activities such as running, walking, bicycling and driving while the user is connected to Internet. This is done by a simple body position independent algorithm and doesn’t need to use embedded Android sensors. In order to fulfill the goal of the algorithm, we need to collect data of device’s location regularly. It is mentionable that “location based services” is one the most important services has been imported and applied in my project. This service provides me many benefits for retrieving the information about current location of the device, processes of gathering data and useful information about location nearby. So I have proposed a development for location based of Android services which gives us required information based on device’s location. The Project definition An android project is an appearance collocation of activities, services and broadcast receivers to work together and their incorporation. The project covers of two main building blocks of android, Activity and Broadcast Receiver, and other additional components Fragment activity and Intent. As it has been mentioned in previous chapter, each component works individually and works together by fitting them properly. The figures, 13 to 14 show what looks like the project at end to achieve the goal.
48 size for itself. I gave this fill_parent property to RelativeLayout screen that it covers all the screen of device with any kind of screen size. In the other hand, in some widgets like TextView, ExpandableListView, Button, I have used wrap_content for their width and height that means it requests for as much as possible space to display its own content. One of the important and necessary properties is ID that should be identified for each widget. It is the unique identifier for a widget in a layout for calling the widget in the java code. It has to be defined in the in this way "@+id/menuexpandable”. The other property is text property which it is used for some kind of widgets such as Button or TextView and they can specify a text inside a widget. <?xml version="1.0" encoding="UTF-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/menuexpandable" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/fons_blur"> <TextView android:id="@+id/menuexpandableTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dip" android:layout_marginBottom="10dip" android:layout_marginLeft="10dip" android:textSize="24sp" android:textColor="@color/black" android:text="Select Option:"/> <ExpandableListView android:id="@id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@id/menuexpandableTextView" android:layout_marginLeft="10dip"/> </RelativeLayout>
49 Strings Resource In order to applying any changes in resources of a project, that applies on whole the package, Android has a policy to keep data in separate files. A separate file to save all the layouts of project, or defines another file name as string.xml to save values to hold text values such as button text or title text. Later in this chapter has been explained more about this file that includes of name/value. The MainActivity Java Class The layout of the main activity is ready, now I can define its java codes. Its java class, a_mainActivity.java is already created in com.wireless.edu java package. An activity needs to start needs to start by defined sub-classes in the Android's framwork. So we should override the defined inherited methods of used sub-class. So firsly, we should use onCreate() necessary method to override all the widgets, describe the screen and starts its state machine. In this screen, onCreate() method has responsibility of set up the expandable list menu that response to clicks and connect us to other activities. When we use public void onCreate (Bundle savedInstanceState), we need to pass a small amount of data by Bundle through onCreate() method which this bundle is prepared by super.onCreate(savedInstanceState). Also, this method provides the original small amount of parents into the activity by the intent that started it. The first thing after calling the super method is to load the UI xml file in the activity and inflate it into the java memory space that for this activity it is called “inflating from XM”. This is done by setContentView (R.layout.main) method. So java will be able to open its related XML layout, parses it and prepares a space for each element that is defined in the XML. As I have mentioned in session 2, R class is an automatically generated class that connects Java and XML and all the other resources together to communicate. As you can see in the figure, there are two elements, one TextView filled by Select
50 Option and an Adapter List with sub-list of Wi-Fi and Telephony. In order to preview the list I have used ExpandableListAdapter. ExpandableListAdapter Function In the main activity we need to create a list group with its children. In order to create a list, adapter is the class to be used, it can map static data defined in xml to group and child view for initiating a list. In the separate xml file the views to display in a group are defined, then they map from keys of each element. This Process is same for a child too with one-level deeper. The first List corresponds to the group of the child, the second List corresponds to the position of the child within the group, and finally the Map holds the data for that particular child. After defining an object of adapter, we fill it with SimpleExpandableListAdapter (Context context, List<? extends list <? extends Map < String, ? >>> childData, int childLayout, String[] childFrom, int[] childTo). mAdapter = new SimpleExpandableListAdapter( this, createGroupList(), R.layout.a_group_row, new String[] { NAME }, new int[] { R.id.menuexpandibleGroupTextView }, createChildList(), R.layout.a_child_row, new String[] { NAME }, new int[] { R.id.menuexpandibleChildTextView } ); setListAdapter(mAdapter); } The CreateGroupList() function, contains of an object of List<Map<String, String>> and a menuItem object of CharSequenc[] array filled with its correspond defined
51 elements in xml view. The CharSequence is an interface that represents an ordered set of characters and defines the methods to probe them. private List createGroupList() { List<Map<String, String>> groupList = new ArrayList<Map<String, String>>(); CharSequence[] menuItems = getResources().getTextArray(R.array.menuItems); for(CharSequence item : menuItems){ Map<String, String> groupMap = new HashMap<String, String>(); groupMap.put(NAME, item.toString()); groupList.add(groupMap); } return groupList; } At least I had to mention that because of using Expandable List, we need to extend the main activity class to ExpandableListActivity as follow. public class a_MainActivity extends ExpandableListActivity {} The createGroupList() is defined by a list of grouplist that gets items for menuItem from /res/values/array.xml to returns the group list. The code snip of array.xml is placed here. <string-array name="menuItems"> <item>WiFi</item> <item>Telephony</item> </string-array> By applying these codes we will have the following screen shot. In addition, I have defined a Sub-List for both of options to achieve the figure 16.
52 Figure 16: Second snapshot of a_ MainActivity Part 2: c_wifiScanActivity After doing click on Wi-Fi we will be navigated to this activity. In this part I explain the layout of this activity, and then its java class and other necessary components to implement this activity. The figure 17 presents whole the layout of c_wifiScanActivity.
53 Figure 17. the c_wifiScanActivity screen I am going to create a new activity and build it based on below steps to develop all the elements that are shown in the figure 17. First defining its layout Importing services that we need to use Defining Wi-Fi information and ….
54 Location detection Updating location Defining the user activity Refer to a database that reserve our desired data Importing Google map The c_wifiScanActivity layout As you can see in the figure 17 this activity is consist of five TextViews and a Google map and one Button that all the elements are embedded in a RelativeLayout view group with fill_parent property to covers all the screen of device with any kind of screen size. In this activity I have a quite bit of data which has to be shown in TextViews and Button and all of these widgets have to be fit in a half of the screen, so I needed to use ScrollView to wrap them in a part of screen and provide us a scroll bar to up and down. This view works like the window that by scrolling we will be able to have a larger screen more than space which device allows us to use. Inside of ScrollView, a LinearLayout is solicited again to ask fill_parent properties for layout_height and layout_width and fill all the space that ScrollView can provide us. To refer the Google map instance as a fragment class in the activity, I had to use fragment to set the inside of it in XML layout. One notable property that is used in this layout is layout_weight equals to 1. This property is defined in ScrollView and fragment tags to imply weight for layout requirements and we are requesting half of the screen for ScrollView and half of the screen for the Google Map. Another widget that is utilized in this layout is button. For button we have to use wrap_content for its layout_height and layout_width because it won’t need more space to take. In following you can find the layout of this activity.
55 <?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"> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ wifiscan" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:background="@drawable/fons_blur"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TextView android:id="@+id/GsmScanTextView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:layout_marginTop="10dip" android:layout_marginBottom="10dip" android:textSize="12sp" android:textColor="@color/black" android:background="@color/white" android:text="To show Cell Info press button"/>
56 <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SHOW CONNECTIONS" /> </LinearLayout> </ScrollView> <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mapview" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" class = "com.google.android.gms.maps.SupportMapFra gment"/> </LinearLayout> Part 2: The c_wifiScanActivity Java Class The layout of this activity is ready, so we can define its related java class, c_wifiScanActivity. This activity is a main building class like the previous activity so firstly it is needed to define its provided subclasses of android framework. So it starts with overriding onCreate() method to define elements which should be implemented. This activity extends FragmentActivity to support the android.support.v4.app library and provide some useful features and ensure us about compatibility of application with older versions of Android. public class c_WifiScanActivity extends FragmentActivity {….. }
57 In this activity, I need to use Wi-Fi service to give me information about the Wi-Fi connection of device. So I should import its java class WifiManager by getSystemService () method, and import all the Wi-Fi services in a WifiManager object. wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); The forth step of this part is device’s location detection while it is using Wi-Fi. In order to achieve this idea we need to apply location services of android and import them in a location manager that is able to manage all the information that is provided by location services. I will explain about it in following of this part. Afterward as I have mentioned, the seventh step of this activity is to save all information that we requested in the database that we defined. In onCreate() method we have to pass the database through the onCreate(). This would be discussed in following parts completely. After passing the database, we have a button that should be defined in onCreate() method that is related to our database. So we need to set up the button to respond to clicks and connect us to the application’s database activity that shows a table of data. This is a user interface object which has its own defined methods to do an action. The method that help us to execute certain code when the button is pushed is onClick() method has to pass it through the setOnClickListener method on the Button. myButton = (Button)findViewById(R.id.button1); myButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i=new Intent(c_WifiScanActivity.this, f_Conne ctionList.class); startActivity(i);}});}
64 LocationProvider It is an abstract superclass for location providers for periodic reports of geographical position of the devices. This class helps the application to get a list of available location providers on the device. The methods used in the project related to LocationProvider are: getAccuracy() to retrieve horizontal accuracy of the provider. getName() for receive name of provider. Criteria This is the class help to choose the best and suitable Location Provider, and it prepares a set of required properties of the LocationProvider. It can provide accuracy, power stage, ability to report altitude, speed, bearing and monetary cost. setAccuracy() :It represents the amount of accuracy of longitude and latitude that could be ACCURACY_FINE that desired location is fine, or ACCURACY_COARSE that has more accuracy with constant value of 2 (0x00000002) that is two times more than ACCURACY_FINE. setAltitudeRequired(): It is a Boolean method that indicated if Altitude is needed or not by demanding setAltitudeRequired(false) or setAltitudeRequired(true). setBearingRequired() : A Boolean method to indicate that if the bear information is needed or no. setCostAllowed(): This is also another Boolean method to say if is allowed to incur monetary cost. setPowerRequirement(): The desired level of power, that could be defined in three ways, ACCURACY_LOW, ACCURACY_HIGH or NO_REQUIERMENT. In the project POWER_LOW is used because of reducing the consumption of power and taking time.
65 Geocoder A class to transform longitude and latitude coordinates of the location to return street address, postal code, city and country of the location. Is possible that for a location it be able to return all information about the location but for another location couldn’t retrieve all information. A Geocoder class is called in this order Geocoder (Context context, Locale locale). The locale is user to present language, country, and variant combination. It is used to notice about existence of information such as numbers, dates of a region. After defining the Geocoder object, we try to prepare a list by getFromLocation (double latitude, double longitude, int maxResults) for obtaining an array of known addresses and getting the accurate or best guess information of location based on longitude and latitude. After filling the address list object with gc.getFromLocation(), we can retrieve address line, locality, postal code and the country name of location. Finding Location Providers by implying Criteria I have used Criteria class of Android to provide the best provider of the user based on our defining, setting requirements and choosing Contexts for using each one of its methods for a location provider in terms of accuracy, power and abilities of returning altitude, and speed. In the following snip code you can see what values are set for the provider. Here I have a short definition for methods and the context that I have used to get the best location provider. setAccuracy() that can be set by one of following accuracy contexts. - ACCURACY_FINE - ACCURACY_COARSE setAltitudeRequired() a Boolean method for defining if we need altitude or not.
66 setBearingRequired() setCostAllowed() setPowerRequirement() that can be set by one of three below contexts to set the power amount which is received by provider. ACCURACY_LOW ACCURACY_HIGH NO_REQUIERMENT POWER_LOW public void onCreate(Bundle icicle) { locationManager= (LocationManager)getSystemService(Context.LOCATION_SERVICE); criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); String provider = locationManager.getBestProvider(criteria, true); location = locationManager.getLastKnownLocation(provider); locationManager.requestLocationUpdates(provider, 2000, 10, locationListener); } As you can see in the snip code, the criteria are called by getBestProvider of LocationManager service to give us a name of criteria. After finding the location of device and getting to know about the location provide based on our setting, we need to request from application to do this regularly. So we have to use requstLocationUpdates() method of location manager to register for location updates by getting, provider, minimum time interval between location
67 updates, in milliseconds, minimum distance between location updates in meter and a pending intent of location listener. Update Location by LocationListener A LocationListener class is a callback method called by the location manager to return or do an action due to any changes or updates of location. As I have mentioned, the location Listener is an important service for listening to the changes and sends or receives notifications when the location is changed, the provider is enabled or disabled and when the status is changes. These methods are named as onLocationChanged(), onProviderDisabled(), onProviderEnabled() and onStatusChanged(). private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateWithNewLocation(location); } public void onProviderDisabled(String provider){ updateWithNewLocation(null); } public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras){} }; The important method that is used by location listener in onLocationChanged() callback method, is updateWithNewLocation(location) method. That I can say that it is a milestone of my project, and by this method I have lots of progress. This method besides registering updates by location manager provides me current and previous location of device and so on, I was able to find distance of previous and
68 current location and then Activity Recognition that all of them are explained in following. UpdateWithNewLocation() method for Finding the Current Location and Previous Location of device In the onCreate() override method we defined an object of location that gets the last known location by calling getLastKnownLocation method of location manager for retrieving the last location that device could distinguish and we should pass it through updateWithNewLocation(location). So the method gets the location object that is filled with all solicited information. First of all function updateWithNewLocation(Location location) provides us the of longitude and latitude double amounts of the current location by two location methods of getLatitude() and getLongitude(). Then these values are set to show on a TextView on the screen. public static double nlat; public static double nlng; nlat = location.getLatitude(); nlng = location.getLongitude(); latLongString = "Lat:" + nlat + "\nLong:" + nlng; myLocationText.setText("Your Current Position is:\n" + latLongString); Now we can continue the updateWithNewLocation method after extracting the latitude and longitude of the current location and having location’s string address to show it on myLocationText TextView element of the screen. Then we have utilized GeoCoder class of location based services to show the street address, city and postal code of the current location of device because longitude and latitude are geographical values of location and user has no idea about them.
69 This class can transform longitude and latitude coordinates to real-world addresses. Geocoder has two responsibilities, one is “Forward Coding” which detects the longitude and latitude of a partial address, and the other is reverse coding which acquires us the street address of device. If we don’t specify a locale 1 , it assumes the device’s default, by the way I have indicated to return the default locale of user. Geocoder gc = new Geocoder(this, Locale.getDefault()); Both geocoding functions return a list of Address objects. Each list can contain several possible results up to what is specified. To define a string street address, we have to use Reverse Geocoding and pass its getFromLocation method through a List<Address> with this format (double latitude, double longitude, int maxResults). This method will return a list of possible address matches to the specified properties. If the GeoCoder could not resolve any addresses for the specified coordinate, it returns null. For the result of this method we have an array of addresses that describes the area. Then we modified the updateWithNewLocation method to instantiate a list of addresses and passed in it the newly received location and limiting the results to a single address. In an address object all the required information are defined by the following methods: getMaxAddressLineIndex(): To return the largest index currently used to show a address line. getAddressLine(): This method can specify a line of the address numbered by given index i. getLocality(): Defines locality of the address or null if is not defined. 1 - Locale represents a language/country/variant combination. Locales are used to alter the presentation of information such as numbers or dates to suit the conventions in the region they describe.
70 getPostalCode getCountryName After all of these processes we will have the exact location of the user in terms of geographical and real-world values. I have added the following snip code to the updateWithNewLocation() method. private String updateWithNewLocation(Location location) { try { List<Address> addresses = gc.getFromLocation(nlat, nlng, 1); StringBuilder sb = new StringBuilder(); if (addresses.size() > 0) { Address address = addresses.get(0); for (int i = 0; i < address.getMaxAddressLineIndex(); i++) sb.append(address.getAddressLine(i)).append("\n"); sb.append(address.getLocality()).append("\n"); sb.append(address.getPostalCode()).append("\n"); sb.append(address.getCountryName()); } addressString = sb.toString(); } catch (IOException e) {} } else { latLongString = "No location found"; } myLocationText.setText("Your Current Position is: \n" + latLongString + "\n" + addressString); return addressString;}
71 Before it is discussed about calculating the distance of user by retrieving longitude and latitude from its previous location and current location while is using internet. Although updateWithNewLocation() method provide us longitude and latitude of current location, it won’t keep in its memory the previous location of user. So the solution for having both current and previous locations and their geographical values is to define two double values with name of plat and plng and at first define them with zero value. While the activity is running and getting current user’s location information, these two values are filled too. When the first location has value of location.getLatitude() for current location latitude as defined nlat and nlng is also equal to location.getLongitude(), plng and plat are amounted to zero. But when the location changes, we contextualize nlat and lng to nlat and nlng that are previous values of location before getting new location latitude and longitude to nlat and nlng. So we need to add them our updateWithNewLocation method. In next part, I have explained about how the distance between two point is calculated. Public double calculateDistance (double lat1, double lon1, double lat2, double lon2) Before explaining the algorithm, I should explain about how the amounts of longitude and latitude that are based on degree, are converted to radians for these calculations. In following I explain about mathematical way of converting Degree to Radian and then the calculateDistance() method of the project. The formula is used which calculates the distance between two points in a great circle, Earth is Heversine formula. It calculates the shortest distance of two points over the earth’s surface. Is just about the distance based on sea surface and didn’t consider the altitude. Heversine formula:
72 a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2) c = 2 ⋅ atan2( √a, √1 - a ) d = R ⋅ c - Distance of two points on the earth Δφ – subtraction of latitude degrees in Radian Δλ – subtraction of longitude degrees in Radian R – Radius of the Earth The following snip code is illustrating how the Heversine formula is implied in the project. double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); double angle = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2 * Math.atan2(Math.sqrt(angle), Math.sqrt(1 - angle)); double raio = 6378100; double distance = raio * c; When we have distance of previous and current location of device, we can define the activity of user by its velocity. This is demonstrated in following part. Activity Recognition Now we can get to the aim that is activity recognition based on applying location based services. As is explained, the first step is to collect data from smartphone user by carrying and storing its locations in the memory of mobile device. Second step is to transfer data and use Heversine formula. Third step is the classification process where unknown activity template will be compared in a loop with every activity template from predefined training set. After calculating distances between each type of activity and target activity, algorithm will display as result that activity
73 which will have minimal distance from the unknown one. Thus, the accuracy of results mostly depends on the templates that were chosen for selected activities. [7] Based on what we have done to now, we have longitude and latitude of two different that maybe it doesn’t change while user is standing. Then we calculate distance of user from its previous point, so by retrieving the distance of two points, it is possible to calculate the velocity of the user if we request it for periodic of 20 seconds. Afterward velocity of the user is can conclude the activity of user such as walking, running and driving which is the goal. int timer = 20; if ( velocity < 5 && velocity >= 1){ myMotion.setText("the user is WALKING"); myAction = "walking"; } else if (velocity < 10 && velocity >= 5){ myMotion.setText("the user is RUNNING"); myAction = "running"; } else if (velocity < 15 && velocity >= 10 ){ myMotion.setText("the user is CYCLING"); myAction = "riding"; } else if (velocity >= 15){ myMotion.setText("the user is DRIVING"); myAction = "driving";} else if (velocity < 1 ){ myMotion.setText("the user is STANDDING"); myAction = "standing"; } And then the function calculateDistance(double lat2,double lon2,double lat1,double lon1) which need to get four entries is called in the updateWithNewLocation() function that already provides us the current and previous location’s longitude and
80 ”android.permission.ACCESS_NETWORK_STATE”> After permissions we have to declare building blocks that we are developing them in them project in a <application> tag. Here we have ready an activity element that should be declare in a tag of <activity> and label it as we want, but for name we should write its .java name. <application android:label="@string/app_name" > <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <activity android:name=".c_WifiScanActivity" android:label="WiFi Scan" android:screenOrientation="portrait" android:windowSoftInputMode="stateHidden"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> </application> And at the end, for the Google Map we have to use a <meta-data> tag that is a name-value tag for additional data that we want to supply it to the parent component. For Google map we assign a value and name as unique name for this item. Name of this meta data for Google map is the package of API_KEY and for value we have to use the certificate key which Google provided us to use in the application. <meta-data android:name="com.google.android.maps.v2.API_KEY"
81 android:value="AIzaSyDiNg51xYmg_330JV5aSYxIAJ4rGK4CLb8"/> Summary: By the end of this part, when this layout of application is run, it looks like Figures 18 - 19. That as you can see it successfully can show the state of Wi-Fi which device is connected and shows the IPaddress, MACAddress and RSSI in first TextView and in second TextView it declares name of router which device is connected and its signal power of the Basic Service Set Identifier(BSSID) of recent Basic Service Sets.
82 Figure 18: First and Second Snapshot of c_wifiScanActivity
83 Figure 19: Third and fourth Snapshot of c_wifiScanActivity In the third TextView illustrates our Current Position in terms of Human readable and Geographical information latitude and longitude. Then in fourth TextView shows the User’s Activity and at least TextView at the end Distance and velocity are displayed. Show button is related to our database that I have explained about it in following and at the end, in the second part of activity we have Google map that shows our location and the movement of device which is showing by black color.
84 Part 3: d_GsmScanActivity This activity starts to work by clicking on the Telephony and GSM scan of the list, we will be navigated to this activity. In this part I am going to skip explaining its layout because is similar to c_wifiScanActivity’s layout. Also its java classes are similar to c_wifiScanActivity activity with some differences, so I will explain about the utilized additional methods and differences in the activity. This activity also has similar steps as the previous one, and uses some extra libraries of android. In following I have mentioned the additional methods and libraries that are used in this activity. Importing additional services Show phone details() method MyPhoneStateListener() method This activity has the whole layout as is presented in the figure 20.
85 Figure 20: a screen shot of d_GSMScanActivity
86 The d_ GSMScanActivity Java Class This activity is started by onCreate() callback method to create all the widget, and Google map of the screen as you can see in the figure 20. In this activity also we will to find information about the cell that device is connected to network. So here one of the differences among these two activities has been appeared, because we don’t need to imply Wi-Fi services to get information of location. The service that we are going to use is TELEPHONY_SERVICE that has been mentioned in previous session. In this activity, we will to retrieve information about the cell that device is currently using its services, so in order to access to the telephony APIs we have to request TELEPHONY_SERVICE context of android and pass it through a Telephony Manager for enabling us to use elements and methods of this service and handling management features of the device. We have used telephony manager to provide us many properties of telephone, the device information, network information and data state details. The applied methods of telephony manager are listed below: getNetworkOperatorName(): returns the alphabetic name of current registered operator. getNetworkOperator: returns the numeric alphabetic name of current registered operator. getCellLocation(): Returns the current location of the device. getNeighboringCellInfo(): Returns the neighboring cell information of the device. getPhoneType():Returns a constant indicating the device phone type. This indicates the type of radio used to transmit voice calls. The phone types that are predictable by this method are GSM, CDMA, SIP and none if it doesn’t know the type. getDataActivity(): Returns a constant indicating the type of activity on a data connection (cellular). The constants that can represent are activity in, activity out, activity in-out and dormant.
87 getDataSet():returns a constant indicating the current data connection state. So after passing TELEPHONY SERVICES through a telephony manager instance, we are able to have above information. This should be created in onCreate() callback method of this activity. So we have updated in the activity by following snip code: TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); Now we need to instantiate an instance for recognition of device connectivity to network. In order to retrieve this information, we need to use one of the Android’s Services with the name of CONNECTIVITY_SERVICE. In session 2, CONNECTIVITY_SERVICE is also mentioned that this Context is the service of handling management of network connections. Like the other services, also we need to utilize a manager in order to keep all information of the service inside of itself. So an object to keep values of network has to be defined like following: (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE) onResume() The active lifetime of application starts with onResume() callback method to receive events. We want to keep the application responsive when the foreground is moving in and out. This method should be light weight and can be used for registering a broadcast receiver or a process that need to be stopped in onPause(). In this override method, I want the activity listens to any changes of the telephony states and receive notifications. For this reason, we need to register a listener object and pass a PhoneStateListener through it and define which contexts of PhoneStateListener are in mind to receive its events. So we have used listen () method of telephony manager and beside of passing myPhoneStateListener as an
88 object of MyPhoneStateListener() through it, we requested to for monitoring the following events. LISTEN_SIGNAL_STRENGTH LISTEN_CELL_LOCATION LISTEN_CALL_STATE The following snip code shows the way of applying this method. protected void onResume() { super.onResume(); telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTH | PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_CALL_STATE); } While the application is listening to events and receiving notifications, it updates information of the cell and shows them in the second TextView. onPause() Now we have to end the listening to events which we called in onResume() by onPause () method and unregister it. So the telephony manager should stop listening updates and notifications by unregistering listener and LISTEN_NONE event pass through listen() method. protected void onPause() { super.onPause(); telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_NONE); }
89 In this activity, I have defined two additional methods to work with telephony manager. They named as show_phone_details() and MyPhoneStateListener() that in following of this part, I am going to briefly outline them. show_phone_details () This method focused on demonstrating information about the cell by utilizing telephony manager as soon as this activity is run, so this method should be called in onCreate() overriding method to show us basic information of cell in the first TextView of screen as you can see in the first figure of figure xxxx. It uses getPhoneType() method of telephony manager to retrieve type of phone such as SIP, CDMA and GSM. And then it shows the device ID by getDeviceId() method and get number of cart by getLine1Number() method of telephony manager. And at least getDataSet() method to returns a constant indicating the current data connection state. private void show_phone_details(){ int phoneType = telephonyManager.getPhoneType(); switch (phoneType) { case (TelephonyManager.PHONE_TYPE_CDMA): TextView1.append("\nPHONE_TYPE_CDMA"); … } String deviceId = telephonyManager.getDeviceId(); String phoneNumber = telephonyManager.getLine1Number(); int dataActivity = telephonyManager.getDataActivity(); int dataState = telephonyManager.getDataState(); switch (dataActivity) { case TelephonyManager.DATA_ACTIVITY_IN:
96 Part 4: Broadcast Receiver In this part, I want to develop broadcast receivers to alert application the connection type of device. The first scenario of this Broadcast receiver is when the device is powered up and working, it starts to detect and monitor the Network connection and send a toast message. And the second scenario is to save all types of connection after checking, by a method that is defined in this Broadcast Receiver. First we have an overview on how broadcast receivers work. Figure 25 – The broadcast Toast message
97 About Broadcast Receivers As I have explained in session 2, Broadcast receivers are one of the building blocks of Android for implementation of the Publish/Subscribe messaging pattern, or more precisely, the Observer pattern. We are using this element for working in background without taking in account that if anyone will get them to send events. So BroadcastReceiver is an element of application in order to get notified and send notifications when an action happens. This action is a type of intent broadcast that when it happens the receiver wakes up and does something. The onReciver () is its callback method that do something when application receives an event. _connectivityReceiver In the application the broadcast receiver is responsible for monitoring network connectivity and announce about the internet connection of mobile based on any modification in the Internet connection, and alert with four different sentences by any changes. This broadcast receiver is divided into main two parts OnReciver callback Method Log method As we want the broadcast starts to monitor the system automatically while the device is working, we create _connectivityReceiver. So we Create connectivityReceiver by extending it from its base class BroadcastReceiver. public class _connectivityReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) {} public void log(Context context, String sentence){} }
98 onReceive() callback Method As you can see it has two methods inside of the BroadcastReceiver. So we start with overriding onReceive (Context context, Intent intent) callback method. This method gets calls when intent matches this receiver. For my application, first it tries to figure out if we are connected to Wi-Fi or disconnected from Wi-Fi, also if we are connected to mobile/GPRS or disconnected. By any changes it the connection it will send a toast message to inform user about connections. To define the type of connection, first should recognize if the device is connected to Internet or not, so it is necessary to use two service managers of android with name of WifiManager and ConnectivityManager. There are services for Wi-Fi or GPRS connectivity, monitoring and modifying the network settings and accessing to the point scans. [1] In this case, Connectivity Service provides us a high level view on monitoring and availability of network. By utilizing its manager, besides of providing queries about the network connectivity states can send a notification in order to changes in the connectivity type or state. To notify us when any event happens, the broadcast receiver should pass through Intent for listening to connectivity of device and any changes of connection therefore does a predefined action. It is done by ConnectivityManager. CONNECTIVITY_ACTION broadcast as is shown in the following manifest snip code. The Intent contains extras to provide us additional information about changes in connectivity. <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> </intent-filter> After that, in order to describe the status of network interface and see what kind of connectivity event occurred, the NetworkInfo class is utilized. The NetworkInfo class is used to find the connection status, network type, and detail the state information of the returned network. We can define status of the
99 network by a NetworkInfo object that it has responsibility of describing the status of a network interface. Its methods to use are as below: getTypeName(): Which will return a human-readable name which clears is WIFI or MOBILE. getState(): to return the current coarse-grained state of the network. isAvailable() isConnected() getSubTypeName(): a human-readable name of subtype of network. The following snip code shows the onReciver() method that is portioned into four parts to check the connection and its type. Before that I have to mention that getParcelableExtra() method extends data from intent and gives us extra information such as reason of failing and other information of the mentioned network. NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && !networkInfo.isConnected()) {} if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {} if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) {} if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE && !networkInfo.isConnected()) { …} By distinguishing any kind of these conditions, The onReciver() method will toast a message, then will retrieve date of changes and save them in history of device by the method defined in the second part of this building block. if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE && !networkInfo.isConnected()) { // TYPE_MOBILE is disconnected Toast.makeText(context, "TYPE_MOBILE is disconnected", Toast.LENGTH_LONG).show();
100 Date date = new Date(); log(context, "TYPE_MOBILE is disconnected at: "+ date.toLocaleString() + "\n NetworkInfo:" + String.valueOf(networkInfo)); } Log The log class is used in order to send an output of logs. The point of developing the log class is, saving all information of connectivity in a file that can be executed from device by referring to its direction. The logfile.txt texts is saved in …\Internal Storage\Android\data\edu.upc.wireless\files directory of device. To return an absolute directory path for an external file, getExternalFilesDir(String type) method of Context class helps to find package’s directory. This method allocates an own external path where the application is placed. Then for writing bytes on a file that we already defined it as logfile.txt, FileOutputStream() method is applied. File dir = context.getExternalFilesDir(null); File file = new File(dir, "logfile.txt"); FileOutputStream fos = new FileOutputStream(file, true); PrintWriter pw = new PrintWriter(fos); pw.println(sentence); pw.close(); fos.close(); Registering the _connec tivityReceiver in the Android Manifest File The following snip code declares connectivityReceiver registration in the manifest file. In addition, an intent filter is added to this file. This intent filter specifies which broadcasts trigger the receiver to become activated. <receiver android:name="._connectivityReceiver" android:enabled="true" android:label="ConnectivityReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> </intent-filter>
101 </receiver> Testing the connectivityReceiver At this point, we tested the application on the device. When it comes back up, it monitors connections and notifies by a toast message that device is connected or not. In addition, we can verify its performance by looking at LogCat of output or by ...\Internal Storage\Android\data\edu.upc.wireless\files route and see all the connections are kept in this logfile.txt. Summary At this point, we tested the application on the device. When it comes back up, it monitors connections and will notify by toast message that device is connected or not. In addition, we can verify its performance by looking at LogCat of output or by Computer\XPERIA sole\Internal Storage\Android\data\edu.upc.wireless\files route and you can see all the connections are kept in this logfile.txt. In following a part of WifiScanActivity which is related to broadcast receivers is explained.
102 C_WifiScanReceiver Broadcast Receivers The wifiScanReceiver is a broadcast receiver applied in C_wifiScanActivity.java for listening to all the Wi-Fi connections of device and return the required information about state, IP address Mac address RSSI and others. private class WifiScanReceiver extends BroadcastReceiver{ public void onReceive(Context c, Intent i){ WifiInfo wifiInfo = wifiManager.getConnectionInfo(); increaseCounter(); stateTextView.setText(headline+ "\n\nscan #"+counter+", wifi is enabled? "+wifiManager.isWifiEnabled()+ "\nwifiInfo.supplicantState: "+wifiInfo.getSupplicantState()+ "\nwifiInfo.IPaddress: "+wifiInfo.getIpAddress()+ "\nwifiInfo.MACaddress: "+wifiInfo.getMacAddress()+ "\nwifiInfo.Rssi: "+wifiInfo.getRssi()); stateTextView.append(Show_configurations()); if(!wifiManager.isWifiEnabled() || wifiManager.getScanResults().isEmpty()) return; StringBuilder sb = new StringBuilder("SCAN RESULT #"+counter+" \n-------- -------\n"); for(ScanResult scanResult: wifiManager.getScanResults()){ sb.append(scanResult.SSID+"\n"); sb.append(scanResult.BSSID+" = "+scanResult.level+" dBm \n\n"); } sb.delete(sb.length()-1, sb.length()); scanShotTextView.setText(sb.toString()); } private void increaseCounter(){ counter++; if(counter%2==0){ scanShotTextView.setTextColor(ORANGE); stateTextView.setTextColor(BLACK); } else{
103 scanShotTextView.setTextColor(BLACK); stateTextView.setTextColor(ORANGE); } } } Show_configurations() method prepares us a list of network configurations and keep information such as SSID, status of the Wi-Fi and priority in a String Builder. private String Show_configurations(){ List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks(); StringBuilder sb = new StringBuilder(); sb.append("\n"); for(WifiConfiguration conf : configurations){ sb.append("\n SSID: ").append(conf.SSID).append(", priority: ").append(conf.priority).append(", status: ").append(conf.status); } return sb.toString(); }
104 The Database The database of Android is used in order to store solicited and required information of an application even if the user kills the application or shut it down. A database in a mobile device is very useful as a supplement to the online world. We can have quick access to the database of an application without need of Internet connectivity. So we will use a database as a cache. So in this part, we need to create a database and table then use it inside of application to store our status, actions and locations and update them. About SQLite SQLite as an open source database is using for a long time for projects. In addition, it is popular to apply for many small devices. There are some reasons to consider about its merit to use for Android. First is its Zero-configuration database that makes it simple to use. Second is its independency from server and its set of libraries that provide database functionality. Third point is its open source property and can be adopted with Android’s framework easily. And at least is single-file database that provides us security straightforward. MySQLiteHelper Android provides an elegant interface for applications to interact with a SQLite database. To access the database, we need a helper class that provides a “connection” to the database, creating the connection if it doesn’t already exist. This class, provided by the Android framework, is called SQLiteOpenHelper. The database class it returns is an instance of SQLiteDatabase.
105 The Database Schema and Its Creation First of all, the content’s database table is created to show the schema of the database. For this project, database is building to store and retrieve types of connection, locations of the user and his activities As it is shown in the following table. Table name: Connection Fields (columns) Data type Key Id INTEGER Primary Key Connection type TEXT Location TEXT Activity TEXT Each row has a unique ID in the table, and it will contain data from connections. In all database we need a primary key, so SQLite like most databases, allows us to declare the ID as a primary key and even assigns a unique number automatically to each query. To build this table, an Object model of connection.java is created. That has two methods of setting and getting for each cell of the table. public Connection(String connection, String location, String action) { super(); this.connection = connection; this.location = location; this.action = action; } In the other hand, the schema of database has to be established when the application starts, so should be created on onCreate() method of MySQLiteHelper. After creating the schema we need onUpgrade() method for calling to alter the schema.
112 Session 4 In this session, the project is run to see how it works. This test is done during a walking and running from UPC to Collblanc station in 03/09/2015. Test of Project
113
114
115
116 Session 5 Conclusion This study attempts to develop an android tool to recognize the connection type of the device, location of the user and specifically to identify the user’s activity. Therefore, in this project, I have proposed an activity recognition tool of android devices which could be used as a part for other android applications which are based on location services and activity recognition. The hypothesis is to recognize five user’s activities such as Standing, Walking, Running, Bicycling and Driving. I based my project on the idea of using user’s location instead of using device’s embedded sensors such as accelerator. In order to achieve this goal the movement speed of user is in consideration. So the system diagnoses the device/user's latitude and longitude location every 20 seconds, then by utilizing haversine formula calculates the user’s distance difference in this period. Analyzing the output data of application demonstrated that 3 major activities including standing, walking and driving could be detect and distinguish accurately because of the difference between their rates while recognition of bicycling and running has less accuracy since they have similar rates. Future work may consider implementing a service for users, to assure that automatic downloads or updates start to work when the device is connected to Wi- Fi. When it is connected to the GSM, any downloads and updates will be interrupted temporarily and the new frequency alters the program or postpones it based on the available bandwidth. The high prices of mobile data in comparison to Wi-Fi connection could be a proper reason for the above, therefore for downloading and upgrading substantial size of data, Wi-Fi connection is should be required. As a future work, we will also implement a user’s track saver to know the user’s regular track of a day.
117 Bibliography 1 - Professional Android 4 Application Development – Reto Meier - www.itebooks.info 2 - https://developer.android.com/training/index.html 3 – Learning Android – Marko Gargenta – O’reilly 4 – Android Programming Tutorials - Mark L. Murphy 5 - TUTORIALS POINT Simply Easy Learning 6 - Fall Detection based on movement and smart Phone Technology, Vo Quang Viet, Gueesang Lee. 7 - ACTIVITY RECOGNITION USING K-NEAREST NEIGHBOR ALGORITHM ON SMARTPHONE WITH TRI-AXIAL ACCELEROMETER Sahak Kaghyan, Hakob Sarukhanyan. 8 - Implementation of Location based Services in Android using GPS and Web Services - Manav Singhal1, Anupam Shukla - ABV-Indian Institute of Information Technology and Management - Gwalior, India. 9 - “Location Based Services on Mobile in India - For IAMAI - Version: 14 April 2008 http://www.iamai.in/Upload/policy/LBS_Draft_Indicus.pdf” 10 - [THE MOBILE USE OF THE INTERNET BY INDIVIDUALS AND ENTERPRISES] 11- Implementation of Location based Services in Android using GPS and Web Services - Manav Singhal1, Anupam Shukla2 - 1ABV-Indian Institute of Information Technology and Management, Gwalior, India - 2ABV-Indian Institute of Information Technology and Management Gwalior, India 12 – “Online Human Activity Recognition on Smart Phones” - Mustafa Kose, Ozlem Durmaz Incel, Cem Ersoy - Bogazici University, Istanbul, Turkey
118 13 – “Location Based Services using Android Mobile Operating System” - Amit Kushwaha1, Vineet Kushwaha - Department of Electronics & Communication Engineering - IIMT Engineering College, Meerut-250001, India