DESIGN AND IMPLEMENTATION OF AN ANDROID MOBILE PHONE TRACKING APPLICATION A Project Presented to the faculty of the Department of Computer Science California State University, Sacramento Submitted in partial satisfaction of the requirements for the degree of MASTER OF SCIENCE in Computer Science by Sagar Zanwar FALL 2012 © 2012 Sagar Zanwar ALL RIGHTS RESERVED ii DESIGN AND IMPLEMENTATION OF AN ANDROID MOBILE PHONE TRACKING APPLICATION A Project by Sagar Zanwar Approved by: __________________________________, Committee Chair Du Zhang, Ph.D. __________________________________, Second Reader Bob Buckley, M.S. ____________________________ Date iii Student: Sagar Zanwar I certify that this student has met the requirements for format contained in the University format manual, and that this project is suitable for shelving in the Library and credit is to be awarded for the project. __________________________, Graduate Coordinator Nikrouz Faroughi, Ph.D. Department of Computer Science iv ___________________ Date Abstract of DESIGN AND IMPLEMENTATION OF AN ANDROID MOBILE PHONE TRACKING APPLICATION by Sagar Zanwar The goal of the Masters project is to develop an application, mainly designed for tracking the lost mobile phone. It is embedded with several tracking features, which will help tracking the lost phone. All the features work on SMS (short text message) basis. So, incoming SMS format plays a vital role. Application on the current platform Mobile Defense is a related app, which uses GPS to track the lost phone of the device or uses the cell tower data to send the coordinates. However, it does not take pictures of the user with inbuilt camera present on the device to track the user with picture and lacks SMS feature, which will be implemented in the current project. Similarly on IOS (iphone OS) an application called Find My iphone which only provides the Location of the device. Android application running in the cell monitors all the incoming messages. If the SMS is meant for the application, it reads the same and performs the expected task. The v application auto starts every time you boot your cell, goes to running mode and continuously listens for the incoming SMS messages. Whenever there is a new incoming SMS, it checks the content of the message and does the certain designed features in the application. Show Me where you are Unknown SIM Identifier Show Me the Picture Call Monitoring Tool Profile management This Master’s project demonstrates added advantage of SMS features, from which user can track the phone. SMS are easy to use and has no dependency on cellular data. In comparison to related application on Android and IOS, the designed application can give the GPS location by sending the SMS, taking the picture and can still work on changing the SIM card. _______________________, Committee Chair Du Zhang, Ph.D. _______________________ Date vi DEDICATION To my Parents vii ACKNOWLEDGEMENTS While working on this project many people have helped me achieve my goal. I would like to thank Dr. Du Zhang , for investing his invaluable time reviewing this project. Without his support it would have been difficult for me to complete this project. I would also like to thank Professor Bob Buckley for giving me his time and input as second reader. I would like to thank my family and Friends, for their undying love and support. In addition, I would like to thank all my professors, who taught me. Without their assistance and guidance, my Master’s degree would not have been completed successfully. viii TABLE OF CONTENTS Page Dedication .................................................................................................................. vii Acknowledgements ................................................................................................... viii List of Figures .............................................................................................................. xi Chapter 1. INTRODUCTION …..………………………………………………………….. 1 1.1 Problem Statement ...................................................................................... 4 1.2 Solution ...................................................................................................... 4 1.3 Project Objectives ....................................................................................... 5 1.4 Report Organization.................................................................................... 7 2. BACKGROUND .................................................................................................... 9 2.1 Related Work .............................................................................................. 9 3. DESIGN AND IMPLEMENTATION ................................................................. 11 3.1 Functional Overview ................................................................................. 11 3.2 User Roles ................................................................................................. 12 3.3 Software Structure of the Application ...................................................... 14 3.3.1 Manifest ..................................................................................... 14 3.3.2 Main Service ............................................................................. 14 3.3.3 SMS Receiver ............................................................................ 15 3.3.4 Camera Service .......................................................................... 15 3.4 Data Flow Diagram ................................................................................... 16 3.5 Implementation Details ............................................................................. 19 3.5.1 Profile Changing ........................................................................ 21 3.5.2 Call Registry .............................................................................. 22 3.5.3 Insert New SIM Card ................................................................. 23 3.5.4 GPS Value-Single and Continuous ............................................ 24 ix 3.5.5 Snapshot Transfer to E-Mail Address ........................................ 25 3.6 JDK 1.6 ..................................................................................................... 26 3.7 Eclipse SDK 1.6.2 ..................................................................................... 28 3.8 Eclipse SDK Features ............................................................................... 28 3.9 Android SDK 2.2 …………………………….……………….………… 29 3.10 Android Services .................................................................................... 31 4. RESULTS ..............................................................................................................33 4.1 Profile Change ..........................................................................................33 4.2 Call Tracking ............................................................................................34 4.3 SIM Change ..............................................................................................35 4.4 Single Tracking Location .........................................................................36 4.5 Advantages and Disadvantages .................................................................38 4.6 Comparison ..............................................................................................39 5. CONCLUSION ......................................................................................................41 5.1 Conclusion ...............................................................................................41 5.2 Future Work .............................................................................................42 Appendix Source Code ...............................................................................................43 Bibliography ...............................................................................................................77 x LIST OF FIGURES Figures Page 1 Data Flow ...................................................................................................................... 16 2 Flow Chart ...................................................................................................................... 17 3 Flow Chart Continued .................................................................................................... 18 4 Flow Diagram of Application ........................................................................................ 20 5 Silent Mode .................................................................................................................... 33 6 Ring and Vibrate Mode .................................................................................................. 33 7 Call Tracking .................................................................................................................. 34 8 SIM Changed .................................................................................................................. 35 9 Single Tracking Location ................................................................................................ 36 10 Continuous Tracking ...................................................................................................... 37 xi 1 Chapter 1 INTRODUCTION Today mobile communication devices are becoming much more technologically advanced and offer more features than just conversation. In cell phone, global positioning system (GPS) tracking is one of those advances. Tracking devices can be used to drive a car through traffic day-to-day or vehicle fleet tracking. Not only can a driver use an auto GPS system for directions, but also the corporate office knows where each vehicle is. In fact, all businesses are under pressure to monitor their shipments in order to enhance security and efficiency. GPS Systems can be used while outdoors for activities such as hiking or camping. As GPS technology has become more important and accessible to consumers, the varieties of GPS enabled devices have also increased at an incredible rate. At the time that the technology gets more advanced, even smaller and more versatile, handheld portable GPS devices are becoming increasingly popular like mobile phones. The popularity of mobile devices is significantly higher among the youngest individuals. Usually, mobile devices like mobile phones or portable digital displays (PDAs) are equipped with global positioning system (GPS) receptors that allow us to get the device geographic position in real time. One more feature in the existing system is intimation of SIM card replacement by extracting IMEI of device for tracking purpose. Mobile phone 2 tracking is a useful mobile application if it contains several features, which aims at the user's security. Such tracking systems are now present in the latest cell phones that are available in the market. They are usually known as smart phones. These smart phones use different Operating systems like Android, Palm, Windows and Blackberry to name a few. Canalys listed android as the best-selling smart phone platform worldwide in Q4 2010 with over 300 million Android devices in use by February 2012 [1]. According to Google's Andy Rubin, as of February 2012 there are over 850,000 Android devices activated every day [2]. Android is a Linux based OS for mobile devices such as smart phones and tablet computers. The Open Handset Alliance led by Google develops it. Google purchased the initial developer of the software, Android Inc., in 2005. The Android Open Source Project (AOSP) is tasked with the maintenance and further development of Android.[3] Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack. Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language [3]. 3 The API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform. Android platform provides a framework API that applications can use to interact with the underlying Android system. The framework API consists of [4] A core set of packages and classes A set of XML elements and attributes for declaring a manifest file A set of XML elements and attributes for declaring and accessing resources. A set of permissions that application can request are like camera usage, GPS, WIFI or data. A permission enforcements mechanism is also included in the system Each successive version of the Android platform can include updates to the Android application framework API that it delivers. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format, which is optimized, for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool. The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management [3]. 4 Android has a large community of developers writing applications ("apps") that extend the functionality of the devices. Developers write primarily in a customized version of Java. Apps can be downloaded from third-party sites or through online stores such as Google Play (formerly Android Market), the app store run by Google. 1.1 Problem Statement The use of mobile devices / cell phones has become part of our daily routine. Today mobile communication devices are becoming much more technologically advanced and offer more features than just conversation. Specially, the introduction of Android smart phones has brought a new revolution in the cell-phone market. In this routine usage, almost everyone has an experience of misplacing or losing his or her cell phone. As Android smart phones are latest in the market, it is expensive to lose one. Hence, a builtin application in the smart phone is very much necessary so that the lost cell can be retrieved. 1.2 Solution It is essential to have a powerful and efficient way for people to recover their Android smart phones once they have lost it. Usually, mobile devices like mobile phones or portable digital displays (PDAs) are equipped with global positioning system (GPS) receptors that allow us to get the device geographic position in real time along with the 5 feature of extracting the information of the cell phone through IMEI number even if the SIM card is being replaced. However, by just enabling the cell phones with GPS system and retrieving the information about the new SIM would be insufficient to track the smart-phone. Hence, came the idea of developing LOST ANDROID MOBILE PHONE TRACKER (LAMPt), an efficient & unique application with a few more features which help in controlling the lost Android smart phone & retrieving it back. This application uses location-based services (LBs) like GPS & global system for mobile (GSM) network to track a mobile device. The application is filled with features like Profile change, Call registry, Intimation of SIM replacement, GPS value-single & GPS value-continues and transfer of snapshots to e-mail address. All the features work on SMS basis. Therefore, incoming SMS format plays a vital role. Our android application running in the smart phone monitors all the incoming messages. If the SMS is meant for the application, it reads the same and performs the expected task. 1.3 Project Objectives SIM replacement: Immediately after the SIM replacement, we are notified about our device IMEI number, details of the new SIM inserted along with the cell info / GPS data. 6 User is expected to hard code a mobile number in the application. This could be your alternative number / the most preferred number to which the information of the lost cell phone has to be sent. Profile change: Say, the GPS data shows our cell very much at home, but, we are unable to trace it as it is in silent mode as you had put in silent mode before going to bed. Else, say the person who flicked your cell is still around and has put it in silent mode keeping his fingers crossed. You can easily convert the profile of the cell from general to silent and silent to general as per your requirement by just sending an SMS to predefined number. Call-Registry: All call registry details like incoming, outgoing calls are tracked by our cell. It records the incoming and outgoing names (if known to address book) and numbers or just number (if not known to the address book) and sends the information in the form of an SMS. Thus, we get to know with whom our cell phone thief has close acquaintance; we can call them in turn to know more about the theft. GPS value-Single: Get to know the GPS value and exact location of the lost phone. This data/value is sent only once from the lost phone. 7 GPS value-continuous: Fetch the GPS values every time the current GPS data is different from the previous one. Then the update is sent to the requested phone number. GPS value is sent after a fixed interval of time and distance. Transfer of snap shots to the e-mail address: Another dynamic feature of the application is transfer of image snapshots. You can activate the front camera, back camera of your cell by just sending an SMS. The application reads the incoming SMS, activates the camera, captures image, sends the series of image snapshots to the e-mail address pre-coded. These images can be further used to get more information about the location of the lost phone. Here we assume the SIM card is data enabled. Automatic deletion of Track-messages: Our application deletes the incoming and outgoing messages pertaining to the application such that the new owner of the cell is clueless about it all. 1.4 Report Organization This project report is organized into five chapters. First chapter deals with the introduction of the project, the problem statement and its solution and objective of the project. Second chapter deals with the background overview. Third chapter deals with the project description, services, dataflow diagrams and flowcharts of the project. In addition, the discussion of implementation details like coding, programming techniques in our project. Fourth chapter is presented with the 8 snapshots and outputs of our project for the different inputs. Finally, fifth chapter it is about the conclusion and the scope of the future work of our project. 9 Chapter 2 BACKGROUND 2.1 Related Work Mobile Defense [5] is an app on android platform, which uses GPS to track the lost phone or the device and uses the cell tower data to send the coordinates. The application sends the coordinates, but does not track continuously if the user changes the location, you need to get manually new location. It could be useful when the user is moving to a different location constantly. The application provides an alarm feature to find the phone if it is nearby you, by hearing the loud sound. However, it does not take pictures of the user with in built camera present on the device to track the user with picture. Find my iPhone [6 ](also known as "Find my iPhone") is an app and service provided by Apple Inc. that allows remote location-tracking of iOS devices. The service is currently available for iOS 5 or later through iCloud. Although it is not bundled with the operating system itself, the app is available for download from the App Store free of charge for iOS devices running iOS 5.0 or later. Find My iPhone allows users to locate their iOS devices using either the iOS app or icloud.com. Other feature includes: Play sound – Makes the device play a sound, even if it is muted. This feature can be used if the device has been accidentally misplaced. 10 Lost Mode (iOS 6 or later) – Flags the device as lost or stolen, allowing the user to lock it with a passcode. If the device is an iPhone and someone finds the device, he/she can call the user directly on the device. Erase iPhone – Completely erases all content and settings. This is useful if the device contains sensitive information, but the device cannot be located after this action is performed. 11 Chapter 3 DESIGN AND IMPLEMENTATION 3.1 Functional Overview Once the application is installed on Android phone, restart the device. Application starts at the boot time automatically and runs in the hidden mode. If the SIM is flipped, an SMS will be sent to the alterative numbers, which are hardcoded in the Android application. Assume your Android smart phone has been stolen then you can track the Android smart phone by sending SMS from any cell phone and get required updates as SMS like all the incoming and outgoing call details along with contact names from the contact list (if saved in the receiving phone) and number, location of the lost Android smart phone once and repeatedly as and when the location changes, change the profile from silent to ringing and vibrate mode and ringing and vibrate to silent mode, stop receiving the updates of the location, capture the image snapshot from the android cell phone and attach and send them as a mail to the email-id which is hard coded in the Android application. 12 3.2 User Roles The role of user in this project is to send SMSs to the lost Android smart phone having application installed with GPS and GPRS enabled. Here we assume the lost phone with installed application on Android phone is called as “phone L” and the phone used for sending SMS is named as “phone-M” The syntax of the SMSs that can be sent by the user and its functionalities are as follows TRACK-InOut-phone number: This command helps in monitoring all the incoming and outgoing calls on phone Land sends as an SMS (Name & contact no) to the phone number which requested this operation. TRACK-profile-RingAndVib@phonenumber: it changes the Phone L profile to ringing, vibrate mode, and acknowledges the same to the phone number, which requested this action (phone M). TRACK-profile-silent@phone number: It changes the Android smart phone's (phone L)profile to silent mode and acknowledges the same to the phone number, which requested this action(phone M). 13 TRACK-single-phone number: This helps in fetching the location of the lost Android smart phone (phone L) and sends an SMS location to the phone number, which requested this operation only once. TRACK-continuous-phone number: This helps in fetching the location of the (phone L) lost Android smart phone and sends an SMS location to the phone number which requested this action as and when the location changes of Phone L , it will keep track of it and sends the new location of the device to requested phone M. TRACK-stop: This command is issued after the TRACK-continuous command to stop sending the location of Phone L to phone M as an SMS to the requested number. TRACK-mail-phone number: This helps in activating the front camera (if not available back camera) on Phone L (lost phone), captures three continuous image snapshots and mails it to the email id which is hardcoded in the application. 14 3.3 Software Structure of the Application 3.3.1 Manifest In an Android project, a manifest file is created in the beginning. Every application must have an Android Manifest .xml file (with precisely that name) in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code. Manifest file takes the permission of the usage of Data, Wi-Fi, camera, GPS Bluetooth to name few services from the android system. 3.3.2 Main Service At the start of application, Main service will fetch the IMEI of the device and the IMSI number of the SIM card. Whenever the SIM card is changed, it will fetch the IMSI number again to verify to the previous stored number IMSI. if they both differ , then application will send an SMS from Lost phone to the hard-coded number. Other functionality of Main service includes the service of changing the profile modes of the lost phone from silent to ring and vibrate or vice versa. Call tracking on lost phone of incoming and outgoing calls is traced by main service. 15 3.3.3 SMS Receiver This is a receiver, which extends the communication from Broadcast Receiver. It reads the incoming message on the lost phone and if the message is intended for the app, then it redirects to respective java files in the project, for execution of functionality needed. SMS receiver calls the Single location file and continuous location to fetch the GPS latitude and longitude. 3.3.4 Camera Service This service initiates the front camera and captures a series of image snapshots on a basis of fixed interval. The images are stored on the memory card, the path is created by triggering the “Auto Capture “file. Once the images are saved, the “SMTP Authenticator” authenticates the Username and password of the email ID which is hard coded , from which the images snapshot are attached to the email and sent to the User preferred email id . 16 3.4 Data Flow Diagram Figure 1: Data Flow 17 Figure 2: Flow Chart 18 Figure 3: Flow Chart Continued 19 3.5 Implementation Details A few interesting features are implemented in this application which makes it different from the other existing tracking systems. This application always runs in the background and monitors all the incoming messages. If the SMS is meant for the application, it reads the same and performs the expected task. We have implemented following features: • Profile changing • Call registry • Insert new SIM card • GPS location -single & continuous • Transfer of snapshots to e-mail address 20 Figure 4 : Flow Diagram of Application 21 3.5.1 Profile Changing Just by sending an SMS from any of the mobile phone to the lost android smart phone, we change the profile of the android phone from general to silent mode or from silent to general mode. We use following syntax /text format to activate this feature, TRACK-profileRingAndVib@phone number (from silent to ring & vibrate) TRACK-profilesilent@phone number (from ring & vibrate to silent mode) // Default number used public static String call_alert_no=""; public String response_phno="", current_cell_id="", standard_cell_id="", ph_imei="", ph_imsi="", initialization_flag="false", alert_nos[]={"9163966583","9163966583"}; // Code Snippet for Profile Changing if(token.trim().equals("profile")) if(mode.trim().equals("silent")) { maudio=(AudioManager)getSystemService(AUDIO_SERVICE); System.out.println("...C...Profile silent"); maudio.setRingerMode(AudioManager.RINGER_MODE_SILENT); maudio=null; sendSMS(response_phno, "Profile Changed To Silent Mode"); // Code snippet for finding the IMEI of the device and IMSI of the SIM card 22 public void FindIMEI_IMSI() { TelephonyManager TelephonyManager)getSystemService(TELEPHONY_SERVICE); String p_imei = manager.getDeviceId(); String p_imsi = manager.getSubscriberId(); if(p_imei!=null && p_imei.length()==15 ){ ph_imei=p_imei; //txt_lat.setText(ph_imei); ph_imsi=p_imsi; // txt_lon.setText(ph_imsi); 3.5.2 Call Registry This feature helps us to give the information about the incoming and outgoing calls on the lost phone Anytime smart phone is lost, by using the command we can track the calls on the Lost phone. And it captures the phone number listed in outgoing and incoming call registry and sends an SMS with the information to the number requested. We use following syntax /text format to activate this feature, TRACK-INout-phone number The following code snippet does the functionality of tracking the incoming and outgoing calls and later composing the SMS as acknowledgment. public class TravelPhoneStateListener extends PhoneStateListener{ String callie_name; static MainService parent; AudioManager maudio; boolean priority_flag; 23 public TravelPhoneStateListener(MainService parent) { TravelPhoneStateListener.parent=parent; } // Code For incoming call case TelephonyManager.CALL_STATE_RINGING: System.out.println("I Am In CALL_STATE_RINGING"); if(MainService.call_alert_flag){ callie_name=getContactNameFromNumber(incoming_number); System.out.println("Callie : "+callie_name+" Number "+incoming_number); MainService.sendSMS(MainService.call_alert_no, "Their is an In-coming call From : "+callie_name+" "+incoming_number); } // Code to Get name from Contact List. public static String getContactNameFromNumber(String number) { ContentResolver cr = parent.getContentResolver(); Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); Cursor cursor= cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);//(uri, new String[]{PhoneLookup.DISPLAY_NAME} .....) 3.5.3 Insert New SIM Card This feature helps us to get the information about changed SIM card. When SIM card is replaced, the application will automatically send the IMEI number of lost cell, details of the new SIM inserted to the two phone alert numbers, which are pre-coded. 24 // Code for SIM changed if(!standard_cell_id.trim().equals(current_cell_id.trim())) { for(int i=0;i<alert_nos.length;i++) { sendSMS(alert_nos[i], "SIM changed. Note IMEI number => "+ph_imei); try{Thread.sleep(5000);}catch(Exception e){} } } 3.5.4 GPS Value-Single and Continuous This feature is used for fetching the location string. We retrieve the location string by sending one SMS to the lost smart phone in a particular format. The mobile will reply by sending the Location String. We can also retrieve the location string in 2 ways. One is single value, which gives GPS value only once. The other way is continuous, where various values of location can be obtained every pre-decided interval of time and displacement. We use following syntax /text format to activate this feature TRACK-single-phone number (for single GPS value) TRACK-continuous-phone number (for continues value) The following code snippet fetches the longitude and latitude using GPS and converts the coordinates into address using the GEO locater. 25 public class SingleLocation extends Service { private LocationManager locManager; private double LATITUDE; private double LONGITUDE; private Geocoder geocoder; Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { LATITUDE = (double) (location.getLatitude()); LONGITUDE = (double) (location.getLongitude()); String latlon=""+LATITUDE+" "+LONGITUDE; geocoder = new Geocoder(this, Locale.ENGLISH); try { List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, maxResult); 3.5.5 Snapshot Transfer to E-Mail Address We can activate the front camera/back camera of the lost smart phone by just sending an SMS. This feature reads the incoming SMS, activates the camera, captures image, and sends the series of snapshots to the pre-coded e-mail address. We need to view the photograph to check out whether we can extract more information about whom, how, where etc. We use following syntax /text format to activate this feature, TRACK-mail-phone number // Sending attachment 26 public class SendAttachment { //String from="checkstudent08@gmail.com"; String filename=null; //Properties mailinfo; String messageinfo; public SendAttachment(String email,String messageinfo,List<String> filePaths) { EMAIL_ID_TO=email; this.messageinfo=messageinfo; //Set the host smtp address Properties props = new Properties(); //file attachment for (String file : filePaths) { MimeBodyPart bp2=new MimeBodyPart(); DataSource atc=new FileDataSource(file); bp2.setDataHandler(new DataHandler(atc)); bp2.setFileName(file); mp.addBodyPart(bp2); } 3.6 JDK 1.6 Anyone who has existing Java applications will benefit immediately from the performance, reliability, and UI improvements in Java SE 6. Coupled with the expanded monitoring capacities built into the platform, the release delivers dramatic out-of-the-box benefits without any coding changes or even a re-compile necessary. Simply running existing Java applications on this latest release is all that is needed. 27 For developers, Java SE 6 streamlines web service and XML development, simplifies GUI development and augments native desktop support, expands programmatic access to native security facilities, and is the first release to offer a standardized framework for scripting languages. NetBeans IDE integrates with the release to further simplify the use of these and other new developer features in the release. Advantages to running applications on JDK 1.6 • Applications run faster on the desktop and servers. • New 'dynamic attach' diagnostics simplify troubleshooting. • Expanded Solaris DTrace support provides value on solaris. • Improved 'native' look and feel across Solaris, Linux, and Windows. Benefits in upgrading developer environments to JDK 1.6 • JavaScript integrated and included with the platform. • Scripting language framework extends support for Ruby, Python, and other languages. • Complete light-weight platform for web services, right out ofthe box. • Simplified GUI design and expanded native platform support. • Full JDBC$ implementation providing improved XML support for Databases. • Java DB included with the JDK, a free to use and deploy Java Database. • Full support by NetBeans IDE 5.5. • Sun Developers Services available to help build more robust application. 28 3.7 Eclipse SDK 1.6.2 Most of the Eclipse SDK is "pure" Java code and has no direct dependence on the underlying operating system. The chief dependence is therefore on the Java Platform itself Portions are targeted to specific classes of operating environments, requiring their source code to only reference facilities available in particular class libraries (e.g. J2ME Foundation 1.0, J2SE 1.3 and 1.4, etc.). In general, the 3.5 release of the Eclipse Project is developed on a mix of Java 1.4, Java 5 and Java 6 VMs. As such, the Eclipse SDK as a whole is targeted at all modern, desktop Java VMs. Full functionality is available for 1.4 level development everywhere, and extended development capabilities are made available on the VMs that support them. 3.8 Eclipse SDK Features Java Development Tooling (JDT) This feature adds Java editing capability to the platform. The implementation includes a fully-featured Java development environment and provides specialized features for handling, manipulating, compiling, executing and debugging Java code. It defines its own extension points that enable tool developers to use Java capability in their plug-ins. An example would be the ability to use the Java Model that defines the package, field and method definitions ofa Java project. 29 Plug-in Development Environment (PDE) This feature provides convenience for creating plug-ins, a task that is filled with repetitive and laborious actions. It greatly simplifies creation, manipulation, debugging and deployment of plug-ins by automating some of the processes involved as well as presenting plug-in information at a much higher level than its XML meta file. The meta file stores details about the plug-in properties such as the used extension points, external libraries, build configuration and deployment options. Manually editing this file would be error prone and tedious, thus using PDE is much preferred. The outlined architecture will be developed using the PDE, allowing it to be built within Eclipse itself. From version 3.0 onwards, PDE allows the launch of a separate workbench to test and debug the plug-in under development. The development code is seamlessly and automatically deployed into the new environment and can be used immediately. 3.9 Android SDK 2.2 Android software development is the process by which new applications are created for the Android operating system. Applications are usually developed in the Java programming language using the Android Software Development Kit, but other development tools are available. Android 2.2 is a minor platform release including user 30 features, developer features, API changes, and bug fixes. For information on developer features and API changes, see the Framework API section. For developers, the Android 2.2 platform is available as a downloadable component for the Android SDK. The downloadable platform includes a fully compliant Android library and system image, as well as a set of emulator skins, sample applications, and more. The downloadable platform includes no external libraries. To get started developing or testing against the Android 2.2 platform, use the Android SDK and A VD Manager tool to download the platform into your SDK. API Level The Android 2.2 platform delivers an updated version of the framework API. The Android 2.2 API is assigned an integer identifier that is stored in the system itself. This identifier, called the "API Level", allows the system to correctly determine whether an application is compatible with the system, prior to installing the application. The Android software development kit (SDK) includes a comprehensive set of development tools. These include a debugger, libraries, a handset emulator based on QEMU, documentation, sample code, and tutorials. Currently supported development platforms include computers running Linux (any modem desktop Linux distribution), Mac OS X 10.4.9 or later, Windows XP or later. 31 Enhancements to Android's SDK go hand in hand with the overall Android platform development. The SDK also supports older versions of the Android platform in case developers wish to target their applications at older devices. Development tools are downloadable components, so after one has downloaded the latest version and platform, older platforms and tools can also be downloaded for compatibility testing. Android applications are packaged in .apk format and stored under / data / app folder on the Android OS (the folder is accessible only to root user for security reasons). APK package contains .dex files (compiled byte code files called Dalvik executables), resource files, etc. 3.10 Android Services The main service that our project provides is using following android.content.pm.PackageManager: Class for retrieving various kinds of infonnation related to the application packages that are currently installed on the device android.app.Activity: An activity is a single, focused thing that the user can do android.location.Geocoder: A class for handling geocoding and reverse geocoding android.location.LocationListener: Used for receiving notifications from the LocationManager when the location has changed 32 android.location.Address: A class representing an Address, i.e., a set of Strings describing a location android.location.LocationManager: This class provides access to the system location services android.telephony.SmsManager: Manages SMS operations such as sending data, text, and SMS messages android.media.AudioManager: Manages SMS operations such as sending data, text, and SMS messages android.telephony.TelephonyManager: Provides access to information about the telephony services on the device 33 Chapter 4 RESULTS 4.1 Profile change Snapshot of the message received after the profile is changed from ringing & vibrate mode to silent Figure 5: Silent Mode Figure 6: Ring and Vibrate Mode 34 4.2 Call Tracking Snapshot of the message received after there was a out-going calls and In-coming calls observed in the lost smart phone Figure 7: Call Tracking 35 4.3 SIM Change Snapshot of the message received after there was an activity of SIM change observed in the lost smart Figure 8: SIM Changed 36 4.4 Single Tracking Location Format of text message to be sent to lost smart-phone to obtain the GPS value address from the lost smart phone. Figure 9: Single Tracking Location 37 Figure 10: Continuous Tracking 38 4.5 Advantages and Disadvantages Advantages The application is auto-started when the phone is switched on and the application runs in the listening mode always. so every time the phone is restated , application restarts without user input. The user cannot see the application running, runs in the hidden mode. Once the application is installed on the phone, the application enters into background mode and runs in task manager. The app is not listed under main menu of the phone app list. The application works even when the SIM card is changed. Even after inserting the new SIM card by the user, we will be still able to run all the features. The application deletes specific incoming and outgoing messages pertaining to the app. whenever the message is intended for the application, the application reads the message, does the required functionality and deletes the message from the inbox of the phone. Ease of use. Once the app is installed, the application automates to send and receive the message without the interception needed from the user. A complete package with intelligent features. Free of cost,as Android is open source software. 39 Disadvantages The application cannot work while the phone is off. If the user switches off the phone the messages cannot be reached to the application. It does not have remote access to the phone. We cannot control the phone remotely to lock down the phone. The application cannot delete the data remotely; the application cannot wipe the confidential data present on the local phone remotely by taking command from text message. 4.6 Comparison In comparison to the working of the Mobile defense and find my iphone. The app designed and implemented does much of the functionality on the SMS feature, whereas the related apps work on GPRS. SMS are much simpler to send from user perspective compared to usage of data on phone. Tracking of the lost phone on the related app is done using map GUI interface where it locates the lost phone on the map, but whereas on the designed application the phone is tracked using street address provided by GEO locater. Capture the sequence of images functionality designed in the application is not present in related application. Find my iphone only provides the location of the lost phone and does not provide any other functionality compared to both application .mobile defense 40 provides the tracking but lacks functionality like changing profile mode from silent to ring and vibrate and vice –versa. The main advantage of the designed application is working of the app even when the SIM card is changed. The designed application still runs in the background with all the functionality. 41 Chapter 5 CONCLUSION 5.1 Conclusion Lost android mobile phone tracker is a unique & efficient application, which is used to track the lost / misplaced android phone. All the features work on SMS basis. Therefore, incoming SMS format plays a vital role. Our android application running in the cell monitors all the incoming messages. If the SMS is meant for the application, it reads the same and performs the expected task. We have created features, which will enhance the existing cell tracking system. Application stands different from the existing system as its not only the GPS value it makes use of but it works on GSM/ text messaging services which makes application a simple & unique one. The highlighting features of our project: Profile change Call registry Intimation of SIM replacement GPS values Single value Continuous value Transfer of snapshots to the e-mail address 42 5.2 Future Work Presently the current project lost phone tracking is a powerful application but as it is said "no technology has an end, it grows every second", For future work the following features are to be added. To make the application work when the device is switched off. The other feature would be to implement the WIPE command, so we can delete all the data remotely by sending the data to the lost phone. The command will sent be using the text message, after receiving the message on the lost phone, the application can delete all the contents on the phone and memory card. 43 Appendix Source Code Main Service.Java package org.com.track; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.os.IBinder; import android.telephony.PhoneStateListener; import android.telephony.SmsManager; import android.telephony.TelephonyManager; import android.widget.TextView; import android.widget.Toast; public class MainService extends Service implements Runnable { TravelPhoneStateListener mPhoneListener; static TelephonyManager tm; //TextView txt_lat,txt_lon,txt_adr; public static String call_alert_no=""; public String response_phno="", current_cell_id="", standard_cell_id="", ph_imei="", ph_imsi="", initialization_flag="true", alert_nos[]={"9945783250", "7899118891"}; public boolean profile_ph=true; static boolean call_alert_flag; static SmsManager sms; AudioManager maudio; public IBinder onBind(Intent arg0) { return null; } public void onCreate() { 44 super.onCreate(); System.out.println("Inside oncreate MainService"); Toast.makeText(this, "Inside on create MainService", Toast.LENGTH_LONG).show(); } public void onStart(Intent intent, int startid) { System.out.println("Inside onstart MainService"); Toast.makeText(this, "Inside onStart MainService", Toast.LENGTH_LONG).show(); mPhoneListener = new TravelPhoneStateListener(MainService.this); MainService.tm = ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)); MainService.tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE); System.out.println("Inside Onstart MainService"); sms = SmsManager.getDefault(); Properties properties = new Properties(); try { properties.load(new FileInputStream("/sdcard/system_file.properties")); initialization_flag=properties.getProperty("initialization_flag"); }catch(Exception ex){ex.printStackTrace();} FindIMEI_IMSI(); if(initialization_flag.equals("false")) { try{ properties.setProperty("initialization_flag","true"); standard_cell_id=ph_imei+ph_imsi; properties.setProperty("standard_cell_identity",standard_cell_id); properties.store(new FileOutputStream("/sdcard/system_file.properties"),null); }catch(Exception ex){ex.printStackTrace();} } else { standard_cell_id=properties.getProperty("standard_cell_identity");; } current_cell_id=ph_imei+ph_imsi; System.out.println("standard_cell_identity : "+standard_cell_id); 45 System.out.println("current_cell_identity : "+current_cell_id); if(!standard_cell_id.trim().equals(current_cell_id.trim())) { for(int i=0;i<alert_nos.length;i++) { sendSMS(alert_nos[i], "SIM changed. Note IMEI number => "+ph_imei); try{Thread.sleep(5000);}catch(Exception e){} } } Thread th=new Thread(this); th.start(); System.out.println("After Thread Started"); } public void run() { System.out.println("Inside Run methode"); while(true) { if(SmsReceiver.flag) { String sms_received=SmsReceiver.msg; String token=sms_received.substring(sms_received.indexOf("")+1,sms_received.lastIndexOf("-")); if(token.trim().equals("INout")) { SmsReceiver.flag=false; profile_ph=false; SmsReceiver.msg=""; call_alert_no=sms_received.substring(sms_received.lastIndexOf("-")+1); call_alert_flag=true; } else if(token.trim().equals("profile")) { profile_ph=false; String mode=""; SmsReceiver.flag=false; SmsReceiver.msg=""; 46 mode=sms_received.substring(sms_received.lastIndexOf("")+1,sms_received.indexOf("@")); response_phno=sms_received.substring(sms_received.indexOf("@")+1); if(mode.trim().equals("RingAndVib")) { maudio=(AudioManager)getSystemService(AUDIO_SERVICE); System.out.println("...C...Profile ring-and-vib"); maudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL); maudio=null; sendSMS(response_phno, "Profile Changed To RingAndVibrate Mode"); } if(mode.trim().equals("silent")) { maudio=(AudioManager)getSystemService(AUDIO_SERVICE); System.out.println("...C...Profile silent"); maudio.setRingerMode(AudioManager.RINGER_MODE_SILENT); maudio=null; sendSMS(response_phno, "Profile Changed To Silent Mode"); } } else { if(profile_ph) { response_phno=sms_received.substring(sms_received.lastIndexOf("-")+1); SmsReceiver.flag=false; SmsReceiver.msg=""; sendSMS(response_phno,"Invalid Request"); } } SmsReceiver.flag=false; } } } public static void sendSMS(String phoneNumber, String message) { 47 System.out.println("Inside Send SMS phone No"+phoneNumber+"Message "+message); sms.sendTextMessage(phoneNumber, null, message, null, null); } public void FindIMEI_IMSI() { TelephonyManager manager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); String p_imei = manager.getDeviceId(); String p_imsi = manager.getSubscriberId(); if(p_imei!=null && p_imei.length()==15 ){ ph_imei=p_imei; //txt_lat.setText(ph_imei); ph_imsi=p_imsi; // txt_lon.setText(ph_imsi); }else{ ph_imei=p_imei; ph_imsi=p_imsi; } } } SingleLocation.Java package org.com.track; import java.io.IOException; import java.util.List; import java.util.Locale; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.location.Location; 48 import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.telephony.SmsManager; import android.widget.Toast; public class SingleLocation extends Service { private LocationManager locManager; private double LATITUDE; private double LONGITUDE; private Geocoder geocoder; final int maxResult =5; String addressList[] = new String[maxResult]; String option; private String response_no="9845375610"; String addr; public boolean flag=false; public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); System.out.println("Inside Single location"); Toast.makeText(this, "Inside oncreate Single", Toast.LENGTH_LONG).show(); } public void onStart(Intent intent, int startid) { System.out.println("Inside onstart Single"); Toast.makeText(this, "Inside on Start", Toast.LENGTH_LONG).show(); locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, locationListener); option=intent.getStringExtra("option"); option=option.trim(); response_no =intent.getStringExtra("phno"); try { Thread.sleep(5000); } catch (InterruptedException e1) { 49 e1.printStackTrace(); } Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { LATITUDE = (double) (location.getLatitude()); LONGITUDE = (double) (location.getLongitude()); String latlon=""+LATITUDE+" "+LONGITUDE; geocoder = new Geocoder(this, Locale.ENGLISH); try { List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, maxResult); if(addresses != null) { int j=0; Address returnedAddress=null; for (j=0; j<maxResult; j++){ returnedAddress = addresses.get(j); StringBuilder strReturnedAddress = new StringBuilder(); for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); } addressList[j] = strReturnedAddress.toString(); } addr="Latitude : "+LATITUDE+"\nLongitude : "+LONGITUDE+"\nAddress : "+addressList[0]; } } catch (IOException e) { e.printStackTrace(); } Toast.makeText(this, latlon, Toast.LENGTH_LONG).show(); sendSMS(response_no,addr); /*flag=false; break;*/ } else { sendSMS(response_no,"Location not Found..."); //locManager.removeUpdates(locationListener); } } 50 @Override public void onDestroy() { super.onDestroy(); locManager.removeUpdates(locationListener); Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show(); } 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) { } }; public static void sendSMS(String phoneNumber, String message) { System.out.println("Inside Send SMS phone No"+phoneNumber+"Message "+message); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, null, null); } } Continuous Location. Java package org.com.track; import java.io.IOException; import java.util.List; 51 import java.util.Locale; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.telephony.SmsManager; import android.widget.Toast; public class ContinousLocation extends Service{ private LocationManager locManager1; private double LATITUDE; private double LONGITUDE; private Geocoder geocoder; final int maxResult =5; String addressList[] = new String[maxResult]; String option; private String response_no="9845375610"; String addr; long prvtime; public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); Toast.makeText(this, "Inside on create Continous", Toast.LENGTH_LONG).show(); } public void onStart(Intent intent, int startid) { Toast.makeText(this, "Inside on Start Continuous", Toast.LENGTH_LONG).show(); locManager1 = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 52 locManager1.requestLocationUpdates(LocationManager.GPS_PROVIDER,60000, 5, locationListener); option=intent.getStringExtra("option"); option=option.trim(); response_no =intent.getStringExtra("phno"); geocoder = new Geocoder(this, Locale.ENGLISH); prvtime=0; } @Override public void onDestroy() { super.onDestroy(); locManager1.removeUpdates(locationListener); //Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show(); } private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { if (location != null) { LATITUDE = (double) (location.getLatitude()); LONGITUDE = (double) (location.getLongitude()); //geocoder = new Geocoder(this, Locale.ENGLISH); long newtime=System.currentTimeMillis(); if((prvtime==0) || (newtime-prvtime)>=60000) { String latlon=""+LATITUDE+" "+LONGITUDE; try { prvtime=newtime; List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, maxResult); if(addresses != null) { int j=0; Address returnedAddress=null; for (j=0; j<maxResult; j++){ returnedAddress = addresses.get(j); StringBuilder strReturnedAddress = new StringBuilder(); for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); } addressList[j] = strReturnedAddress.toString(); } 53 addr="Latitude : "+LATITUDE+"\nLongitude : "+LONGITUDE+"\nAddress : "+addressList[0]; } } catch (IOException e) { e.printStackTrace(); } Toast.makeText(ContinousLocation.this, latlon, Toast.LENGTH_LONG).show(); sendSMS(response_no,addr); } } } public void onProviderDisabled(String provider) { //updateWithNewLocation(null); } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { } }; public static void sendSMS(String phoneNumber, String message) { System.out.println("Inside Send SMS phone No"+phoneNumber+"Message "+message); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, null, null); } } MyReceiver.Java package org.com.track; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; 54 import android.os.Bundle; public class MyReceiver extends BroadcastReceiver{ public static String outnum; public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) { Bundle bundle = intent.getExtras(); if(bundle == null) return; String callie_name; outnum = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); System.out.println("Out Going Number : "+ outnum); if(MainService.call_alert_flag){ callie_name=TravelPhoneStateListener.getContactNameFromNumber(outnum); System.out.println("Callie : "+callie_name+" Number "+outnum); MainService.sendSMS(MainService.call_alert_no, "Their is an Out-going call To : "+callie_name+" - "+outnum); } } } } SMS Receiver.Java package org.com.track; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.telephony.TelephonyManager; import android.widget.TextView; import android.widget.Toast; 55 public class SmsReceiver extends BroadcastReceiver{ public static double latitude; public static double longitude; public static boolean flag=false; public static String msg; TravelPhoneStateListener mPhoneListener; static TelephonyManager tm; TextView txt_lat,txt_lon,txt_adr; public static String call_alert_no=""; public String current_cell_id="", standard_cell_id="", ph_imei="", ph_imsi="", initialization_flag="true", alert_nos[]={"9986850107", "9916593867"}; static String response_phno=""; public boolean profile_ph=true; static boolean call_alert_flag; static SmsManager sms; AudioManager maudio; Context ct; String str = ""; private Handler mHandler = new Handler(); public void onReceive(Context context, Intent intent) { //---get the SMS message passed in--Toast.makeText(context, "SMS RECEIVED", Toast.LENGTH_LONG).show(); Bundle bundle = intent.getExtras(); System.out.println("SMS RECEIVED"); flag=false; SmsMessage[] msgs = null; ct=context; if (bundle != null) { //---retrieve the SMS message received--Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; int i=msgs.length-1; msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); //1 str = msgs[i].getMessageBody().toString(); //2 System.out.println("SMS RECEIVED DATA=="+str); if(str.startsWith("TRACK")) { mHandler.postDelayed(new Runnable() { 56 public void run() { if(str.startsWith("TRACK")) { Uri deleteUri = Uri.parse("content://sms"); Cursor c = ct.getContentResolver().query(deleteUri, null, null, null, null); System.out.println("Message size : "+ c.getCount()); if (c.moveToFirst()) { try { // Delete the SMS String pid = c.getString(0); // Get id; String uri = "content://sms/" + pid; int count=ct.getContentResolver().delete(Uri.parse(uri), null, null); System.out.println("Delete count : "+count); } catch (Exception e) {} } } System.out.println("Here I Am - 2 "); } }, 7000); System.out.println("...1...Inside Receive SMS IF"); msg=str; System.out.println("...2...Finished Receive SMS IF"); String sms_received=SmsReceiver.msg; String token=sms_received.substring(sms_received.indexOf("")+1,sms_received.lastIndexOf("-")); System.out.println("...A...Token "+token); if(token.trim().equals("single")){ SmsReceiver.flag=false; SmsReceiver.msg=""; System.out.println("...3...Inside equals(..single..)"); response_phno=sms_received.substring(sms_received.lastIndexOf("-")+1); System.out.println("...B...Phone NO "+response_phno); System.out.println("...4...Calling Intent kir"); Intent kir = new Intent(context, SingleLocation.class); kir.putExtra("option", "single"); kir.putExtra("phno", response_phno); kir.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startService(kir); //context.startActivity(kir); 57 //abortBroadcast(); System.out.println("...5...Finished With Intent kir"); }else if(token.trim().equals("continuous")){ SmsReceiver.flag=false; SmsReceiver.msg=""; System.out.println("...3...Inside equals(..Continuous..)"); response_phno=sms_received.substring(sms_received.lastIndexOf("-")+1); System.out.println("...C...Phone NO "+response_phno); System.out.println("...4...Calling Intent kir Continuous"); Intent kir = new Intent(context, ContinousLocation.class); kir.putExtra("option","continuous"); kir.putExtra("phno", response_phno); context.startService(kir); System.out.println("...5...Finished With Intent kir Continuous"); }else if(token.trim().equals("mail")){ SmsReceiver.flag=false; SmsReceiver.msg=""; System.out.println("...5...Inside equals(..pic..)"); response_phno=sms_received.substring(sms_received.lastIndexOf("")+1); System.out.println("...F...Phone NO "+response_phno); /*Intent pt=new Intent(context, AutoCaptutreATY.class); pt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(pt); abortBroadcast(); */ Intent kir = new Intent(context, CameraService.class); context.startService(kir); System.out.println("...6...Picture Activated"); } else if(token.trim().equals("stop")) { SmsReceiver.flag=false; SmsReceiver.msg=""; Intent kir = new Intent(context, ContinousLocation.class); kir.putExtra("option","continuous"); kir.putExtra("phno", response_phno); context.stopService(kir); } else { flag=true; } } 58 } } } Travel Phone Listener. Java package org.com.track; import android.content.ContentResolver; import android.database.Cursor; import android.media.AudioManager; import android.net.Uri; import android.provider.ContactsContract.PhoneLookup; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; public class TravelPhoneStateListener extends PhoneStateListener{ String callie_name; static MainService parent; AudioManager maudio; boolean priority_flag; public TravelPhoneStateListener(MainService parent) { TravelPhoneStateListener.parent=parent; } @Override public void onCallStateChanged(int state, String incoming_number) { System.out.println("switch : " +state); // boolean ringing=false, offhook=false; switch (state) { case TelephonyManager.CALL_STATE_OFFHOOK: System.out.println("I Am In CALL_STATE_OFFHOOK"); //callie_name=getContactNameFromNumber(incoming_number); //System.out.println("Callie : "+callie_name+" Number "+incoming_number); 59 //offhook=true; break; case TelephonyManager.CALL_STATE_RINGING: System.out.println("I Am In CALL_STATE_RINGING"); if(MainService.call_alert_flag){ callie_name=getContactNameFromNumber(incoming_number); System.out.println("Callie : "+callie_name+" Number "+incoming_number); MainService.sendSMS(MainService.call_alert_no, "Their is an In-coming call From : "+callie_name+" "+incoming_number); } //ringing=true; break; case TelephonyManager.CALL_STATE_IDLE: System.out.println("I Am In CALL_STATE_IDLE"); //callie_name=getContactNameFromNumber(incoming_number); //System.out.println("Callie : "+callie_name+" Number "+incoming_number); break; } } public static String getContactNameFromNumber(String number) { ContentResolver cr = parent.getContentResolver(); Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); Cursor cursor= cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);//(uri, new String[]{PhoneLookup.DISPLAY_NAME} .....) System.out.println("Cursor cursor : "+cursor); if (cursor.moveToFirst()) { System.out.println("Cursor Has Recordes"); do{ String name =cursor.getString(0); cursor.close(); return name; }while (cursor.moveToNext()); } cursor.close(); 60 return "New Nmber"; } } LostCellTrack.Java package org.com.track; import android.app.Activity; import android.os.Bundle; public class LostCellTrackActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } AutoCapture.Java package org.com.track; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import android.app.Activity; 61 import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Bitmap.CompressFormat; import android.hardware.Camera; import android.os.Bundle; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; public class AutoCaptutreATY extends Activity { public SurfaceHolder mHolder; private Preview mPreview; Camera mCamera; Context mContext; int count=0; String TAG="CAMERA"; ArrayList<String> path; static PackageManager pm = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.auto_cap); /*pm = getApplicationContext().getPackageManager(); pm.setComponentEnabledSetting(getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); */ try{startImageCapture();}catch(Exception e){} } public void startImageCapture() { mPreview = new Preview(this); setContentView(mPreview); } class Preview extends SurfaceView implements SurfaceHolder.Callback,Runnable { Context context; 62 boolean mPreviewRunning = false; public Preview(Context context) { super(context); this.context=context; mHolder=getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public Surface getSurface() { return mHolder.getSurface(); } public void surfaceCreated(SurfaceHolder holder) { Log.e("TAG", "surfaceCreated"); if(mCamera==null){ mCamera = OpenFrontFacingCamera(); } } public void surfaceDestroyed(SurfaceHolder holder) { mCamera.stopPreview(); mPreviewRunning = false; mCamera.release(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (mPreviewRunning) {mCamera.stopPreview();} try { mCamera.setPreviewDisplay(holder); } catch (IOException e) {e.printStackTrace();} mCamera.startPreview(); mPreviewRunning = true; capture(); } public void capture() 63 { Log.v("Inside while true","Inside while true"); try { Thread t1=new Thread(this); t1.start(); } catch(Exception e){Log.v("Error is this:",e.toString());} } public void run() { try{ Thread.sleep(3000); for(int i=0;i<3;i++){ Log.v("Inside Run","--Inside Run--"); mCamera.takePicture(null, mPictureCallback, mPictureCallback); Thread.sleep(5000); } // mCamera.stopPreview(); path=new ArrayList<String> (); path.add("/sdcard/image1.jpg"); path.add("/sdcard/image2.jpg"); path.add("/sdcard/image3.jpg"); new SendAttachment("checkstudent11@gmail.com","Adndroid programe with Attachment",path); DeleteImage(); //MainService.sendSMS(SmsReceiver.response_phno, "Mail sent Succesfully"); /* pm = getApplicationContext().getPackageManager(); pm.setComponentEnabledSetting(getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); */ finish(); }catch(Exception e){Log.v("-------------",e.toString());} } } Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() { public void onPictureTaken(byte[] imageData, Camera c) { if (imageData != null) { Log.v("OLD preview","OLD preview"); StoreByteImage(mContext, imageData, 20, "ImageName"); 64 mCamera.startPreview(); } } }; public boolean StoreByteImage(Context mContext, byte[] imageData, int quality, String expName) { count++; File sdImageMainDirectory = new File("/sdcard/image"+count+".jpg"); FileOutputStream fileOutputStream = null; try { BitmapFactory.Options options=new BitmapFactory.Options(); options.inSampleSize = 5; Bitmap bm = BitmapFactory.decodeByteArray(imageData, 0, imageData.length,options); if(sdImageMainDirectory.exists()) { sdImageMainDirectory.delete(); fileOutputStream = new FileOutputStream(sdImageMainDirectory); }else if(!sdImageMainDirectory.exists()){ fileOutputStream = new FileOutputStream(sdImageMainDirectory); } BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream); bm.compress(CompressFormat.JPEG, quality, bos); bos.flush(); bos.close(); } catch (Exception e) {e.printStackTrace();} return true; } private Camera OpenFrontFacingCamera() { Camera camera = null; // Look for front-facing camera, using the Gingerbread API. // Java reflection is used for backwards compatibility with pre-Gingerbread APIs. try { Class<?> cameraClass = Class.forName("android.hardware.Camera"); Object cameraInfo = null; Field field = null; int cameraCount = 0; 65 Method getNumberOfCamerasMethod = cameraClass.getMethod( "getNumberOfCameras" ); if ( getNumberOfCamerasMethod != null ) { cameraCount = (Integer) getNumberOfCamerasMethod.invoke( null, (Object[]) null ); } Class<?> cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo"); if ( cameraInfoClass != null ) { cameraInfo = cameraInfoClass.newInstance(); } if ( cameraInfo != null ) { field = cameraInfo.getClass().getField( "facing" ); } Method getCameraInfoMethod = cameraClass.getMethod( "getCameraInfo", Integer.TYPE, cameraInfoClass ); if ( getCameraInfoMethod != null && cameraInfoClass != null && field != null ) { for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) { getCameraInfoMethod.invoke( null, camIdx, cameraInfo ); int facing = field.getInt( cameraInfo ); if ( facing == 1 ) { // Camera.CameraInfo.CAMERA_FACING_FRONT try { Method cameraOpenMethod = cameraClass.getMethod( "open", Integer.TYPE ); if ( cameraOpenMethod != null ) { camera = (Camera) cameraOpenMethod.invoke( null, camIdx ); } } catch (RuntimeException e) { Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage()); } } } } } // Ignore the bevy of checked exceptions the Java Reflection API throws - if it fails, who cares. catch ( ClassNotFoundException e ) {Log.e(TAG, "ClassNotFoundException" + e.getLocalizedMessage());} catch ( NoSuchMethodException e ) {Log.e(TAG, "NoSuchMethodException" + e.getLocalizedMessage());} catch ( NoSuchFieldException e ) {Log.e(TAG, "NoSuchFieldException" + e.getLocalizedMessage());} catch ( IllegalAccessException e ) {Log.e(TAG, "IllegalAccessException" + e.getLocalizedMessage());} 66 catch ( InvocationTargetException e ) {Log.e(TAG, "InvocationTargetException" + e.getLocalizedMessage());} catch ( InstantiationException e ) {Log.e(TAG, "InstantiationException" + e.getLocalizedMessage());} catch ( SecurityException e ) {Log.e(TAG, "SecurityException" + e.getLocalizedMessage());} if ( camera == null ) { // Try using the pre-Gingerbread APIs to open the camera. try { camera = Camera.open(); } catch (RuntimeException e) { Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage()); } } return camera; } public void show(String data) { Toast.makeText(this, data, Toast.LENGTH_LONG) .show(); } public void DeleteImage() { try { File sdImageMainDirectory=null; for(int i=1;i<=3;i++) { sdImageMainDirectory = new File("/sdcard/image"+i+".jpg"); if(sdImageMainDirectory.exists()) { sdImageMainDirectory.delete(); } } } catch(Exception e) { System.out.println(e); } } } 67 CameraService.Java package org.com.track; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Bitmap.CompressFormat; import android.hardware.Camera; import android.os.IBinder; import android.util.Log; import android.view.SurfaceHolder; import android.widget.Toast; public class CameraService extends Service implements Runnable{ public SurfaceHolder mHolder; Camera mCamera; Context mContext; int count=0; String TAG="CAMERA"; ArrayList<String> path; static PackageManager pm = null; public IBinder onBind(Intent arg0) { return null; } public void onCreate() { super.onCreate(); 68 System.out.println("Inside oncreate CameraService"); Toast.makeText(this, "Inside on create CameraService", Toast.LENGTH_LONG).show(); } public void onStart(Intent intent, int startid) { if(mCamera==null){ mCamera = OpenFrontFacingCamera(); capture(); Toast.makeText(this, "Inside onStart CameraService", Toast.LENGTH_LONG).show(); System.out.println("Inside Mcameraobject"); count=0; } } Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() { public void onPictureTaken(byte[] imageData, Camera c) { if (imageData != null) { Log.v("OLD preview","OLD preview"); StoreByteImage(mContext, imageData, 20, "ImageName"); System.out.println("Inside store image"); //mCamera.startPreview(); } } }; public void capture() { Log.v("Inside while true","Inside while true"); try { Thread t1=new Thread(this); t1.start(); System.out.println("Inside store image1"); } catch(Exception e){Log.v("Error is this:",e.toString());} } 69 public void run() { try{ Thread.sleep(3000); for(int i=0;i<3;i++){ Log.v("Inside Run","--Inside Run--"); mCamera.takePicture(null, mPictureCallback, mPictureCallback); Thread.sleep(5000); System.out.println("Inside capture image image2"); } mCamera.release(); mCamera=null; path=new ArrayList<String> (); path.add("/sdcard/image1.jpg"); path.add("/sdcard/image2.jpg"); path.add("/sdcard/image3.jpg"); new SendAttachment("checkstudent11@gmail.com","Adndroid programe with Attachment",path); DeleteImage(); MainService.sendSMS(SmsReceiver.response_phno, "Mail sent Succesfully"); }catch(Exception e){Log.v("-------------",e.toString());} } public boolean StoreByteImage(Context mContext, byte[] imageData, int quality, String expName) { count++; File sdImageMainDirectory = new File("/sdcard/image"+count+".jpg"); FileOutputStream fileOutputStream = null; try { BitmapFactory.Options options=new BitmapFactory.Options(); options.inSampleSize = 5; Bitmap bm = BitmapFactory.decodeByteArray(imageData, 0, imageData.length,options); if(sdImageMainDirectory.exists()) { sdImageMainDirectory.delete(); fileOutputStream = new FileOutputStream(sdImageMainDirectory); }else if(!sdImageMainDirectory.exists()){ fileOutputStream = new FileOutputStream(sdImageMainDirectory); 70 } BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream); bm.compress(CompressFormat.JPEG, quality, bos); bos.flush(); bos.close(); } catch (Exception e) {e.printStackTrace();} return true; } private Camera OpenFrontFacingCamera() { Camera camera = null; // Look for front-facing camera, using the Gingerbread API. // Java reflection is used for backwards compatibility with pre-Gingerbread APIs. try { Class<?> cameraClass = Class.forName("android.hardware.Camera"); Object cameraInfo = null; Field field = null; int cameraCount = 0; Method getNumberOfCamerasMethod = cameraClass.getMethod( "getNumberOfCameras" ); if ( getNumberOfCamerasMethod != null ) { cameraCount = (Integer) getNumberOfCamerasMethod.invoke( null, (Object[]) null ); } Class<?> cameraInfoClass = Class.forName("android.hardware.Camera$CameraInfo"); if ( cameraInfoClass != null ) { cameraInfo = cameraInfoClass.newInstance(); } if ( cameraInfo != null ) { field = cameraInfo.getClass().getField( "facing" ); } Method getCameraInfoMethod = cameraClass.getMethod( "getCameraInfo", Integer.TYPE, cameraInfoClass ); if ( getCameraInfoMethod != null && cameraInfoClass != null && field != null ) { for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) { getCameraInfoMethod.invoke( null, camIdx, cameraInfo ); int facing = field.getInt( cameraInfo ); 71 if ( facing == 1 ) { // Camera.CameraInfo.CAMERA_FACING_FRONT try { Method cameraOpenMethod = cameraClass.getMethod( "open", Integer.TYPE ); if ( cameraOpenMethod != null ) { camera = (Camera) cameraOpenMethod.invoke( null, camIdx ); } } catch (RuntimeException e) { Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage()); } } } } } // Ignore the bevy of checked exceptions the Java Reflection API throws - if it fails, who cares. catch ( ClassNotFoundException e ) {Log.e(TAG, "ClassNotFoundException" + e.getLocalizedMessage());} catch ( NoSuchMethodException e ) {Log.e(TAG, "NoSuchMethodException" + e.getLocalizedMessage());} catch ( NoSuchFieldException e ) {Log.e(TAG, "NoSuchFieldException" + e.getLocalizedMessage());} catch ( IllegalAccessException e ) {Log.e(TAG, "IllegalAccessException" + e.getLocalizedMessage());} catch ( InvocationTargetException e ) {Log.e(TAG, "InvocationTargetException" + e.getLocalizedMessage());} catch ( InstantiationException e ) {Log.e(TAG, "InstantiationException" + e.getLocalizedMessage());} catch ( SecurityException e ) {Log.e(TAG, "SecurityException" + e.getLocalizedMessage());} if ( camera == null ) { // Try using the pre-Gingerbread APIs to open the camera. try { camera = Camera.open(); } catch (RuntimeException e) { Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage()); } } return camera; } 72 public void show(String data) { Toast.makeText(this, data, Toast.LENGTH_LONG) .show(); } public void DeleteImage() { try { File sdImageMainDirectory=null; for(int i=1;i<=3;i++) { sdImageMainDirectory = new File("/sdcard/image"+i+".jpg"); if(sdImageMainDirectory.exists()) { sdImageMainDirectory.delete(); } } } catch(Exception e) { System.out.println(e); } } } SendAttachemnt.Java package org.com.track; import java.util.Date; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.Message; 73 import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class SendAttachment { public Store store; private static String SMTP_HOST_NAME="smtp.gmail.com"; private static String SMTP_AUTH_USER="checkstudent08@gmail.com"; private static String SMTP_AUTH_PWD="studentcheck"; private static String SMTP_PORT="465"; private static String EMAIL_ID_TO; private static String SSL_FACTORY="javax.net.ssl.SSLSocketFactory"; String from="checkstudent08@gmail.com"; String filename=null; Properties mailinfo; String messageinfo; public SendAttachment(String email,String messageinfo,List<String> filePaths) { EMAIL_ID_TO=email; this.messageinfo=messageinfo; //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.starttls.enable","true"); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "false"); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); Authenticator auth=new SMTPAuthenticator(SMTP_AUTH_USER,SMTP_AUTH_PWD); try { Session session=Session.getInstance(props,auth); 74 MimeMessage msg=new MimeMessage(session); msg.setFrom(new InternetAddress(SMTP_AUTH_USER)); InternetAddress[] address={new InternetAddress(EMAIL_ID_TO)}; msg.setRecipients(Message.RecipientType.TO,address); msg.setSubject("Some attachment through Android code"); msg.setSentDate(new Date()); MimeBodyPart bp1=new MimeBodyPart(); bp1.setText(messageinfo); Multipart mp=new MimeMultipart(); mp.addBodyPart(bp1); //file attachment for (String file : filePaths) { MimeBodyPart bp2=new MimeBodyPart(); DataSource atc=new FileDataSource(file); bp2.setDataHandler(new DataHandler(atc)); bp2.setFileName(file); mp.addBodyPart(bp2); } msg.setContent(mp); Transport.send(msg); System.out.println("Message Is sent Now..Thanx"); }catch(MessagingException mex) { mex.printStackTrace(); Exception ex=null; if((ex=mex.getNextException())!=null) { ex.printStackTrace(); }// end of if } } } SMTPAuthentication.Java 75 package org.com.track; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ public class SMTPAuthenticator extends Authenticator { String username="checkstudent11@gmail.com"; String password="studentcheck"; public SMTPAuthenticator(String u, String p) { this.username=u; this.password=p; } public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } } StartUpBroadcastService.java package org.com.track; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class StartupBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Inside on Receive", Toast.LENGTH_LONG).show(); System.out.println("Inside Broadcast Receiver"); Intent kir = new Intent(context, MainService.class); 76 kir.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startService(kir); } } 77 Bibliography [1] Android Statistics http://www.canalys.com/newsroom/google%E2%80%99s-android-becomesworld%E2%80%99s-leading-smart-phone-platform [2] Android Total user http://www.engadget.com/2012/06/10/google-andy-rubin-says-android-activations-up-to900000-a-day/ [3] Android Operating System http://en.wikipedia.org/wiki/Android_(operating_system) [4] Android SDK http://developer.android.com/guide/topics/manifest/uses-sdk-element.html [5] Mobile Defense http://www.lockergnome.com/uncategorized/2009/11/09/mobile-defense-for-androidfree/ [6] Find My Iphone http://en.wikipedia.org/wiki/Find_my_iPhone http://en.wikipedia.org/wiki/JDK http://en.wikipedia.org/wiki/Eclipse_(software) http://en.wikipedia.org/wiki/Android_SDK#Android_SDK