You are on page 1of 15

ARDUINO SWITCHING if (readString == "C") //Text from

android {
String readString;
digitalWrite(6,LOW); }
void setup(){
if (readString == "c") //Text from
Serial.begin(9600); android {

pinMode(4, OUTPUT);//Ignition digitalWrite(6,HIGH); }

pinMode(5, OUTPUT);//Push Start readString="";

pinMode(6, OUTPUT);//Sparkplug }}

digitalWrite(4,HIGH); ARDUINO GPS MODULE


digitalWrite(5,HIGH);
#include <DFRobot_sim808.h>
digitalWrite(6,HIGH);}
#include <SoftwareSerial.h>
void loop() {

while (Serial.available()) {
#define MESSAGE_LENGTH 160
delay(3);
char message[MESSAGE_LENGTH];
char c = Serial.read();
int messageIndex = 0;
readString += c; }
char MESSAGE[300];
if (readString.length() >0) {
char lat[12];
Serial.println(readString);
char lon[12];
if (readString == "A") //Text from
char wspeed[12];
android {

digitalWrite(4,LOW); }
char phone[16];
if (readString == "a") //Text from
android { char datetime[24];

digitalWrite(4,HIGH); }

if (readString == "B") //Text from #define PIN_TX 10


android {
#define PIN_RX 11
digitalWrite(5,LOW); }
SoftwareSerial mySerial(PIN_TX,PIN_RX);
if (readString == "b") //Text from
DFRobot_SIM808
android {
sim808(&mySerial);//Connect RX,TX,PWR,
digitalWrite(5,HIGH);

}
String readString;
void sendSMS();

void getGPS(); //*********** Detecting unread SMS


************************
void readSMS();
messageIndex = sim808.isSMSunread();

//*********** At least, there is one


void setup()
UNREAD SMS ***********
{
if (messageIndex > 0)
mySerial.begin(9600);
{
Serial.begin(9600);

readSMS();

getGPS();
//******** Initialize sim808 module
sendSMS();
*************

while(!sim808.init())
//************* Turn off the GPS
{
power ************
Serial.print("Sim808 init error\r\n");
sim808.detachGPS();
delay(10);

Serial.println("Please send SMS


message to me!");

} }

delay(50);
}

Serial.println("SIM Init success");


void readSMS()

Serial.println("Init Success, please send {


SMS message to me!");
Serial.print("messageIndex: ");
}
Serial.println(messageIndex);

void loop()
sim808.readSMS(messageIndex,
{ message, MESSAGE_LENGTH, phone,
datetime);
//***********In order not to full SIM }
Memory, is better to delete it**********

sim808.deleteSMS(messageIndex);

Serial.print("From number: ");


Serial.print(sim808.GPSdata.year);
Serial.println(phone);
Serial.print("/");
Serial.print("Datetime: ");
Serial.print(sim808.GPSdata.month);
Serial.println(datetime);
Serial.print("/");
Serial.print("Recieved Message: ");
Serial.print(sim808.GPSdata.day);
Serial.println(message);
Serial.print(" ");

Serial.print(sim808.GPSdata.hour);

Serial.print(":");

Serial.print(sim808.GPSdata.minute);

Serial.print(":");
}
Serial.print(sim808.GPSdata.second);

Serial.print(":");
void getGPS()

{ Serial.println(sim808.GPSdata.centisecond
);
while(!sim808.attachGPS())
Serial.print("latitude :");
{
Serial.println(sim808.GPSdata.lat);
Serial.println("Open the GPS power
failure"); Serial.print("longitude :");

delay(1000); Serial.println(sim808.GPSdata.lon);

} Serial.print("speed_kph :");

delay(3000);
Serial.println(sim808.GPSdata.speed_kph)
;
Serial.println("Open the GPS power
Serial.print("heading :");
success");

Serial.println(sim808.GPSdata.heading);
while(!sim808.getGPS())
Serial.println();
{
float la = sim808.GPSdata.lat; Serial.println(phone);

float lo = sim808.GPSdata.lon;

float ws = sim808.GPSdata.speed_kph; sim808.sendSMS(phone,MESSAGE);

dtostrf(la, 6, 2, lat); //put float value of }


la into char array of lat. 6 = number of
digits before decimal sign. 2 = number of
digits after the decimal sign.
ANDROID STUDIO DESIGN
dtostrf(lo, 6, 2, lon); //put float value
of lo into char array of lon <?xml version="1.0" encoding="utf-
8"?>
<android.support.constraint.Constra
dtostrf(ws, 6, 2, wspeed); //put float intLayout
value of ws into char array of wspeed xmlns:android="http://schemas.andro
id.com/apk/res/android"

xmlns:app="http://schemas.android.c
om/apk/res-auto"

xmlns:tools="http://schemas.android
.com/tools"
android:id="@+id/layout"
sprintf(MESSAGE, "Latitude :
%s\nLongitude : %s\nWind Speed : %s android:layout_width="match_parent"
kph\nhttp://www.latlong.net/Show-
android:layout_height="match_parent
Latitude-Longitude.html", lat, lon, "
wspeed);
android:background="@drawable/bgwht
e"
android:orientation="vertical"
//sprintf(MESSAGE, "Latitude : android:visibility="visible"
%s\nLongitude : %s\nWind Speed : %s tools:context="com.exclikers.homeau
kph\nhttp://maps.google.com/maps?q= tomationsystem.MainActivity"
%s,%s\n",lat, lon, wspeed,lat, lon);
tools:layout_editor_absoluteX="0dp"

tools:layout_editor_absoluteY="81dp
">

<ToggleButton
}
android:id="@+id/toggleButton1"

android:layout_width="100dp"
void sendSMS()
android:layout_height="50dp"
{
android:layout_marginBottom="453dp"
Serial.println("Start to send message ...");
android:layout_marginLeft="155dp"

android:background="@drawable/toggl
Serial.println(MESSAGE); e_switch"
android:text="ToggleButton"
android:textOff=""
android:textOn="" android:textOff=""
android:textOn=""
app:layout_constraintBottom_toBotto
mOf="parent" app:layout_constraintBottom_toBotto
mOf="parent"
app:layout_constraintLeft_toLeftOf=
"parent" app:layout_constraintLeft_toLeftOf=
"parent"
android:layout_marginTop="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf
="@+id/textView1" app:layout_constraintTop_toBottomOf
="@+id/toggleButton2"
app:layout_constraintVertical_bias=
"0.0" /> app:layout_constraintVertical_bias=
"1.0" />
<ToggleButton
<TextView
android:id="@+id/toggleButton2" android:id="@+id/textView"

android:layout_width="100dp" android:layout_width="wrap_content"

android:layout_height="50dp" android:layout_height="wrap_content
"
android:layout_marginBottom="319dp" android:text="Device
Controls"
android:layout_marginLeft="155dp"
android:textColor="@android:color/h
android:background="@drawable/toggl olo_green_dark"
e_switch" android:textSize="20sp"
android:text="ToggleButton" android:textStyle="bold"
android:textOff=""
android:textOn="" app:layout_constraintLeft_toLeftOf=
"parent"
app:layout_constraintBottom_toBotto
mOf="parent" app:layout_constraintRight_toRightO
f="parent"
app:layout_constraintLeft_toLeftOf=
"parent" app:layout_constraintTop_toTopOf="p
arent"
android:layout_marginTop="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf
="@+id/textView2" app:layout_constraintHorizontal_bia
s="0.498" />
app:layout_constraintVertical_bias=
"0.071" /> <TextView
android:id="@+id/textView1"
<ToggleButton
android:layout_width="wrap_content"
android:id="@+id/toggleButton3"
android:layout_height="wrap_content
android:layout_width="250dp" "
android:text="Connect
Device"
android:layout_height="80dp"
android:textColor="@android:color/h
android:layout_marginBottom="218dp"
olo_orange_light"
android:textSize="15sp"
android:layout_marginLeft="80dp" android:textStyle="bold"
android:background="@drawable/engin app:layout_constraintLeft_toLeftOf=
eoff" "parent"
android:text="ToggleButton"
app:layout_constraintRight_toRightO <ImageView
f="parent" android:id="@+id/splash"

android:layout_marginTop="55dp" android:layout_width="100dp"

app:layout_constraintHorizontal_bia android:layout_height="100dp"
s="0.498"
android:background="@drawable/splas
app:layout_constraintTop_toBottomOf h_img" />
="@+id/textView" />
</LinearLayout>
<TextView
android:id="@+id/textView2"
<?xml version="1.0" encoding="utf-
android:layout_width="wrap_content" 8"?>
<android.support.constraint.Constra
android:layout_height="wrap_content intLayout
" xmlns:android="http://schemas.andro
android:text="Activate id.com/apk/res/android"
Security"
xmlns:app="http://schemas.android.c
android:textColor="@android:color/h om/apk/res-auto"
olo_orange_light"
android:textSize="15sp" xmlns:tools="http://schemas.android
android:textStyle="bold" .com/tools"

app:layout_constraintLeft_toLeftOf= android:layout_width="match_parent"
"parent"
android:layout_height="match_parent
app:layout_constraintRight_toRightO "
f="parent"
android:background="@drawable/bgwht
android:layout_marginTop="17dp" e">

app:layout_constraintHorizontal_bia <WebView
s="0.498"
android:layout_width="395dp"
app:layout_constraintTop_toBottomOf
="@+id/toggleButton1" /> android:layout_height="587dp"
android:id="@+id/webview"

</android.support.constraint.Constr app:layout_constraintTop_toTopOf="p
aintLayout> arent"

android:layout_marginTop="8dp"
<?xml version="1.0" encoding="utf- android:layout_marginLeft="8dp"
8"?>
<LinearLayout
app:layout_constraintLeft_toLeftOf=
xmlns:android="http://schemas.andro
"parent"
id.com/apk/res/android"
android:layout_marginRight="8dp"
android:layout_width="fill_parent"
app:layout_constraintRight_toRightO
android:layout_height="fill_parent"
f="parent">
android:background="@drawable/splas </WebView>
h"
android:layout_gravity="center"
android:id="@+id/lin_lay"
android:gravity="center"
android:orientation="vertical" </android.support.constraint.Constr
> aintLayout>
<?xml version="1.0" encoding="utf-
8"?> android:layout_centerHorizontal="tr
<RelativeLayout ue" />
xmlns:android="http://schemas.andro
id.com/apk/res/android" <Button
android:id="@+id/btnExit"
xmlns:tools="http://schemas.android android:layout_width="80dp"
.com/tools"
android:layout_height="80dp"
android:layout_width="match_parent"
android:layout_alignParentBottom="t
android:layout_height="match_parent rue"
"
android:layout_alignParentEnd="true
android:animateLayoutChanges="false "
"
android:animationCache="false" android:layout_alignParentRight="tr
ue"
android:background="@drawable/hb"
android:orientation="vertical" android:layout_marginBottom="23dp"
tools:animationCache="false"
android:layout_marginEnd="42dp"
tools:context="com.exclikers.homeau
tomationsystem.HomeScreen"> android:layout_marginRight="42dp"

android:background="@drawable/exit"
<ToggleButton
android:id="@+id/btnStart"
android:onClick="exitClickButton" /
>
android:layout_width="200dp"
<Button
android:layout_height="60dp" android:id="@+id/btnHelp"
android:layout_width="80dp"
android:layout_marginTop="137dp"
android:layout_height="80dp"
android:background="@drawable/switc
h_start" android:layout_alignParentBottom="t
rue"
android:onClick="homeClickButton"
android:textOff="" android:layout_alignParentLeft="tru
android:textOn="" e"

android:layout_alignParentTop="true android:layout_alignParentStart="tr
" ue"

android:layout_centerHorizontal="tr android:layout_marginBottom="24dp"
ue" />
android:layout_marginLeft="42dp"
<Button
android:id="@+id/btnTrack"
android:layout_marginStart="42dp"
android:layout_width="200dp"
android:background="@drawable/help"
android:onClick="btnhelp"
android:layout_height="90dp" />

android:layout_marginTop="93dp"

android:background="@drawable/track <TextView
" android:id="@+id/setGPS"

android:onClick="trackbutton" android:layout_width="wrap_content"

android:layout_below="@+id/btnStart android:layout_height="wrap_content
" "
android:text="Set GPS }
Number" /** Called when the activity is
first created. */
android:textColor="@android:color/h Thread splashTread;
olo_orange_light" @Override
android:textSize="15sp" public void onCreate(Bundle
android:textStyle="bold" savedInstanceState) {
android:onClick="btnGPS"
super.onCreate(savedInstanceState);
android:layout_below="@+id/btnTrack
" setContentView(R.layout.activity_sp
lashscreen);
android:layout_centerHorizontal="tr StartAnimations();
ue" /> }
private void StartAnimations()
{
Animation anim =
AnimationUtils.loadAnimation(this,
</RelativeLayout> R.anim.alpha);
anim.reset();
LinearLayout
l=(LinearLayout)
findViewById(R.id.lin_lay);
SPLASH SCREEN l.clearAnimation();
l.startAnimation(anim);
package
com.exclikers.homeautomationsystem; anim =
AnimationUtils.loadAnimation(this,
import android.app.Activity; R.anim.translate);
import android.content.Intent; anim.reset();
import ImageView iv = (ImageView)
android.graphics.PixelFormat; findViewById(R.id.splash);
import android.os.Bundle; iv.clearAnimation();
import android.view.Window; iv.startAnimation(anim);
import
android.view.animation.Animation; splashTread = new Thread()
import {
android.view.animation.AnimationUti @Override
ls; public void run() {
import android.widget.ImageView; try {
import android.widget.LinearLayout; int waited = 0;
// Splash
import android.app.Activity; screen pause time
import android.content.Intent; while (waited <
import 3500) {
android.graphics.PixelFormat; sleep(100);
import android.os.Bundle; waited +=
import android.view.Window; 100;
import }
android.view.animation.Animation; Intent intent =
import new Intent(Splashscreen.this,
android.view.animation.AnimationUti
ls; HomeScreen.class);
import android.widget.ImageView;
import android.widget.LinearLayout; intent.setFlags(Intent.FLAG_ACTIVIT
Y_NO_ANIMATION);
public class Splashscreen extends
Activity {
startActivity(intent);
public void
onAttachedToWindow() {
super.onAttachedToWindow(); Splashscreen.this.finish();
Window window = } catch
getWindow(); (InterruptedException e) {
// do nothing
} finally {
window.setFormat(PixelFormat.RGBA_8
888);
Splashscreen.this.finish();
} HOME SCREEN
} package
}; com.exclikers.homeautomationsystem;
splashTread.start();
import android.*;
} import android.Manifest;
import android.app.Activity;
} import android.app.AlertDialog;
import
android.app.assist.AssistStructure;
import android.content.Context;
import
android.content.DialogInterface;
DEVICES import android.content.Intent;
import
package android.content.SharedPreferences;
com.exclikers.homeautomationsystem; import
android.content.pm.PackageManager;
import android.os.Bundle;
import
import android.os.Bundle; android.support.annotation.Nullable
;
import
import android.app.Activity; android.support.v4.app.ActivityComp
import android.webkit.WebView; at;
import
android.support.v4.content.ContextC
public class Devices extends ompat;
Activity { import
android.telephony.SmsManager;
WebView webview; import android.text.InputFilter;
import android.text.InputType;
import android.view.View;
@Override import android.widget.Button;
public void onCreate(Bundle import android.widget.EditText;
savedInstanceState) { import android.widget.TextView;
import android.widget.Toast;
super.onCreate(savedInstanceState);

setContentView(R.layout.devices_nex
t); import static
com.exclikers.homeautomationsystem.
R.id.btnStart;
webview = (WebView)
findViewById(R.id.webview); /**
* Created by Exclikeras on
webview.getSettings().setBuiltInZoo 3/21/2017.
mControls(true); */

webview.loadUrl("file:///android_as public class HomeScreen extends


set/index.htm"); Activity {

} TextView setGPS;

@Override
} protected void onCreate(Bundle
savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen InputFilter[] { new
); InputFilter.LengthFilter(20)});
builder.setView(input);
setGPS = (TextView)
findViewById(R.id.setGPS); // Set up the buttons

builder.setPositiveButton("SAVE",
/* new
btnremote.setOnClickListener(new DialogInterface.OnClickListener() {
View.OnClickListener() { @Override
public void public void
onClick(View v) { onClick(DialogInterface dialog, int
which) {
*//*sendData("LEDOFF"); //m_Text =
input.getText().toString();
Toast.makeText(getBaseContext(), SharedPreferences
"Turn off LED", sharedPreferences=getSharedPreferen
Toast.LENGTH_SHORT).show();*//* ces("SavedData",
Intent i = new Context.MODE_PRIVATE);
Intent(HomeScreen.this,
Devices.class); SharedPreferences.Editor
startActivity(i); editor=sharedPreferences.edit();

} editor.putString("gpsno",m_Text =
});*/ input.getText().toString());
} editor.commit();

public void Toast.makeText(HomeScreen.this,"Sav


homeClickButton(View v) ed!",Toast.LENGTH_LONG).show();
{ //
/* if (v.getId() == setGPS.setText(m_Text);
R.id.btnStart)
{*/
Intent i = new }
Intent(HomeScreen.this, });
MainActivity.class);
startActivity(i); builder.setNegativeButton("Cancel",
// } new
DialogInterface.OnClickListener() {
} @Override
public void
onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
private String m_Text = "";
builder.show();
public void btnGPS (View view)
{ }
AlertDialog.Builder builder
= new AlertDialog.Builder(this);
builder.setTitle("Enter GPS
Mobile Number:");

// Set up the input


final EditText input = new int
EditText(this); MY_PERMISSIONS_REQUEST_SEND_SMS =
// Specify the type of 1;
input expected; this, for example,
sets the input as a password, and public void trackbutton(View v)
will mask the text {
SharedPreferences
input.setInputType(InputType.TYPE_C sharedPreferences=getSharedPreferen
LASS_TEXT); ces("SavedData",Context.MODE_PRIVAT
input.setFilters(new
E); AlertDialog.Builder(HomeScreen.this
String telNr = );
sharedPreferences.getString("gpsno" builder.setMessage("Do you
,""); want to exit?");
String message = "Request
GPS Location"; builder.setCancelable(true);
//String telNr =
"09108727748"; builder.setPositiveButton("Ok", new
DialogInterface.OnClickListener() {
if @Override
(ContextCompat.checkSelfPermission( public void
this, Manifest.permission.SEND_SMS) onClick(DialogInterface dialog, int
!= id) {
PackageManager.PERMISSION_GRANTED) finish();
{
}
ActivityCompat.requestPermissions(t });
his, new String[]
{Manifest.permission.SEND_SMS}, builder.setNegativeButton("Cancel",
new
MY_PERMISSIONS_REQUEST_SEND_SMS); DialogInterface.OnClickListener() {
} @Override
else public void
{ onClick(DialogInterface dialog, int
if (telNr.equals("")){ id) {
dialog.cancel();
Toast.makeText(HomeScreen.this,"Ple }
ase set GPS sim });
number!",Toast.LENGTH_LONG).show(); AlertDialog alert =
} builder.create();
else alert.show();
{ }
SmsManager sms =
SmsManager.getDefault(); public void onBackPressed(){
AlertDialog.Builder builder
sms.sendTextMessage(telNr, null, = new
message, null, null); AlertDialog.Builder(HomeScreen.this
);
Toast.makeText(HomeScreen.this, builder.setMessage("Do you
"GPS Location Requested!", want to exit?");
Toast.LENGTH_SHORT).show();
} builder.setCancelable(true);
}
} builder.setPositiveButton("Ok", new
DialogInterface.OnClickListener() {
@Override
public void
public void btnhelp(View v) onClick(DialogInterface dialog, int
{ id) {
finish();
Intent i = new }
Intent(HomeScreen.this, });
Devices.class);
startActivity(i); builder.setNegativeButton("Cancel",
new
DialogInterface.OnClickListener() {
} @Override
public void
onClick(DialogInterface dialog, int
id) {
public void dialog.cancel();
exitClickButton(View v) }
{ });
AlertDialog.Builder builder AlertDialog alert =
= new builder.create();
alert.show(); private static final String TAG
} = "bluetooth";

ToggleButton t1, t2, t3, t4,


t5, t6, t7, t8;
// ConstraintLayout
} devicescreen, remotescreen,
remotebuttons, dvdbuttons,
projectorbuttons, airconbuttons;

MAIN ACTIVITY
private BluetoothAdapter
package btAdapter = null;
com.exclikers.homeautomationsystem; private BluetoothSocket
btSocket = null;
private OutputStream outStream
import android.app.AlertDialog; = null;
import android.content.Context;
import // SPP UUID service
android.content.DialogInterface; private static final UUID
import MY_UUID =
android.content.SharedPreferences; UUID.fromString("00001101-0000-
import android.os.Bundle; 1000-8000-00805F9B34FB");
import java.io.IOException;
import java.io.OutputStream; // MAC-address of Bluetooth
import java.lang.reflect.Method; module (you must edit this line)
import java.util.UUID; private static String address =
"98:D3:31:F5:9E:6B";
import android.app.Activity;
import
android.bluetooth.BluetoothAdapter; /**
import * Called when the activity is
android.bluetooth.BluetoothDevice; first created.
import */
android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import // TextView btnlight1,
android.support.constraint.Constrai btnlight2, btnlight3, btnlight4,
ntLayout; btndevice1, btndevice2, btndevice3,
import android.text.InputFilter; btndevice4;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import @Override
android.view.View.OnClickListener; public void onCreate(Bundle
import android.widget.AdapterView; savedInstanceState) {
import android.widget.ArrayAdapter;
import android.widget.Button; super.onCreate(savedInstanceState);
import android.widget.EditText;
import android.widget.ListView; setContentView(R.layout.activity_ma
import android.widget.TextView; in);
import android.widget.Toast;
import android.widget.ToggleButton; t1 = (ToggleButton)
findViewById(R.id.toggleButton1);
import static t2 = (ToggleButton)
android.view.View.INVISIBLE; findViewById(R.id.toggleButton2);
import static t3 = (ToggleButton)
android.view.View.VISIBLE; findViewById(R.id.toggleButton3);

public class MainActivity extends t3.setOnTouchListener(btnTouch);


Activity {
t1.setOnClickListener(new
View.OnClickListener() { @Override
@Override public void
public void onClick(View v) {
onClick(View v) { if (t3.isChecked())
if (t1.isChecked()) {
{ sendData("C");
sendData("A"); } else {
sendData("c");
Toast.makeText(MainActivity.this, }
"Device Connected!", }
Toast.LENGTH_SHORT).show(); });
} else { */
sendData("a");

Toast.makeText(MainActivity.this,
"Device Disconnected!",
Toast.LENGTH_SHORT).show();
}
}
}); btAdapter =
BluetoothAdapter.getDefaultAdapter(
t2.setOnClickListener(new );
View.OnClickListener() { checkBTState();
@Override
public void
onClick(View v) {
if (t2.isChecked())
{
sendData("B"); }

Toast.makeText(MainActivity.this,
"Security On!",
Toast.LENGTH_SHORT).show();
} else {
sendData("b");
private View.OnTouchListener
Toast.makeText(MainActivity.this,
btnTouch = new
"Security Off!",
View.OnTouchListener() {
Toast.LENGTH_SHORT).show();
@Override
}
public boolean onTouch(View
}
v, MotionEvent event) {
});
int action =
/*
event.getAction();
t3.setOnClickListener(new
if (action ==
View.OnClickListener() {
MotionEvent.ACTION_DOWN)
public void
sendData("C");
onClick(View view) {
else if (action ==
MotionEvent.ACTION_UP)
makethisToastup();}}); sendData("c");
t3.setOnTouchListener(new return false; // the
View.OnTouchListener() { listener has NOT consumed the
public boolean event, pass it on
onTouch(View view, MotionEvent }
event) { };
makethisToastdown(); /*
return false; public void makethisToastup(){
}}); sendData("C");
*/ }
public void makethisToastdown()
{
sendData("c");
/* }
t3.setOnClickListener(new */
View.OnClickListener() {
private BluetoothSocket "...Connecting...");
createBluetoothSocket(BluetoothDevi try {
ce device) throws IOException { btSocket.connect();
if (Build.VERSION.SDK_INT Log.d(TAG,
>= 10) { "...Connection ok...");
try { } catch (IOException e) {
final Method m = try {
device.getClass().getMethod("create btSocket.close();
InsecureRfcommSocketToServiceRecord } catch (IOException
", new Class[]{UUID.class}); e2) {
return errorExit("Fatal
(BluetoothSocket) m.invoke(device, Error", "In onResume() and unable
MY_UUID); to close socket during connection
} catch (Exception e) { failure" + e2.getMessage() + ".");
Log.e(TAG, "Could }
not create Insecure RFComm }
Connection", e);
} // Create a data stream so
} we can talk to server.
return Log.d(TAG, "...Create
device.createRfcommSocketToServiceR Socket...");
ecord(MY_UUID);
} try {
outStream =
@Override btSocket.getOutputStream();
public void onResume() { } catch (IOException e) {
super.onResume(); errorExit("Fatal
Error", "In onResume() and output
Log.d(TAG, "...onResume - stream creation failed:" +
try connect..."); e.getMessage() + ".");
}
// Set up a pointer to the }
remote node using it's address.
BluetoothDevice device = @Override
btAdapter.getRemoteDevice(address); public void onPause() {
super.onPause();
// Two things are needed to
make a connection: Log.d(TAG, "...In
// A MAC address, which onPause()...");
we got above.
// A Service ID or UUID. if (outStream != null) {
In this case we are using the try {
// UUID for SPP. outStream.flush();
} catch (IOException e)
try { {
btSocket =
createBluetoothSocket(device); errorExit("Bluetooth Error: ",
} catch (IOException e1) { "Make sure the bluetooth is on. ");
errorExit("Fatal }
Error", "In onResume() and socket }
create failed: " + e1.getMessage()
+ "."); try {
} btSocket.close();
} catch (IOException e2) {
// Discovery is resource errorExit("Fatal
intensive. Make sure it isn't Error", "In onPause() and failed to
going on close socket." + e2.getMessage() +
// when you attempt to ".");
connect and pass your message. }
}
btAdapter.cancelDiscovery();
private void checkBTState() {
// Establish the // Check for Bluetooth
connection. This will block until support and then check to make sure
it connects. it is turned on
Log.d(TAG, // Emulator doesn't support
Bluetooth and will return null
if (btAdapter == null) {
errorExit("Fatal /* @Override
Error", "Bluetooth not support"); public void
} else { onCheckedChanged(CompoundButton
if buttonView, boolean t1) {
(btAdapter.isEnabled()) {
Log.d(TAG, if(t1)
"...Bluetooth ON..."); {
} else {
//Prompt user to
turn on Bluetooth //r.setBackgroundColor(Color.BLACK)
Intent ;
enableBtIntent = new sendData("B");
Intent(BluetoothAdapter.ACTION_REQU
EST_ENABLE); Toast.makeText(getBaseContext(),
"Turn on LED",
startActivityForResult(enableBtInte Toast.LENGTH_SHORT).show();
nt, 1); }
} else
} {
}
//r.setBackgroundColor(Color.WHITE)
private void errorExit(String ;
title, String message) { sendData("b");

Toast.makeText(getBaseContext(), Toast.makeText(getBaseContext(),
title + " - " + message, "Turn off LED",
Toast.LENGTH_LONG).show(); Toast.LENGTH_SHORT).show();
finish(); }
}
}*/
private void sendData(String
message) {
byte[] msgBuffer =
message.getBytes();
}
Log.d(TAG, "...Send data: "
+ message + "...");

try {

outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "Please
check device's Bluetooth Module: "
+ e.getMessage();
if
(address.equals("00:00:00:00:00:00"
))
msg = msg +
".\n\nUpdate your server address
from 00:00:00:00:00:00 to the
correct address on line 35 in the
java code";
// msg = msg +
".\n\nCheck that the SPP UUID: " +
MY_UUID.toString() + " exists on
server.\n\n";

errorExit("Connection
Failed: ", msg);
}
}

You might also like