Sie sind auf Seite 1von 34

package com.ejemplo.

bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

Aqu se muestran las libreras que se van a


utilizar tanto para la conexin del
bluetooth y los diferentes procedimientos

import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ConexionBT {


private static final String TAG = "Servicio_Bluetooth";
private static final boolean D = true;
// Nombre para el registro SDP cuando el socket sea creado
private static final String NAME = "BluetoothDEB";
// UUID Identificador unico de URI para esta aplicacion
private static final UUID MY_UUID = UUID.fromString("00001101-0000-10008000-00805F9B34FB");
// UUID para chat con otro Android
0800200c9a66");

("fa87c0d0-afac-11de-8a39-

// UUID para modulos BT RN42


00805F9B34FB");

("00001101-0000-1000-8000-

// Campos de coexion
private final BluetoothAdapter AdaptadorBT;
private final Handler mHandler;
private AcceptThread HebraDeAceptacion;
private ConnectThread HiloDeConexion;
private ConnectedThread HiloConetado;
private int EstadoActual;
// Constantes que indican el estado de conexion
public static final int STATE_NONE = 0;
public static final int STATE_LISTEN = 1;
entrantes

// No se esta haciendo nada


// Escuchando por conexiones

public static final int STATE_CONNECTING = 2; // Iniciando conexion saliente


public static final int STATE_CONNECTED = 3; // Conectado con un
dispositivo
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<< METODOS
>>>>>>>>>>>>>>>>>>>>>>>>>>>
//----<<<<---->>>>----METODOS NO ALTERADOS----<<<<---->>>>---/**
* Constructor. Prepara una nueva sesion para la conexion Bluetooth
Smartphone-Dispositivo
* @param context El identificador UI de la actividad de context
* @param handler Un Handler para enviar mensajes de regreso a la
actividad marcada por el UI
*
* */
public ConexionBT(Context context, Handler handler) {
AdaptadorBT = BluetoothAdapter.getDefaultAdapter();
EstadoActual = STATE_NONE;

mHandler = handler;
}

/**
* Actualizamos estado de la conexion BT a la actividad
* @param estado Un entero definido para cada estado
*/
private synchronized void setState(int estado) {
EstadoActual = estado;
// Le enviamos al Handler el nuevo estado actual para que se actualize en la
Actividad
mHandler.obtainMessage(MainActivity.Mensaje_Estado_Cambiado, estado,
-1).sendToTarget();
}
/**
* Regresa el estado de la conexion */
public synchronized int getState() {
return EstadoActual;
}

/**
* Inicia el servicio bluetooth. Especificamente inicia la HebradeAceptacion
para iniciar el
* modo de "listening". LLamado por la Actividad onResume() */
public synchronized void start() {
if (D) Log.e(TAG, "start");

//Cancela cualquier hilo que quiera hacer una conexion


if (HiloDeConexion != null) {HiloDeConexion.cancel(); HiloDeConexion =
null;}
//Cancela cualquier hebra que este corriendo una conexion
if (HiloConetado != null) {HiloConetado.cancel(); HiloConetado = null;}
// Inicia la hebra que escuchara listen en el BluetoothServerSocket
if (HebraDeAceptacion == null) {
HebraDeAceptacion = new AcceptThread();
HebraDeAceptacion.start();
}
setState(STATE_LISTEN);
}
/**
* Inicia el HiloConectado para iniciar la conexion con un dispositivo remoto
* @param device -->El dispositivo BT a conectar
*/
public synchronized void connect(BluetoothDevice device) {
if (D) Log.e(TAG, "Conectado con: " + device);
//Cancela cualquier hilo que intente realizar una conexion
if (EstadoActual == STATE_CONNECTING) {
if (HiloDeConexion != null) {HiloDeConexion.cancel(); HiloDeConexion
= null;} }
//Cancela cualquier hilo que se encuentre corriendo una conexion
if (HiloConetado != null) {HiloConetado.cancel(); HiloConetado = null;}
//Inicia el hilo para conectar con un dispositivo
HiloDeConexion = new ConnectThread(device);
HiloDeConexion.start();

setState(STATE_CONNECTING);
}

/**
* Inicia la hebra conectada para iniciar la administracion de la conexin BT
* @param socket El socket Bt donde se realizara la conexion
* @param device El dispositivo BT con que se conectara
*/
public synchronized void connected(BluetoothSocket socket,
BluetoothDevice device) {
if (D) Log.e(TAG, "connected");
// Cancela el hilo que completo la conexion
if (HiloDeConexion != null) {HiloDeConexion.cancel(); HiloDeConexion =
null;}
//Cancela el hilo que actualmente esta corriendo la conexion
if (HiloConetado != null) {HiloConetado.cancel(); HiloConetado = null;}
// Cancela la Hebradeaceptacion debido a que solo queremos conectar con
un dispositivo**********
if (HebraDeAceptacion != null) {HebraDeAceptacion.cancel();
HebraDeAceptacion = null;}
//Inicia el hilo para administrar la conexion y realizar transmisiones
HiloConetado = new ConnectedThread(socket);
HiloConetado.start();
//Envia el nombre del dispositivo conectado de vuelta
Message msg =
mHandler.obtainMessage(MainActivity.Mensaje_Nombre_Dispositivo);
Bundle bundle = new Bundle();

bundle.putString(MainActivity.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
* Para todos los hilos y pone el estado de STATE_NONE donde no esta
haciendo nada
*/
public synchronized void stop() {
if (D) Log.e(TAG, "stop");
if (HiloDeConexion != null) {HiloDeConexion.cancel(); HiloDeConexion =
null;}
if (HiloConetado != null) {HiloConetado.cancel(); HiloConetado = null;}
if (HebraDeAceptacion != null) {HebraDeAceptacion.cancel();
HebraDeAceptacion = null;}
setState(STATE_NONE);
}
/**
* Escribe en el HiloConectado de manera Asincrona
* @param out Los bytes a escribir
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
ConnectedThread r; //Creacion de objeto temporal
// Syncronizar la copia del HiloConectado
synchronized (this)

if (EstadoActual != STATE_CONNECTED) return;

r = HiloConetado; }
// Realizar la escritura Asincrona
r.write(out);
}
/**
* Indica que el intento de conexion fallo y notifica a la actividad
WidgetProvider/UpdateService
*/
private void connectionFailed() {
setState(STATE_LISTEN);
//Envia un mensaje de falla de vuelta a la actividad
Message msg = mHandler.obtainMessage(MainActivity.Mensaje_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Error de conexin");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
/**
* Indica que la conexion se perdio y notifica a la UI
activity(WidgetProvider/UpdateSErvice)
*/
private void connectionLost() {
setState(STATE_LISTEN);
//Envia un mensaje de falla de vuelta a la actividad
Message msg = mHandler.obtainMessage(MainActivity.Mensaje_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Se perdio conexion");

msg.setData(bundle);
mHandler.sendMessage(msg);
msg = mHandler.obtainMessage(MainActivity.MESSAGE_Desconectado);
mHandler.sendMessage(msg);
}
/**
* Este hilo corre mientras se este ESCUCHANDO por conexiones entrantes.
Este se
* comporta como el lado-Servidor cliente. Corre mientras la conexion es
aceptada(o cancelada)
*/
private class AcceptThread extends Thread {
// El soket de servidor Local
private final BluetoothServerSocket mmServerSocket;
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public AcceptThread() {
BluetoothServerSocket tmp = null;
//Creamos un nuevo listening server socket
try {
tmp = AdaptadorBT.listenUsingRfcommWithServiceRecord(NAME,
MY_UUID);
} catch (IOException e) {
Log.e(TAG, "listen() fallo", e);
}
mmServerSocket = tmp; }
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

public void run() {


if (D) Log.e(TAG, "Comenzar HiloDeAceptacion " + this);
setName("HiloAceptado");
BluetoothSocket socket = null;
//Escucha al server socket si no estamos conectados
while (EstadoActual != STATE_CONNECTED) {
try {
//Esto es un bloque donde solo obtendremos una conexion o una
excepcion
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "accept() failed", e);
break;
}
//Si la conexion fue aceptada...
if (socket != null) {
synchronized (ConexionBT.this) {
switch (EstadoActual) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Iniciamos HebraConectada
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// O no esta lista o ya esta conectado. Termina el nuevo
socket

try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "No se pudo cerrar el socket no deseado", e);
}
break;
}
}
}
}
if (D) Log.e(TAG, "Fin de HIlodeAceptacion");
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public void cancel() {
if (D) Log.e(TAG, "Cancela " + this);
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() del servidor FAllo", e);
}
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}
/**
* Esta Hebra correra mientras se intente realizar una conexion de salida con
un dispositivo.

* Este correra a travs de la conexion ya sea establecida o fallada


*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device) {


mmDevice = device;
BluetoothSocket tmp = null;
// Obtiene un BluetoothSocket para la conexion con el Dispositivo
obtenido
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "create() Fallo", e);
}
mmSocket = tmp;
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public void run() {
Log.e(TAG, "Comenzando HebraConectada");
setName("HiloConectado");
//Siempre cancela la busqueda debido a que esta hara lenta la conexion
AdaptadorBT.cancelDiscovery();
// Realiza la conexion con el socketBluetooth
try {

// Aqui solo recibiremos o una conexion establecida o una excepcion


mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Cierra el socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "Imposible cerrar el socket durante la falla de
conexion", e2);
}
// Inicia el servicio a traves de reiniciar el modo de listening
ConexionBT.this.start();
return;
}
// Resetea el HiloConectado pues ya lo hemos usado
synchronized (ConexionBT.this) {
HiloDeConexion = null;
}
// Inicia el hiloconectado
connected(mmSocket, mmDevice);
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public void cancel() {
try {
mmSocket.close();

} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}//fin de conectThread
/**
* Este hilo corre durante la conexion con un dispositivo remoto.
* Este maneja todas las transmisiones de entrada y salida.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket BTSocket;
private final InputStream INPUT_Stream;
private final OutputStream OUTPUT_Stream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "Creacion de HiloConectado");
BTSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Obtencion del BluetoothSocket de entrada y saldida
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Sockets temporales No creados", e);
}

INPUT_Stream = tmpIn;
OUTPUT_Stream = tmpOut;
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/**
* Escribe al Stream de salida conectado
* @param buffer Los bytes a escribir
*/
public void write(byte[] buffer) {
try {
OUTPUT_Stream.write(buffer); //Compartir el mensaje enviado con
la UI activity
mHandler.obtainMessage(MainActivity.Mensaje_Escrito, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {Log.e(TAG, "Exception during write", e);}
}//FIN DE WRITE
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public void cancel() {
try {
BTSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() del socket conectado Fallo", e);
}
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

public void run() {


Log.e(TAG, "Comenzar Hebraconectada");
byte[] buffer = new byte[1024];
int bytes;
while (true) { //Mantiene escuchando el InputStream mientras este
conectado
try {
//Lee desde el InputStream
bytes = INPUT_Stream.read(buffer);
// byte[] readBufX = (byte[]) buffer; //Construye un String desde los bytes
validos en el buffer
// String readMessageX = new String(readBufX, 0, bytes);//Se envia el
readNessagexxx en lugar del buffer pues ya se PARSEO
mHandler.obtainMessage(MainActivity.Mensaje_Leido, bytes, -1,
buffer).sendToTarget(); //readMessageX por buffer
} catch (IOException e) {Log.e(TAG, "disconnected", e);connectionLost();break;
}
}//_____________-----FIN DE WHILE (TRUE)-----_________________
}//**************_________FIN DE PUBLIC VOID
RUN__________**************
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}//--------------------*****FIN de la clase ConnectedThread*****------------------} //<<<<<____>>>>>_____<<<<<_____>>>>>_____FIN DE LA CLASE
CONEXIONBT_____<<<<<_____>>>>>____<<<<<_____>>>>>

MAIN ACTIVITY
package com.ejemplo.bluetooth;
import android.os.Bundle;
import android.os.Handler;

import android.os.Message;
import android.os.Vibrator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {

View botonE;
RadioGroup rg;
int checar;
public static final String TAG = "LEDv0";

public static final boolean D = true;


// Tipos de mensaje enviados y recibidos desde el Handler
de ConexionBT
public static final int Mensaje_Estado_Cambiado = 1;
public static final int Mensaje_Leido = 2;
public static final int Mensaje_Escrito = 3;
public static final int Mensaje_Nombre_Dispositivo = 4;
public static final int Mensaje_TOAST = 5;
public static final int MESSAGE_Desconectado = 6;
public static final int REQUEST_ENABLE_BT = 7;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
//Nombre del dispositivo conectado
private String mConnectedDeviceName = null;
// Adaptador local Bluetooth
private BluetoothAdapter AdaptadorBT = null;
//Objeto miembro para el servicio de ConexionBT
private ConexionBT Servicio_BT = null;
//Vibrador
private Vibrator vibrador;
//variables para el Menu de conexin
private boolean seleccionador=false;
public int Opcion=R.menu.main;

//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\/
/\\//\\
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final Button BotonLedb


=(Button)findViewById(R.id.btnApagar);
final Button BotonLeda =
(Button)findViewById(R.id.btnEncender);
rg=(RadioGroup) findViewById(R.id.radioGroup1);
BotonLeda.setOnClickListener(new View.OnClickListener()
{
public void onClick(View vv) {
if(BotonLeda.isClickable())
if(D) Log.e("BotonLed", "Encendiendo..");
checar =rg.getCheckedRadioButtonId();
switch(checar){
case R.id.radiobano: sendMessage("a\r");
break;
case R.id.radiorecamara1: sendMessage("c\r");
break;

case R.id.radiorecamara2: sendMessage("e\r");


break;
case R.id.radiosala: sendMessage("g\r");
break;
case R.id.radiococina: sendMessage("k\r");
break;
case R.id.radiocomedor: sendMessage("m\r");
break;
case R.id.radiogarage: sendMessage("o\r");
break;
case R.id.radioentrada: sendMessage("q\r");
break;
case R.id.radiopasillo: sendMessage("s\r");
break;
case R.id.radioventilador: sendMessage ("i\r");
break;
case R.id.radiogeneral:sendMessage ("u\r");}
}
});//fin de metodo de BotonLedencender
BotonLedb.setOnClickListener(new View.OnClickListener(){
public void onClick (View vv){
if(BotonLedb.isClickable())

if(D) Log.e("BotonLed", "Apagando..");

checar =rg.getCheckedRadioButtonId();
switch(checar){
case R.id.radiobano: sendMessage("b\r");
break;
case R.id.radiorecamara1: sendMessage("d\r");
break;
case R.id.radiorecamara2: sendMessage("f\r");
break;
case R.id.radiosala: sendMessage("h\r");
break;
case R.id.radiococina: sendMessage("l\r");
break;
case R.id.radiocomedor: sendMessage("n\r");
break;
case R.id.radiogarage: sendMessage("p\r");
break;
case R.id.radioentrada: sendMessage("r\r");
break;
case R.id.radiopasillo: sendMessage("t\r");
break;
case R.id.radioventilador: sendMessage("j\r");
break;
case R.id.radiogeneral: sendMessage("v\r");

break;
}} } });

public void onStart() {


super.onStart();
ConfigBT();
}

@Override
public void onDestroy(){
super.onDestroy();
if (Servicio_BT != null) Servicio_BT.stop();//Detenemos
servicio
}
public void ConfigBT(){
// Obtenemos el adaptador de bluetooth
AdaptadorBT = BluetoothAdapter.getDefaultAdapter();
if (AdaptadorBT.isEnabled()) {//Si el BT esta encendido,
if (Servicio_BT == null) {//y el Servicio_BT es nulo,
invocamos el Servicio_BT
Servicio_BT = new ConexionBT(this, mHandler);
}
}
else{ if(D) Log.e("Setup", "Bluetooth apagado...");

Intent enableBluetooth = new


Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth,
REQUEST_ENABLE_BT);
}
}
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
//Una vez que se ha realizado una actividad regresa un
"resultado"...
switch (requestCode) {
case REQUEST_ENABLE_BT://Respuesta de intento de
encendido de BT
if (resultCode == Activity.RESULT_OK) {//BT esta
activado,iniciamos servicio
ConfigBT();
} else {//No se activo BT, salimos de la app
finish();}
}//fin de switch case
}//fin de onActivityResult
@Override
public boolean onPrepareOptionsMenu(Menu menux){
//cada vez que se presiona la tecla menu este metodo es
llamado
menux.clear();//limpiamos menu actual

if
(seleccionador==false)Opcion=R.menu.main;//dependiendo
las necesidades
if
(seleccionador==true)Opcion=R.menu.desconecta; //
crearemos un menu diferente
getMenuInflater().inflate(Opcion, menux);
return super.onPrepareOptionsMenu(menux);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Conexion:
if(D) Log.e("conexion", "conectandonos");
vibrador = (Vibrator)
getSystemService(VIBRATOR_SERVICE);
vibrador.vibrate(1000);
String address =
"20:14:04:15:10:68";//Direccion Mac del hc-06
BluetoothDevice device =
AdaptadorBT.getRemoteDevice(address);
Servicio_BT.connect(device);
return true;
case R.id.desconexion:

if (Servicio_BT != null)
Servicio_BT.stop();//Detenemos servicio
return true;
}//fin de swtich de opciones
return false;
}//fin de metodo onOptionsItemSelected
public void sendMessage(String message) {
if (Servicio_BT.getState() ==
ConexionBT.STATE_CONNECTED) {//checa si estamos
conectados a BT
if (message.length() > 0) { // checa si hay algo que
enviar
byte[] send = message.getBytes();//Obtenemos bytes
del mensaje
if(D) Log.e(TAG, "Mensaje enviado:"+ message);
Servicio_BT.write(send);

//Mandamos a escribir el

mensaje
}
} else Toast.makeText(this, "No conectado",
Toast.LENGTH_SHORT).show();
}//fin de sendMessage
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {

switch (msg.what) {
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
case Mensaje_Escrito:
byte[] writeBuf = (byte[]) msg.obj;//buffer de escritura...
// Construye un String del Buffer
String writeMessage = new String(writeBuf);
if(D) Log.e(TAG, "Message_write =w= "+ writeMessage);
break;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
case Mensaje_Leido:
byte[] readBuf = (byte[]) msg.obj;//buffer de lectura...
//Construye un String de los bytes validos en el buffer
String readMessage = new String(readBuf, 0, msg.arg1);
if(D) Log.e(TAG, "Message_read =w= "+ readMessage);
break;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
case Mensaje_Nombre_Dispositivo:

mConnectedDeviceName =
msg.getData().getString(DEVICE_NAME); //Guardamos nombre
del dispositivo
Toast.makeText(getApplicationContext(), "Conectado con "+
mConnectedDeviceName, Toast.LENGTH_SHORT).show();
seleccionador=true;
break;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
case Mensaje_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
case MESSAGE_Desconectado:
if(D) Log.e("Conexion","DESConectados");
seleccionador=false;
break;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}//FIN DE SWITCH CASE PRIMARIO DEL HANDLER
}//FIN DE METODO INTERNO handleMessage

};//Fin de Handler
}//Fin MainActivity
MAINT ACTIVITY PRINCIPAL
//Libreras que se van a utilizar
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivityprincipal extends Activity{
DBAdapter dbAdapter;
EditText et1,et2;
Button btentrar;
Button btnuevo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

et1= (EditText) findViewById(R.id.editText1);


et2= (EditText) findViewById(R.id.editText2);
btentrar= (Button)findViewById(R.id.button1);
btnuevo = (Button)findViewById(R.id.button2);
dbAdapter = new DBAdapter(this);
dbAdapter.open();
btentrar.setOnClickListener(new OnClickListener() {
@Override
//inicia el mtodo en donde los textos va a obtener el valor
que se ingrese en el respectivo textbox
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et1.getWindowToken(), 0);
imm.hideSoftInputFromWindow(et2.getWindowToken(), 0);
String username = et1.getText().toString();
String password = et2.getText().toString();
//En este ciclo se realiza para cuando se va ingresar con un
usaurio y ver si es correcto el usuario y la contrasea
if (username.length() > 0 && password.length() > 0) {
try {
if (dbAdapter.Login(username, password)) {
Toast.makeText(MainActivityprincipal.this,
"Usuario Correcto", Toast.LENGTH_LONG)

.show();
Intent intent =new Intent
(MainActivityprincipal.this,MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(MainActivityprincipal.this,
"Nombre de usuario Invalido o Contrasea Incorrecta",
Toast.LENGTH_LONG).show();
}} catch (Exception e) {
Toast.makeText(MainActivityprincipal.this, "Ocurrio un
problema",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivityprincipal.this,
"usuario o contrasea desconocida",
Toast.LENGTH_LONG).show();
}
}
});
btnuevo.setOnClickListener(new OnClickListener() {
@Override
//Este mtodo es para agregar un nuevo usuario donde de
igual manera lo que se encuntre en el textbox se agregara a

la base de datos y de esa forma el usuario y la contrasea que


se ingres ya se pueda utilizar
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et1.getWindowToken(), 0);
imm.hideSoftInputFromWindow(et2.getWindowToken(), 0);
try {
String username = et1.getText().toString();
String password = et2.getText().toString();
long i = dbAdapter.register(username, password);
if(i != -1)//En este ciclo se verifica si es correcto el usuario que
se ingres si no de lo contrario le mandara el error
Toast.makeText(MainActivityprincipal.this, "Usuario
Correctamente registrado",Toast.LENGTH_LONG).show();
} catch (SQLException e) {
Toast.makeText(MainActivityprincipal.this, "Ocurrio un
problema",
Toast.LENGTH_LONG).show();}
}});
}
}
DBHELPER
import android.content.Context;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper{
private static final String DATABASE_TABLE = "Acceso";
private static final int DATABASE_VERSION = 1;
//En este mtodo se va a crear la base de datos
private static final String DATABASE_CREATE = "CREATE TABLE
Acceso (_id integer primary key autoincrement,"+ "username
text not null,"+ "password text not null);";
public DbHelper(Context context) {
super(context, DATABASE_TABLE, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXIST Acceso");
db.execSQL(DATABASE_CREATE);
}}

DBADAPTER
// Librerias que se utilizaran
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

//Este mtodo se utiliza para ejecutar las consultas sobre la


base de datos
public class DBAdapter {
private static final String DATABASE_TABLE = "Acceso";
public static final String KEY_ROW_ID = "_id";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
SQLiteDatabase mDb;
Context mCtx;
DbHelper mDbHelper;
public DBAdapter(Context context)
{
this.mCtx = context;
}
public DBAdapter open() throws SQLException

{
mDbHelper = new DbHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close()
{
mDbHelper.close();
}
public long register(String user,String pw)
{
//Esta parte est jalando los valores de los textbox y los
almacena en la base de datos
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pw);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean Login(String username, String password)
throws SQLException
{
//En esta parte del cdigo se est realizando una consulta en
la cual est buscando el usuario y contrasea que se esta
escribiendo

Cursor mCursor = mDb.rawQuery("SELECT * FROM " +


DATABASE_TABLE + " WHERE username=? AND password=?",
new String[]{username,password});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
return true;
}
}
return false; }}

Das könnte Ihnen auch gefallen