Activity 1 (This is where the list of linked devices is made)
package com.example.artur.micasav3;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
public class DispositivosBT extends AppCompatActivity {
//1)
// depuracion de LOGCAT
private static final String TAG = "DispositivosBT";
//DECLARACION DE LIST VIEW
ListView IdLista;
// String que se enviara a la actividad principal; ,ain activity
public static String EXTRA_DEVICE_ADDRES = "device_address";
// Declaracion de campos
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dispositivos_bt);
}
@Override
public void onResume() {
super.onResume();
VerificarEstadoBT();
//Inicializa la array que contandra la lista de los dispositivos bluetooth vinculados
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.nombre_dispositivos); //parte a modificar
// Presenta los dispositivos vinculasdos en LastView
IdLista = (ListView) findViewById(R.id.IdLista);
IdLista.setAdapter(mPairedDevicesArrayAdapter);
IdLista.setOnItemClickListener(mDeviceClickListener);
//Obtiene el adaptador local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
//Obtiene un conjunto de dsipositivos actualmente emparejados y los agrega a "pairedDevices"
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
//Adiciona un dispositivo previo emparejado al array
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
}
// Configura un (on-click) para la lista
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
//Obtener la direccion MAC del dispositivo, que son los ultimos 17 acaracteres en la...
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
//Realiza un intetnt para iniciar la siguiente actividad
//Mientras toma un EXTRA DEVICE ADDRESS que es la direccion MAC
Intent i = new Intent(DispositivosBT.this, MenuPrincipal.class); // Parte a modificar
i.putExtra(EXTRA_DEVICE_ADDRES, address);
startActivity(i);
}
};
private void VerificarEstadoBT() {
// Comprueba que el dispositivo tiene Bluetooth y esta encendido
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBtAdapter == null) {
Toast.makeText(getBaseContext(), "El dispositivo no soporta Bluetooth", Toast.LENGTH_SHORT).show();
} else {
if (mBtAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth Activado...");
} else {
//Solicita al usuario que active el Bluetooth
Intent eneableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(eneableBtIntent, 1);
}
}
}
}
Activity 2 (It is the main menu, where by means of a button I enter another activity)
package com.example.artur.micasav3;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.widget.ImageButton;
public class MenuPrincipal extends AppCompatActivity {
private TextView BufferIn, IdPorcentaje1, IdPorcentaje2, IdPorcentaje3;
ImageButton IdImageIluminacion;
Handler bluetoothIn;
final int handlerState = 0;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder DataStringIN = new StringBuilder();
private ConnectedThread MyConexionBT;
//Identificador unico de servicio - SPP UUID
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String para la direccion MAC
private static String address = null;
//-------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_principal);
IdImageIluminacion = (ImageButton) findViewById(R.id.IdImageIluminacion);
IdImageIluminacion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MenuPrincipal.this, Iluminacion.class);
startActivity(i);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
});
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
DataStringIN.append(readMessage);
int endOfLineIndex = DataStringIN.indexOf("#");
if (endOfLineIndex > 0) {
String dataInPrint = DataStringIN.substring(0, endOfLineIndex);
BufferIn.setText("Dato: " + dataInPrint); //parte a modificar
DataStringIN.delete(0, DataStringIN.length());
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
VerificarEstadoBT();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
//crea un conexion de salida segura para el dispositivo
//usando el servicio UUID
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}
@Override
public void onResume() {
super.onResume();
//Consigue la direccion MAC desde DeviceListActivity via intent
Intent intent = getIntent();
//Consigue la direccion MAC desde DeviceListActivity via EXTRA
address = intent.getStringExtra(DispositivosBT.EXTRA_DEVICE_ADDRES);
//Setea la direccion MAC
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "La creación del Socket fallo", Toast.LENGTH_LONG).show();
}
// Establece la conexión con el socket Bluetooth.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
MyConexionBT = new ConnectedThread(btSocket);
MyConexionBT.start();
}
@Override
public void onPause() {
super.onPause();
try { // Cuando se sale de la aplicación esta parte permite
// que no se deje abierto el socket
btSocket.close();
} catch (IOException e2) {
}
}
//Comprueba que el dispositivo Bluetooth Bluetooth está disponible y solicita que se active si está desactivado
private void VerificarEstadoBT() {
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "El dispositivo no soporta bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//Crea la clase que permite crear el evento de conexion
public class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Se mantiene en modo escucha para determinar el ingreso de datos
while (true) {
try {
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
// Envia los datos obtenidos hacia el evento via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//Envio de trama
public void write(String input) {
try {
mmOutStream.write(input.getBytes());
} catch (IOException e) {
//si no es posible enviar datos se cierra la conexión
Toast.makeText(getBaseContext(), "La Conexión fallo", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
Activity 3 (It's where I have 2 relays and pressing any button turns on arduino)
package com.example.artur.micasav3;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class Iluminacion extends AppCompatActivity {
private TextView BufferIn;
Button rele1, rele2;
Handler bluetoothIn;
final int handlerState = 0;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder DataStringIN = new StringBuilder();
private ConnectedThread MyConexionBT;
//Identificador unico de servicio - SPP UUID
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String para la direccion MAC
private static String address = null;
//-------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_iluminacion);
/////
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
/////
rele1 = (Button) findViewById(R.id.IdTodoOn);
rele2 = (Button) findViewById(R.id.IdTodoOff);
BufferIn = (TextView) findViewById(R.id.IdBufferIn);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
DataStringIN.append(readMessage);
int endOfLineIndex = DataStringIN.indexOf("#");
if (endOfLineIndex > 0) {
String dataInPrint = DataStringIN.substring(0, endOfLineIndex);
BufferIn.setText("Dato: " + dataInPrint);
DataStringIN.delete(0, DataStringIN.length());
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
VerificarEstadoBT();
////////ENCENDER O APAGAR TODOO////
rele1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyConexionBT.write("A");
}
});
rele2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyConexionBT.write("a");
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
//crea un conexion de salida segura para el dispositivo
//usando el servicio UUID
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}
@Override
public void onPause() {
super.onPause();
try { // Cuando se sale de la aplicación esta parte permite
// que no se deje abierto el socket
btSocket.close();
} catch (IOException e2) {
}
}
//Comprueba que el dispositivo Bluetooth está disponible y solicita que se active si está desactivado
private void VerificarEstadoBT() {
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "El dispositivo no soporta bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//Crea la clase que permite crear el evento de conexion
public class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Se mantiene en modo escucha para determinar el ingreso de datos
while (true) {
try {
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
// Envia los datos obtenidos hacia el evento via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//Envio de trama
public void write(String input) {
try {
mmOutStream.write(input.getBytes());
} catch (IOException e) {
//si no es posible enviar datos se cierra la conexión
Toast.makeText(getBaseContext(), "La Conexión fallo", Toast.LENGTH_LONG).show();
finish();
}
}
}
}