Beruflich Dokumente
Kultur Dokumente
bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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;
("fa87c0d0-afac-11de-8a39-
("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
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");
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)
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; }
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
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.
} 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);
}
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
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";
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\/
/\\//\\
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
}} } });
@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...");
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);
.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
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;
{
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