Sunteți pe pagina 1din 83

PROJECT REPORT ON

SAFE DRIVING USING MOBILE APP


SUBMITTED BY:

TRUPTI RAJARAM ZURE


MANISHA SELVARAJ

UNDER THE GUIDANCE OF


PROF. ROHINI DESAI

VIDYALANKAR SCHOOL OF INFORMATION TECHNOLOGY,


WADALA (E), MUMBAI-400 037.

UNIVERSITY OF MUMBAI
2017-2018

VIDYALANKAR SCHOOL OF INFORMATION TECHNOLOGY


WADALA (E), MUMBAI 400037

1
CERTIFICATE

This is to certify that the project entitled “SAFE DRIVING USING


MOBILE APP” is a bonafide work of “TRUPTI RAJARAM ZURE”
And “MANISHA SELVARAJ” submitted to the University of
Mumbai in partial fulfilment of the requirement for the award of the
degree of “Bachelors of Science (Information Technology)”.

Internal Guide Internal examiner External examiner

Coordinator Principal College Seal

2
ANDROID MOBILE APPLICATION

“SAFE DRIVING USING MOBILE


APPLICATION”

3
ACKNOWLEDGEMENT

This project could not have been accomplished if not for the direct or indirect
contribution from many known and unknown individuals. We wish to take this
opportunity to express our sincere gratitude to all of them. We express our
gratitude towards our internal guide Prof. Rohini Desai who gave us unending
support from the stage the project was initiated.
A source of inspiration, given by them constantly kept our spirits high,
whenever we were dispirited. The foundation that we have been able to develop
today owes much credit to her. Always ready to co-operate, she has been very
kind in guiding us how to go about developing the project.
We are also highly obliged to our Principal Dr. Rohini Kelkar who has extended
timely whenever required. We would even like to thank all our friends for their
co-operation and help in our project. Above all we would like to thank the
almighty who have given us inspiration & courage to accept it as a course of
life.

4
STATEMENT BY STUDENT

I declare that this written submission represents my ideas in my own words and

where others' ideas or words have been included, I have adequately cited and

referenced the original sources. I also declare that I have adhered to all

principles of academic honesty and integrity and have not misrepresented or

fabricated or falsified any idea/data/fact/ source in my submission. I understand

that any violation of the above will be cause for disciplinary action by the

Institute and can also evoke penal action from the sources which have thus not

been properly cited or from whom proper permission has not been taken when

needed.

Signature of the candidate

Certified by

Signature of the guide

Date:

5
ABSTRACT

As vehicle manufacturers continue to increase their emphasis on safety with advanced driver-
assistance systems (ADASs), we propose a device that is not only already in abundance but
portable enough as well to be one of the most effective multipurpose devices that are able to
analyse and advise on safety conditions. Mobile smartphones today are equipped with
numerous features that can help to aid in safety enhancements for drivers on the road. In
present days mobile phones are plays most important role in every human life, but at the
same time in driving of automobile, mobile phones using is the main reason for accidents of
automobiles.
The proposed system is an Android application to manage incoming phone calls It will
temporary block the calls til the person is driving by leaving a message to the caller that
(person is driving) by tracing the change in location using Geolocation. The main objective
of this project is to create an Mobile application with driving mode feature. Which will
automatically temporary block calls if person is driving.

6
TABLE OF CONTENTS

Sr. No. Topic Page. No.

1 Introduction

1.1 Organizational profile

1.2 Introduction to project

2 System study and analysis

2.1 Problem definition

2.2 Feasibility

2.3 System analysis

2.4 Current system

2.5 Proposed system

2.6 System requirement

3 System development

3.1 Gantt chart

3.2 Event table

3.3 Use Case diagram

3.4 Activity diagram

3.5 Class Diagram

3.6 Menu Tree

7
3.7 Deployment diagram

3.8 Sequence Diagram

4 Table list

5 System testing and conclusion

5.1 Conclusion

6 Process Involved

7 Source Code

8 Screen layout with test data and test result

9 References/ bibliography/websites used

8
LIST OF TABLE AND FIGURES

List of tables

Sr. No Topic Page No.


3.2 Event table
4 Table List
4.1 Data structure
4.2 Browse data

List of figure

Sr.no Topic Page.no


2.3.1 System planning
3.1 Gantt chart
3.1.1 Tasks
3.1.2 Chart
3.3 Use case diagram
3.4 Activity diagram
3.5 Class diagram
3.6 Menu tree
3.7 Deployment diagram
3.8 Sequence diagram

9
1.INTRODUCTION

10
1.1 ORGANIZATIONAL PROFILE:
Now a day’s most of the people used the mobile having the android operating system.
Android applications are today’s most effective platform for any sort of works like
communication, security, games, entertainment etc. over the world. It is interesting to discuss
that android application have some specific internal objective that make them a part of
everyone’s life today. Today, people don’t look at them as just applications; they are defined
with more inner sense.

1.2 INTRODUCTION TO PROJECT:


The developed android application will be used by vehicle drivers and the administrator who
maintains the system. The main aim of the project is to design a mobile phone application
with driving mode feature. Whenever the application gets started and vehicle engine is in
running mode then the application will track the vehicle motion using Global Positioning
System, if there is any change in vehicle position the mobile application will set in the
driving mode. And then the system automatically manages the incoming phone calls. When
the call is coming to the person, the application disconnects the call and sends SMS message
to the caller as the user is under driving mode or under busy mode. This feature helps in
avoiding the unnecessary calls (like customer care etc.), also avoids accidents when the user
diverts his/her attention from driving the vehicle. If the same caller will call thrice then the
mobile will get ring.

11
2. SYSTEM STUDY
AND ANALYSIS

12
2.1 PROBLEM DEFINITION:
Mobile phone use while driving is common, but it is widely considered dangerous due to
its potential for causing distracted driving and accidents

General Cell Phone Statistics. The National Safety Council reports that cell phone use
while driving leads to 1.6 million crashes each year. Nearly 330,000 injuries occur each
year from accidents caused by texting while driving. 1 out of every 4 car accidents in the
India is caused by texting and driving.

Cell phone related car accidents and fatalities continues to increase despite legislative
action by the state governments that prohibit specific cell phone related activities while
driving and despite educational efforts to warn the general public about the risk cell phone
use pose to not only the driver but its passengers and the entire community. Due to the
similarities of risk between cell phone use while driving and driving while under the
influence of alcohol, a demand to regulate cell phone use while behind the wheel in order
to decrease the number of accidents and fatalities is not being met.

2.2 FEASIBILITY:
A feasibility study is the study of positive possibilities of the project. It is also measure of
how beneficial or practical development of information system would be to an
organization.

The different types of feasibility are as follows:

 Economic feasibility.

 Operational feasibility
.
 Technical feasibility.

Economic Feasibility:
Higher level of automation most often requires more funds. Hence based on the hardware
and software specification a desirable alternative costs and benefits to see if the investment
made in creating / developing a new system is costlier or more beneficial.

13
The product is not made for a particular visitor. Thus the economic cost for the hardware and
software and other peripheral devices are thus reduced.
My system is economically feasible as the costs involved in implementing the automated
system is in lieu with the cash flow of the organization. Thus the system developed will be
beneficial to the users.
However there will be an additional cost for implementing the technology on which the
system is to be implemented

Technical Feasibility:
It is essential to check whether the proposed system is technically feasible and to determine
the technology and skills necessary to carry out the successful implementation of the project.
The necessary software required for the development of system is

 Android OS 4.0 or higher

 SQLite

 Android Studio 2.2.3

There is requirement for the mentioned software and an expertise for handling system. Thus
in the presence of required hardware, software the proposed system is technically feasible.

Operational Feasibility:
The operational feasibility is obtained by consulting the system user whether it satisfies the
user’s requirements. A system with an easy interface will always help the user to use the
system. It is mainly related to human organizations and political aspects. The points to be
considered are:

 Some kind of graphical user interface changes can be brought to the system.

2.3 SYSTEM ANALYSIS:

Planning:
It consists of initial assessment and feasibility study. During initial assessment and feasibility
study the technical aspects of the hardware and software were determine as which hardware

14
and software should be used to develop the project. Also the cost needed to developed project
was estimated.

Analysis:
It consists of user requirements, existing system evaluation and logical system design. During
this stage the requirements needed by user were analysed, macro analyses of both the
individual needs were. Logical system design was created specifying and identifying.

Detailed system design:


During these phase the complete design of the system including all the technical specification
for the screens, menus, reports were made. The system was coded, the actual database was
created and system was customized by the creation of tables, user authorizations and so on.

Code Generation:
The design must be translated into a machine –readable form. The code generation step
performs this task. If designed is performed in a detailed manner, code generation can be
accomplished mechanistically.

Testing:
Once code has been generated, program testing begins. The testing process focuses on the
logical internals of the software, ensuring that all statements have been tested, and on the
functional externals; that is, conducting tests to uncover errors and ensure that defined input
will produce actual results that agree with required results.

Maintenance:
The software will definitely undergo change once it is delivered to the customer. There can
be many reasons for this change to occur. Change could happen because of some unexpected
input values into the system. In addition, the changes in the system could directly affect the
software operations. The software should be developed to accommodate changes that could
happen during the post implementation period

15
Planning Anyalysis Design Testing Implementation

Figure 2.3.1 : SYSTEM PLANNING

16
2.4 CURRENT SYSTEM:
This process is done using truecaller or by a feature in Samsung phone. The current system
like truecaller is used to block call commonly and the feature of Samsung is drive mode is
only available in that phone. This current system is time consuming. To manually handle
such a system was very difficult task. But now-a-days because of android application this job
is becoming easier to drive safely by using mobile phones.
The following are the reasons why the current system should be made for
an android application:
 To reduce the burden of manual work to decide to handling calls while driving.

 To save time of management and to avoid accidents during driving.

 To check that the exact location automatically to find motion of car and to decide
speed of car. So that it can alert the driver when speed increases a certain limit.

LIMITATIONS OF CURRENT SYSTEM:


Notifications do not pop up, every time driver has to reject call manually while driving. The
feature is not available for all commonly. A lot of accidents occur due to the mobile phones but
by just activating this app before driving will automatically reduce driver burden.

Time consumption –The current system like true caller is timing consuming one because
we have to block call manually and in Samsung phone that feature has to be activated by us and
we only deactivate it once we stop driving .

Storage Requirements- The current system occupies more storage in mobile phone by
having its extra own database.

Less Reliable- The current system don’t reject calls automatically by detecting whether
car is in motion or not.

Accuracy- as the current system doesn’t detect the motion of car automatically the
accuracy is reduced.

Difficulty in detecting whether call is important one -the current system


completely blocks the call driving even if it’s an emergency condition

Problems faced by caller -the current system don’t allow call at any condition and
current system doesn’t inform the caller why the receiver is not attending call.

17
2.5 PROPOSED SYSTEM:
The objective of the design of a new system. The main aim of the project is to design mobile
phone application with driving mode feature. Whenever the mobile phone is set up on driving
mode, the system will automatically manage the incoming phone calls. When the call is
coming to the person, this system disconnects the call and sends SMS message to the caller as
the user is under driving mode or under busy mode. This feature helps in avoiding the
unnecessary calls , also avoids accidents when the user diverts from driving the vehicle. If the
same caller will call thrice then the mobile will get ring.

The developed application will be used by vehicle driver and the administrator. The
functionalities of the proposed system can be divided into 6 well defined modules:

Modules:
1. GPS

2. Call block

3. SMS forwarding

4. Driving module

5. Settings

6. About

2.6 SYSTEM REQUIREMENTS:


SOFTWARE SPECIFICATIONS
 Android OS 4.0
or higher

 SQLite

 Android Studio 1.5.1

OPERATING SYSTEMS
 Windows 10 (64-bit)

18
HARDWARE SPECIFICATIOS
 Hard disk - 500 GB
 o
 Processor - i5 Generation 2.4 GHz
 o
 Ram - 4 GB
 o

19
3.SYSTEM
DEVELOPMENT

20
3.1 GANTT CHART:
A Gantt chart is a type of bar chart, developed by Henry Gantt in the 1910s, that illustrates a
project schedule. Gantt charts illustrate the start and finish dates of the terminal elements and
summary elements of a project. Terminal elements and summary elements comprise the work
breakdown structure of the project. Modern Gantt charts also show the dependency (i.e.
precedence network) relationships between activities. Gantt charts can be used to show
current schedule status using percent-complete shadings.

Gantt charts can be used for scheduling generic resources, so as well as their use in project
management, they can also be used in scheduling production processes and employee
restoring. In the latter context, they may also be known as time bar schedules.

There are many computer applications supporting the use of Gantt charts for employee
scheduling, for example, Gantt.

Figure 3.1.1: Tasks

21
Figure 3.1.2: Gantt Chart

22
3.2 EVENT TABLE:
The event table is a table of data that is typically written to the log file for each scenario and
also appears in the Analysis window. The event table contains timing information about
specific events that occur during the scenario.

EVENT TRIGGER ACTIVITY SOURCE RESPONSE DESTINATION

USER REGISTERATION USER CLICKS USER ENTER USER SERVICES USER


ON LOGIN PHONE NO &
NAME

DRIVE MODE INVOKE USER CLICKS ENABLE GPS USER INVOKES DRIVE USER
ON BUTTON LOCATION MODE

BLOCKING CALL WHEN GPS LOCATION USER BLOCKS CALL CALLER


STARTS GETS CHANGE
DRIVING

SPEED LIMIT WHEN USER CREATES A USER PROMPT USER


INCREASE PROPMT (SPEED LIMIT
SPEED EXCEEDED)

SENDING SMS USER STARTS BLOCKS CALL USER SMS(I AM CALLER


DRIVING DRIVING CALL
U LATER)

DRIVING MANUAL CLICKS ON INFORMATION USER SHOWS USER


BUTTON ABOUT CONTENT
DRIVING

Figure 3.2: Event Table

23
3.3 USE CASE DIAGRAM:

A use case diagram in the Unified Modelling Language (UML) is a type of behavioural
diagram defined by and created from a Use-case analysis. Its purpose is to present a
graphical overview of the functionality provided by a system in terms of actors, their goals
(represented as use cases), and any dependencies between those use cases.

Figure 3.3: Use case diagram

24
3.4 ACTIVITY DIAGRAM:
An activity diagram illustrates the dynamic nature of a system by modelling the flow of
control from activity to activity. An activity represents an operation on some class in the
system that results in a change in the state of the system. Typically, activity diagrams are
used to model workflow or business processes and internal operation. Because an activity
diagram is a special kind of state chart diagram, it uses some of the same modelling
conventions.

Figure 3.4 Activity diagram


25
3.5 CLASS DIAGRAM:
The class diagram is the main building block in object oriented modeling. It is used both for
general conceptual modeling of the systematics of the application, and for detailed modeling
translating the models into programming code. The classes in a class diagram represent both
the main objects and or interactions in the application and the objects to be programmed. In
the class diagram these classes are represented with boxes which contain three parts:

 The upper part holds the name of the class.

 The middle part contains the attributes of the class.

 The bottom part gives the methods or operations the class can take or
undertake.

Figure 3.5: Class diagram

26
3.6 MENU TREE:

Menu tree is systematic diagram, tree analysis, analytical tree, hierarchy diagram. The menu
tree diagram starts with one item that branches into tw or more, each of which branch into
two or more, and so on. It looks like a tree, with trunk and multiple branches.

It is used to break down broad categories into finer and finer levels of detail.
Developing the tree diagram helps you move your thinking step by step from
generalities to specifics

Figure 3.6: Menu Tree

27
3.7 DEPLOYMENT DIAGRAM:
Deployment diagram is a structure diagram which shows architecture of the system as
deployment (distribution) of software artifacts to deployment targets. Artifacts represent
concrete elements in the physical world that are the result of a development process.

Figure 3.7 Deployment diagram

28
3.8 SEQUENCE DIAGRAM:
A sequence diagram is an interaction diagram that shows how objects operate with one
another and in what order. It is a construct of a message sequence chart.A sequence
diagram shows object interactions arranged in time sequence. Sequence diagrams are
sometimes called event diagrams or event scenarios

Figure 3.8: Sequence diagram

29
4.TABLE LIST

30
Figure 4.1: Data structure

Figure 4.2: Browse data

31
5.SYSTEM TESTING
AND CONCLUSION

32
SYSTEM TESTING
Testing is the process of examining a product to determine what defects it contains to
conduct a test, programmers must have already constructed software and there must be
well-defined standard for what constitute a defect. The developers can test products by
reviewing their constructions and compositions or by exercising their functions and
examining the results.

An information system is an integrated collection of software components. Components can


be tested individually or in groups or entire system can be tested as a whole. Testing
components individually or in groups is called unit testing. Testing components in group is
called integrated testing. Testing entire system is called system testing.

The three types of testing are correlated to specific phase of SDLC. A system text examines
the behavior of entire system with respect to technical and user. These requirements are
determined during analysis phase of SDLC. During high level design, the division of the
system into high level components and structural design of those components are
determined. Integration testing tests the behavior of variable group of software components.
Unit testing test each individual software components in isolation.

Because of each testing level is related to specific phase of SDLC, testing activities can be
spread out through the life cycle. Planning for each type testing can occur with its related
SDLC phase. And development of specific test can occur once the planning for each type
testing can occur with its reached SDLC phase, and development of specific test can occur
once the planning is complete. Test can’t be conducted until relevant portion of the system
have been constructed.

Unit Testing:
This is a process of testing individual code modules before they integrate with other modules.
Unit testing being tested may be a function, sub routine, procedure, or method. Unit testing
may be relatively small groups of inter related modules that are always executes as group.
The goal of unit testing is to identify and fix as many errors as possible before modules and
expensive to locate and fix when many modules are combined.

Integrated Testing:
An integration test tests the behavior of group modules. The purpose of an integration test is
to identify errors that were not or could not be detected by unit testing individual modules or
methods.

Such error may result from number of problem including


Interface Compatibility.
Parameter Values.

33
Runtime Exception.
Unexpected State Interaction.

System Testing:
After integration, the whole program will again be tested. Case studies will again be applied
with integrated software.

Methodology used for testing:


The testing methodology implemented for testing of the project is Black Box testing.

In the black box testing, the internal logic of the system under testing is not considered and
the test cases are decided form the specification or the requirements. It is often called
functional testing. It aims to test functionality according to the requirements. Equivalence
class portioning, boundary value analysis, and because effecting graphing are examples of
methods for selecting test cases for black box testing. State-based testing is another approach
in which the system is modeled as a state machine and then this model is used to select test
cases using some transaction or path based coverage criteria, state-based testing can also be
viewed as grey-box testing in that it often requires more information than just the
requirements.

The testing methodology implemented for testing of the project is the black box testing.
Refer the above paragraph for explanation.

Test Cases:
The forms were tested for their functionality and error messages displayed wherever
the input does not meet the required requirements.

34
5.1 CONCLUSION
This was our project of System Design Lab about “THE ANDROID APPLICATION” (SAFE
DRIVING APPLICATION). Development of this System takes a lot of efforts from us. We
think this system gave a lot of satisfaction to all of us. Though every task is never said to be
perfect in this development field even more improvement may be possible in this system. We
learned so many things and gained a lot of knowledge about development field. We hope this
will prove fruitful to us.

35
6.PROCESS
INVOLVED

36
1. BLOCKING CALL
A. Tracing location
B. Sending sms to user

2. TRACKING SPEED
A. Checking driving speed
B. Prompting an alert

3. MANUAL
A. Providing guidelines to driver

4. REGISTRATION
A. Storing user details

37
7.SOURCE CODE

38
Activity_start.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_start"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
tools:context="sss.example.com.safedrive.Start">

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/bg" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical">

<TextView
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:padding="10dp"
android:textSize="20dp"
android:background="@drawable/border"
android:text="INVOKE DRIVE MODE NOW"
android:textColor="#fff"
android:layout_margin="20dp"
android:textStyle="bold" />

<TextView

android:textSize="20dp"
android:background="@drawable/border"
android:id="@+id/settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:padding="10dp"
android:text="Settings"
android:textColor="#fff"

android:layout_margin="20dp"

39
android:textStyle="bold" />
<TextView
android:id="@+id/drivingmanual"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:padding="10dp"

android:textSize="20dp"

android:text="Driving Manual"
android:textColor="#fff"
android:background="@drawable/border"
android:layout_margin="20dp"
android:textStyle="bold" />
<TextView

android:textSize="20dp"

android:id="@+id/abaut"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:padding="10dp"
android:text="About"
android:textColor="#fff"
android:background="@drawable/border"
android:layout_margin="20dp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>

Start.java

package sss.example.com.safedrive;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class Start extends AppCompatActivity {


TextView t,about,drivingmanual,settings;

40
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
t = (TextView)findViewById(R.id.start);
about = (TextView)findViewById(R.id.abaut);
settings = (TextView)findViewById(R.id.settings);
drivingmanual = (TextView)findViewById(R.id.drivingmanual);
SharedPreference.initialize(getApplicationContext());
t.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Start.this,MainActivity.class);
startActivity(i);
}
});
about.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(Start.this,About.class);
startActivity(i);
}
});
drivingmanual.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(Start.this,Driving.class);
startActivity(i);
}
});
settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(Start.this,Setting.class);
startActivity(i);
}
});
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg">

41
<TextView
android:id="@+id/txtmessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@color/colorPrimaryDark"
android:textSize="20dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/text1"
android:layout_centerHorizontal="true"
android:padding="5dp"
android:src="@drawable/mobile" />

<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/textView3"
android:gravity="center"
android:padding="5dp"
android:text="SafeDrive Mode : ON"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="0 KMPH"
android:textColor="#fff"
android:textSize="35sp"
android:textStyle="bold" />

<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp"
android:background="@drawable/border"
android:gravity="center"

42
android:padding="10dp"
android:text="I'm not driving"
android:textColor="#fff"
android:textSize="25dp"
android:textStyle="bold" />

<EditText
android:id="@+id/speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/textView3"
android:layout_marginLeft="30dp"
android:padding="5dp"
android:text="km/hr"
android:textColor="#f00"
android:visibility="gone" />

<Button
android:id="@+id/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/speed"
android:text="Update speed"
android:visibility="gone" />
</RelativeLayout>

Main.java

package sss.example.com.safedrive;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

43
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class MainActivity extends AppCompatActivity implements


GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
EditText km;
TextView imnot;
Button update;
LocationManager locationManager;
boolean GpsStatus;
Location mLastLocation;
String lat, lon;
private AbsoluteSizeSpan sizeSpanLarge = null;
private AbsoluteSizeSpan sizeSpanSmall = null;
private double speed = 0.0;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public static myDBClass myDb;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new myDBClass(getApplicationContext());
CheckGpsStatus();
km = (EditText) findViewById(R.id.speed);
imnot = (TextView) findViewById(R.id.text2);
km = (EditText) findViewById(R.id.speed);

imnot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent ii = new Intent(MainActivity.this,Start.class);
startActivity(ii);
finish();
}
});
if(SharedPreference.contains("km")){
km.setText(SharedPreference.get("km"));
}else{

44
Toast.makeText(this, "empty", Toast.LENGTH_SHORT).show();
}

update = (Button) findViewById(R.id.update);


update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreference.save("km", km.getText().toString());
}
});
if (GpsStatus == true) {
Toast.makeText(this, "Location Services Is Enabled",
Toast.LENGTH_SHORT).show();

} else {
Toast.makeText(this, "Location Services Is DisEnabled",
Toast.LENGTH_SHORT).show();
}

LocationManager lm = (LocationManager)
getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}

try {
network_enabled =
lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}

if (!gps_enabled && !network_enabled) {


// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setMessage("gps_network_not_enabled");
dialog.setPositiveButton("open setting", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(myIntent);

}
});

45
dialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub

}
});
dialog.show();
}
SharedPreference.initialize(getApplicationContext());
// startService(new Intent(SpeedCalc.this, MyService.class));
startService(new Intent(MainActivity.this, IncomingCallReceiver.class));
buildGoogleApiClient();
Intent intent = getIntent();
Bundle b = intent.getExtras();
TextView tv = (TextView) findViewById(R.id.txtmessage);
// int count =0;
if (b != null) {
tv.setText(b.getString("number"));
}
/* if(count>3){
Toast.makeText(this, "Your Friend Calling you plz reply",
Toast.LENGTH_SHORT).show();
}else{
if (b != null) {
tv.setText(b.getString("number"));
}
++count;
}
*/
}

@Override
public void onConnected(Bundle bundle) {

mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lon = String.valueOf(mLastLocation.getLongitude());

46
}
updateUI();
}

@Override
public void onConnectionSuspended(int i) {

@Override
public void onLocationChanged(Location location) {
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());

speed = location.getSpeed();
double speedKPH = convertSpeed(speed);

if (speedKPH > 20.0) {


Toast.makeText(this, "Car is running state", Toast.LENGTH_SHORT).show();
imnot.setText("Driving a car");

} else if (speedKPH == 0) {
Toast.makeText(this, "Car is steady state", Toast.LENGTH_SHORT).show();
imnot.setText("I am not driving");
}

String speedString = "" + roundDecimal(convertSpeed(speed), 2);


String unitString = measurementUnitString(0);

setSpeedText(R.id.textView3, speedString + " " + unitString);


//if(speedString)
Log.i("Speed", speedString);
updateUI();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}

synchronized void buildGoogleApiClient() {


mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();

47
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}

@Override
protected void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}

void updateUI() {
Log.i("cor", "lat:-" + lat + "long" + lon);

private double roundDecimal(double value, final int decimalPlace) {


BigDecimal bd = new BigDecimal(value);

bd = bd.setScale(decimalPlace, RoundingMode.HALF_UP);
value = bd.doubleValue();

return value;
}

private double convertSpeed(double speed) {


return ((speed * Constants.HOUR_MULTIPLIER) *
Constants.UNIT_MULTIPLIERS[0]);
}

private String measurementUnitString(int unitIndex) {


String string = "";

switch (unitIndex) {
case Constants.INDEX_KM:
string = "km/h";
break;
case Constants.INDEX_MILES:
string = "mi/h";
break;
}

return string;
}

private void setSpeedText(int textid, String text) {


Spannable span = new SpannableString(text);
int firstPos = text.indexOf(32);

48
span.setSpan(sizeSpanLarge, 0, firstPos,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(sizeSpanSmall, firstPos + 1, text.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TextView tv = ((TextView) findViewById(textid));

tv.setText(span);
}

public void CheckGpsStatus() {

locationManager = (LocationManager)
getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
}

activity_settings.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/upbg"
tools:context="sss.example.com.safedrive.Setting">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical">
<TextView
android:gravity="center"
android:textStyle="bold"
android:text="@string/appstatus"
android:textSize="25dp"

android:textColor="#fff"
android:layout_width="match_parent"

49
android:layout_height="wrap_content" />
<LinearLayout
android:layout_weight="2"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:paddingTop="10dp"
android:gravity="center"
android:textStyle="bold"
android:text="@string/auto"
android:textSize="25dp"
android:textColor="#fff"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<CheckBox
android:background="#fff"
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<TextView
android:paddingTop="10dp"
android:gravity="center"
android:textStyle="bold"
android:text="@string/automsg"
android:textSize="25dp"
android:textColor="#fff"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:paddingTop="10dp"
android:gravity="center"
android:textStyle="bold"
android:text="@string/msg"
android:textSize="25dp"
android:textColor="#fff"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/save"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Save"/>
</LinearLayout>
</RelativeLayout>

50
Setting.java

package sss.example.com.safedrive;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

public class Setting extends AppCompatActivity {


public static CheckBox cb;
Button save;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
cb = (CheckBox)findViewById(R.id.checkbox);
//save = (Button) findViewById(R.id.save);
cb.setChecked(true);
/* if(SharedPreference.contains("cb")){
cb.setChecked(true);
}else{
cb.setChecked(false);
}*/
/*save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreference.save("cb",false);
}
});*/

activity_driving.java
package sss.example.com.safedrive;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

public class Setting extends AppCompatActivity {

51
public static CheckBox cb;
Button save;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
cb = (CheckBox)findViewById(R.id.checkbox);
//save = (Button) findViewById(R.id.save);
cb.setChecked(true);
/* if(SharedPreference.contains("cb")){
cb.setChecked(true);
}else{
cb.setChecked(false);
}*/
/*save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreference.save("cb",false);
}
});*/

driving.java
package sss.example.com.safedrive;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Driving extends AppCompatActivity {

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

activity_about.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

52
android:layout_height="match_parent"
tools:context="sss.example.com.safedrive.About"
android:background="@drawable/upbg">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:textColor="#fff"
android:textStyle="bold"
android:gravity="center"
android:layout_marginTop="50dp"
android:text="@string/abouth"/>
<TextView

android:textColor="#fff"
android:textStyle="bold"
android:gravity="left"
android:textSize="17dp"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/about"/>
</LinearLayout>
</RelativeLayout>

About.java

package sss.example.com.safedrive;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class About extends AppCompatActivity {

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

53
blockcallreceiver.java
import java.lang.reflect.Method;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;

import static android.content.Context.TELEPHONY_SERVICE;

public class BlockCallReceiver extends BroadcastReceiver{

Context context;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle myBundle = intent.getExtras();
if (myBundle != null)
{
System.out.println("--------Not null-----");
try
{
if (intent.getAction().equals("android.intent.action.PHONE_STATE"))
{
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
System.out.println("--------in state-----");
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
{
// Incoming call
String incomingNumber
=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
System.out.println("--------------my number---------"+incomingNumber);

// this is main section of the code,. could also be use for particular number.
// Get the boring old TelephonyManager.
TelephonyManager telephonyManager =(TelephonyManager)
context.getSystemService(TELEPHONY_SERVICE);

// Get the getITelephony() method


Class<?> classTelephony =
Class.forName(telephonyManager.getClass().getName());
Method methodGetITelephony =
classTelephony.getDeclaredMethod("getITelephony");

// Ignore that the method is supposed to be private


methodGetITelephony.setAccessible(true);

// Invoke getITelephony() to get the ITelephony interface


*/

54
/*Object telephonyInterface = methodGetITelephony.invoke(telephonyManager);

// Get the endCall method from ITelephony


Class<?> telephonyInterfaceClass =
Class.forName(telephonyInterface.getClass().getName());
Method methodEndCall =
telephonyInterfaceClass.getDeclaredMethod("endCall");

// Invoke endCall()
methodEndCall.invoke(telephonyInterface);*//*

TelephonyManager tm = (TelephonyManager)
context.getSystemService(TELEPHONY_SERVICE);

Method m1 = tm.getClass().getDeclaredMethod("getITelephony");
m1.setAccessible(true);
Object iTelephony = m1.invoke(tm);

Method m2 = iTelephony.getClass().getDeclaredMethod("silenceRinger");
Method m3 = iTelephony.getClass().getDeclaredMethod("endCall");

m2.invoke(iTelephony);
m3.invoke(iTelephony);
}

}
}
catch (Exception ex)
{ // Many things can go wrong with reflection calls
ex.printStackTrace();
}
}
}

sharedpreference.java

package sss.example.com.safedrive;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import java.util.Set;

public class SharedPreference {

private static Context context = null;


private static SharedPreferences preferences;

55
private static SharedPreferences.Editor editor;

public static Context getContext() {


return context;
}

public static void initialize(Context con) {


if (context == null) {
context = con;
}
if (null == preferences) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
if (null == editor) {
editor = preferences.edit();
}
}

public static void save(String key, String value) {


editor.putString(key, value);
editor.commit();
}

public static void save(String key, Integer value) {


save(key, String.valueOf(value));
}

public static void save(String key, Boolean value) {


save(key, String.valueOf(value));
}

public static void save(String key, Long value) {


save(key, String.valueOf(value));
}

public static String get(String key) {


return preferences.getString(key, null);
}

public static Set<String> getObjectSet(String key) {


return preferences.getStringSet(key, null);
}

public static void setObjectSet(String key, Set<String> array) {


editor.putStringSet(key, array);
editor.commit();
}

public static Boolean contains(String key) {


return preferences.contains(key);

56
}

public static void removeKey(String key) {


editor.remove(key);
editor.commit();
}
}

mydbclass.java

package sss.example.com.safedrive;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class myDBClass extends SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "callls";

// Table Name
private static final String TABLE_NAME = "callsdb";

public myDBClass(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// Create Table Name

//db.execSQL("CREATE TABLE " + TABLE_Name + "(MemberID INTEGER


PRIMARY KEY AUTOINCREMENT," + " Name TEXT(100)," + " Tel TEXT(100));");
db.execSQL("CREATE TABLE callsdb (pnumbers VARCHAR);");
//db.execSQL("CREATE TABLE todolist (id INTEGER, eventtitle VARCHAR,todolist
VARCHAR);");

57
Log.d("CREATE TABLE", "Create Table Successfully.");
}

public void insert(String number){


SQLiteDatabase db;
db = this.getWritableDatabase();
Cursor c2 = db.rawQuery("INSERT INTO `callsdb`(`pnumbers`) VALUES ('" +
number + "')", null);
Log.i("count",c2.getCount()+"");
//c2.moveToFirst();
Log.d("alredy exist true==>", "insert");
}

public boolean deleteTitle(String name) {


SQLiteDatabase db = null;
return db.delete(TABLE_NAME, "producttitle" + "=" + name, null) > 0;
}

public void deleteAll() {

SQLiteDatabase db;
db = this.getWritableDatabase();
db.execSQL("delete from productlist");
}

/*public long UpdateData(String productttile, int price, int qyt) {


// TODO Auto-generated method stub

try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data

*/

/**
* for API 11 and above
* SQLiteStatement insertCmd;
* String strSQL = "INSERT INTO " + TABLE_MEMBER
* + "(MemberID,Name,Tel) VALUES (?,?,?)";
* <p>
* insertCmd = db.compileStatement(strSQL);
* insertCmd.bindString(1, strMemberID);
* insertCmd.bindString(2, strName);
* insertCmd.bindString(3, strTel);
* return insertCmd.executeInsert();
*//*

ContentValues Val = new ContentValues();


Val.put("producttitle", productttile);

58
Val.put("price", price);
Val.put("qyt", qyt);
//Val.put("", );

long rows = db.update(TABLE_NAME,Val,"producttitle"+productttile,null);


db.close();
return rows; // return rows inserted.

} catch (Exception e) {
return -1;
}

}*/

/*public long InsertData1(String eventTitle, String strtodolist) {


try {
SQLiteDatabase db;
db = this.getWritableDatabase();

ContentValues Val = new ContentValues();


Val.put("eventtitle", eventTitle);
Val.put("todolist", strtodolist);

long rows = db.insert(TABLE_NAME1, null, Val);

db.close();
return rows; // return rows inserted.

} catch (Exception e) {
return -1;
}
}*/
/*public boolean UpdateData(String productttile, int price, int qyt) {
ContentValues args = new ContentValues();
//args.put("producttitle", productttile);
SQLiteDatabase db;
db = this.getWritableDatabase();
args.put("price", price);
args.put("qyt", qyt);
return db.update(TABLE_NAME, args, "producttitle" + "=" + productttile, null) > 0;
}*/

// Select Data
public String[] SelectData(String eventtitle) {
// TODO Auto-generated method stub

59
try {
String arrData[] = null;

SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data

Cursor cursor = db.query(TABLE_NAME, new String[]{"*"}, "eventtitle=?", new


String[]{String.valueOf(eventtitle)}, null, null, null, null);

if (cursor != null) {
if (cursor.moveToFirst()) {
arrData = new String[cursor.getColumnCount()];
arrData[0] = cursor.getString(0);
arrData[1] = cursor.getString(1);
arrData[2] = cursor.getString(2);
}
}
cursor.close();
db.close();
return arrData;

} catch (Exception e) {
return null;
}

public Cursor getAll() {

// Select All Query


String selectQuery = "SELECT * FROM " + TABLE_NAME;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

return cursor;
}
/* public Cursor UpdateData(String evt,String ss) {
//update eventlist set venue = 'Thane' where id = 2
String getevt = " \"" + evt + "\" ";
String uptodo = " \"" + ss + "\" ";
String strSQL = "UPDATE "+TABLE_NAME+" SET todolist = "+uptodo+" WHERE
eventtitle = "+getevt ;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(strSQL, null);

return cursor;

60
}*/

public Cursor getlist(String title) {

// Select All Query


String s = " \"" + title + "\" ";
String selectQuery = "SELECT guestlist FROM eventlist where eventtitle = " + s;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

return cursor;
}

public Cursor gettodolist(String title) {

// Select All Query


String s = " \"" + title + "\" ";
String selectQuery = "SELECT todolist FROM todolist where eventtitle = " + s;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

return cursor;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

// Re Create on method onCreate


onCreate(db);
}

public void deletefun(String title) {


//Open the database
SQLiteDatabase database = this.getWritableDatabase();

//Execute sql query to remove from database


//NOTE: When removing by String in SQL, value must be enclosed with ''
database.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " +
"producttitle" + "= '" + title + "'");

//Close the database


database.close();
}

61
.
mainactivity java
package sss.example.com.safedrive;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class MainActivity extends AppCompatActivity implements


GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
EditText km;
TextView imnot;
Button update;
LocationManager locationManager;
boolean GpsStatus;
Location mLastLocation;
String lat, lon;
private AbsoluteSizeSpan sizeSpanLarge = null;
private AbsoluteSizeSpan sizeSpanSmall = null;
private double speed = 0.0;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public static myDBClass myDb;

62
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new myDBClass(getApplicationContext());
CheckGpsStatus();
km = (EditText) findViewById(R.id.speed);
imnot = (TextView) findViewById(R.id.text2);
km = (EditText) findViewById(R.id.speed);

imnot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent ii = new Intent(MainActivity.this,Start.class);
startActivity(ii);
finish();
}
});
if(SharedPreference.contains("km")){
km.setText(SharedPreference.get("km"));
}else{
Toast.makeText(this, "empty", Toast.LENGTH_SHORT).show();
}

update = (Button) findViewById(R.id.update);


update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreference.save("km", km.getText().toString());
}
});
if (GpsStatus == true) {
Toast.makeText(this, "Location Services Is Enabled",
Toast.LENGTH_SHORT).show();

} else {
Toast.makeText(this, "Location Services Is DisEnabled",
Toast.LENGTH_SHORT).show();
}

LocationManager lm = (LocationManager)
getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;

try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}

63
try {
network_enabled =
lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}

if (!gps_enabled && !network_enabled) {


// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setMessage("gps_network_not_enabled");
dialog.setPositiveButton("open setting", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(myIntent);

}
});
dialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub

}
});
dialog.show();
}
SharedPreference.initialize(getApplicationContext());
// startService(new Intent(SpeedCalc.this, MyService.class));
startService(new Intent(MainActivity.this, IncomingCallReceiver.class));
buildGoogleApiClient();
Intent intent = getIntent();
Bundle b = intent.getExtras();
TextView tv = (TextView) findViewById(R.id.txtmessage);
// int count =0;
if (b != null) {
tv.setText(b.getString("number"));
}
/* if(count>3){
Toast.makeText(this, "Your Friend Calling you plz reply",
Toast.LENGTH_SHORT).show();
}else{
if (b != null) {
tv.setText(b.getString("number"));
}

64
++count;
}
*/
}

@Override
public void onConnected(Bundle bundle) {

mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lon = String.valueOf(mLastLocation.getLongitude());

}
updateUI();
}

@Override
public void onConnectionSuspended(int i) {

@Override
public void onLocationChanged(Location location) {
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());

speed = location.getSpeed();
double speedKPH = convertSpeed(speed);

if (speedKPH > 20.0) {


Toast.makeText(this, "Car is running state", Toast.LENGTH_SHORT).show();
imnot.setText("Driving a car");

} else if (speedKPH == 0) {
Toast.makeText(this, "Car is steady state", Toast.LENGTH_SHORT).show();
imnot.setText("I am not driving");
}

String speedString = "" + roundDecimal(convertSpeed(speed), 2);

65
String unitString = measurementUnitString(0);

setSpeedText(R.id.textView3, speedString + " " + unitString);


//if(speedString)
Log.i("Speed", speedString);
updateUI();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}

synchronized void buildGoogleApiClient() {


mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();

@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}

@Override
protected void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}

void updateUI() {
Log.i("cor", "lat:-" + lat + "long" + lon);

private double roundDecimal(double value, final int decimalPlace) {


BigDecimal bd = new BigDecimal(value);

bd = bd.setScale(decimalPlace, RoundingMode.HALF_UP);
value = bd.doubleValue();

return value;
}

private double convertSpeed(double speed) {

66
return ((speed * Constants.HOUR_MULTIPLIER) *
Constants.UNIT_MULTIPLIERS[0]);
}

private String measurementUnitString(int unitIndex) {


String string = "";

switch (unitIndex) {
case Constants.INDEX_KM:
string = "km/h";
break;
case Constants.INDEX_MILES:
string = "mi/h";
break;
}

return string;
}

private void setSpeedText(int textid, String text) {


Spannable span = new SpannableString(text);
int firstPos = text.indexOf(32);

span.setSpan(sizeSpanLarge, 0, firstPos,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(sizeSpanSmall, firstPos + 1, text.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TextView tv = ((TextView) findViewById(textid));

tv.setText(span);
}

public void CheckGpsStatus() {

locationManager = (LocationManager)
getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
}

67
incomingcallreciever.java

package sss.example.com.safedrive;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.media.AudioManager;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;

import static android.content.Context.TELEPHONY_SERVICE;


import static sss.example.com.safedrive.MainActivity.myDb;
import static sss.example.com.safedrive.Setting.cb;

public class IncomingCallReceiver extends BroadcastReceiver implements


GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {

ArrayList ar = new ArrayList();


int count;
Context context;
Location mLastLocation;
String lat, lon;
String incomingNumber = "";
AudioManager audioManager;

68
TelephonyManager telephonyManager;
private AbsoluteSizeSpan sizeSpanLarge = null;
private AbsoluteSizeSpan sizeSpanSmall = null;
private double speed = 0.0;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

public void onReceive(Context context, Intent intent) {


SharedPreference.initialize(context);
audioManager = (AudioManager)
context.getSystemService(Context.AUDIO_SERVICE);

telephonyManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
incomingNumber =
intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.i("counter", incomingNumber);

myDb.insert(incomingNumber);

}
}

if (!incomingNumber.equals("")) {

ContentResolver cr = context.getContentResolver();
Cursor numbers =
cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new
String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.NUMBER + "=?", new
String[]{incomingNumber}, null);

Log.i("count of calls", ar.size() + "");


Cursor c = myDb.getAll();
Log.i("====>",c.getCount()+"");
if (c.getCount() < 6) {
Log.i("true","count is greate than 7");
rejectCall(context, intent);
rejectCall();

SmsManager smsManager = SmsManager.getDefault();


smsManager.sendTextMessage(incomingNumber, null, "I am driving,I will call
you later.", null, null);

/* if (SharedPreference.get("key").equals("1")) {
audioManager.setStreamMute(AudioManager.STREAM_RING, true);

69
Toast.makeText(context, "stop car", Toast.LENGTH_SHORT).show();
} else {
//SmsManager smsManager = SmsManager.getDefault();
//smsManager.sendTextMessage(incomingNumber, null, "User is driving", null,
null);
rejectCall(context, intent);
rejectCall();
}*/
}
else{

Log.i("false","count is smaller than 7 means call noth came");


}

//rejectCall(context,intent);

// startApp(context, incomingNumber);

/* private void startApp(Context context, String number) {


Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("number", "Rejected " + number);
context.startActivity(intent);
}*//* private void startApp(Context context, String number) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("number", "Rejected " + number);
context.startActivity(intent);
}*/

private void rejectCall() {

try {

Class<?> classTelephony =
Class.forName(telephonyManager.getClass().getName());
Method method = classTelephony.getDeclaredMethod("getITelephony");

method.setAccessible(true);

Object telephonyInterface = method.invoke(telephonyManager);

70
Class<?> telephonyInterfaceClass =
Class.forName(telephonyInterface.getClass().getName());
Method methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall");

methodEndCall.invoke(telephonyInterface);
} catch (Exception e) {

e.printStackTrace();
}

private void rejectCall(Context context, Intent intent)

{
Bundle myBundle = intent.getExtras();
if (myBundle != null) {
System.out.println("--------Not null-----");
try {
if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
System.out.println("--------in state-----");
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
// Incoming call
String incomingNumber =
intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
System.out.println("--------------my number---------" + incomingNumber);

ar.add(incomingNumber);
// this is main section of the code,. could also be use for particular number.
// Get the boring old TelephonyManager.
TelephonyManager telephonyManager = (TelephonyManager)
context.getSystemService(TELEPHONY_SERVICE);

// Get the getITelephony() method


Class<?> classTelephony =
Class.forName(telephonyManager.getClass().getName());
Method methodGetITelephony =
classTelephony.getDeclaredMethod("getITelephony");

// Ignore that the method is supposed to be private


methodGetITelephony.setAccessible(true);

// Invoke getITelephony() to get the ITelephony interface


/*Object telephonyInterface =
methodGetITelephony.invoke(telephonyManager);

// Get the endCall method from ITelephony


Class<?> telephonyInterfaceClass =

71
Class.forName(telephonyInterface.getClass().getName());
Method methodEndCall =
telephonyInterfaceClass.getDeclaredMethod("endCall");

// Invoke endCall()
methodEndCall.invoke(telephonyInterface);*/

TelephonyManager tm = (TelephonyManager)
context.getSystemService(TELEPHONY_SERVICE);

Method m1 = tm.getClass().getDeclaredMethod("getITelephony");
m1.setAccessible(true);
Object iTelephony = m1.invoke(tm);

Method m2 = iTelephony.getClass().getDeclaredMethod("silenceRinger");
Method m3 = iTelephony.getClass().getDeclaredMethod("endCall");

m2.invoke(iTelephony);
m3.invoke(iTelephony);
}

}
} catch (Exception ex) { // Many things can go wrong with reflection calls
ex.printStackTrace();
}
}

@Override
public void onConnected(Bundle bundle) {

mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lon = String.valueOf(mLastLocation.getLongitude());

}
updateUI();
}

72
@Override
public void onConnectionSuspended(int i) {

@Override
public void onLocationChanged(Location location) {
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());

speed = location.getSpeed();
double speedKPH = convertSpeed(speed);

if (speedKPH > 20.0) {


Toast.makeText(context, "Car is running state", Toast.LENGTH_SHORT).show();
SharedPreference.save("key", "1");

} else if (speedKPH == 0) {
Toast.makeText(context, "Car is steady state", Toast.LENGTH_SHORT).show();
SharedPreference.save("key", "0");
}

String speedString = "" + roundDecimal(convertSpeed(speed), 2);


String unitString = measurementUnitString(0);

setSpeedText(R.id.textView3, speedString + " " + unitString);


//if(speedString)
Log.i("Speed", speedString);
updateUI();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}

synchronized void buildGoogleApiClient() {


mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();

protected void onStart() {

mGoogleApiClient.connect();

73
}

protected void onDestroy() {

mGoogleApiClient.disconnect();
}

void updateUI() {
Log.i("cor", "lat:-" + lat + "long" + lon);

private double roundDecimal(double value, final int decimalPlace) {


BigDecimal bd = new BigDecimal(value);

bd = bd.setScale(decimalPlace, RoundingMode.HALF_UP);
value = bd.doubleValue();

return value;
}

private double convertSpeed(double speed) {


return ((speed * Constants.HOUR_MULTIPLIER) *
Constants.UNIT_MULTIPLIERS[0]);
}

private String measurementUnitString(int unitIndex) {


String string = "";

switch (unitIndex) {
case Constants.INDEX_KM:
string = "km/h";
break;
case Constants.INDEX_MILES:
string = "mi/h";
break;
}

return string;
}

private void setSpeedText(int textid, String text) {


Spannable span = new SpannableString(text);
int firstPos = text.indexOf(32);

span.setSpan(sizeSpanLarge, 0, firstPos,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(sizeSpanSmall, firstPos + 1, text.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

74
}

interface ITelephony {

boolean endCall();

void answerRingingCall();

void silenceRinger();

}
}

constant java.
package sss.example.com.safedrive;

public interface Constants


{
public static final int TEXT_SIZE_SMALL = 15;
public static final int TEXT_SIZE_LARGE = 80;
public static final int INDEX_KM = 0;
public static final int INDEX_MILES = 1;
public static final int DEFAULT_SPEED_LIMIT = 80;
public static final int HOUR_MULTIPLIER = 3600;
public static final double UNIT_MULTIPLIERS[] = { 0.001, 0.000621371192 };

75
8.SCREEN LAYOUT
WITH TEST DATA AND
TEST RESULTS

76
1.HOMEPAGE

77
2.DRIVEMODE PAGE

78
3.SETTINGS PAGE

79
4. DRIVING GUIDE PAGE

80
5. ABOUT APP PAGE

81
9. REFRENCES/
BIBLOGRAPHY

82
References:

Beginning Android
Android Programming: The Big Nerd Ranch Guide

Website:

www.google.com
www.developer.android.com
www.stackoverflow.com
www.codeproject.com
www.udemy.com

83

S-ar putea să vă placă și