Andriod Studio
Abrimos nuestro Android Studio y selecionamos New Project selecionamos un Empty Activity y presionamos NextEl nombre de nuestra aplicación manoEl nivel de nuestra api: 19 el package name: com.tutosoftware.mano y presionamos Finish
Nos vamos al directorio app/manifests Y en el archivo AndroidManifest.xml agregamos los permisos para manejar el bluetooth.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutosoftware.mano">
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".ManoControl"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Ahora nos vamos al directorio app/res/layout y en el archivo activity_main.xml agregamos los siguientes elementos.
<?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"
tools:context=".MainActivity"
tools:layout_width="match_parent"
tools:orientation="vertical">
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:id="@+id/textView"
android:text="Dispositivos Emparejados"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:id="@+id/button"
android:text="Emparejar dispositivos"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"/>
<ListView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/listView"
android:layout_below="@+id/textView"
android:layout_above="@+id/button"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
En la clase MainActivity.java escribimos lo siguiente:
package com.tutosoftware.mano;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
Button btnEmparejar;
ListView listaDispositivos;
//Bluetooth
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnEmparejar = (Button) findViewById(R.id.button);
listaDispositivos = (ListView) findViewById(R.id.listView);
//if the device has bluetooth
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if (myBluetooth == null) {
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "El dispositivo bluetooht no esta disponible", Toast.LENGTH_LONG).show();
//finish apk
finish();
} else if (!myBluetooth.isEnabled()) {
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon, 1);
}
btnEmparejar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pairedDevicesList();
}
});
}
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
listaDispositivos.setAdapter(adapter);
listaDispositivos.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(MainActivity.this, ManoControl.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
startActivity(i);
}
};
}
Ahora creamos una Activity selecionamos New->Activity->Empty Activity y la nombramos ManoControl
Ahora nos vamos al directorio app/res/layout y en el archivo activity_mano_control.xml agregamos los siguientes elementos.
<?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"
tools:context=".ManoControl">
<Button
android:id="@+id/uno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_marginLeft="100dp"
android:text="1" />
<Button
android:id="@+id/dos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_marginLeft="100dp"
android:text="2" />
<Button
android:id="@+id/tres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="100dp"
android:text="3" />
<Button
android:id="@+id/cuatro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="4" />
<Button
android:id="@+id/cinco"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:layout_marginLeft="100dp"
android:text="5" />
<Button
android:id="@+id/abrir"
android:layout_width="194dp"
android:layout_height="wrap_content"
android:layout_marginTop="250dp"
android:layout_marginLeft="100dp"
android:text="Abrir" />
<Button
android:id="@+id/cerrar"
android:layout_width="133dp"
android:layout_height="52dp"
android:layout_marginTop="300dp"
android:layout_marginLeft="100dp"
android:text="Cerrar"/>
<Button
android:id="@+id/paz"
android:layout_width="133dp"
android:layout_height="52dp"
android:layout_marginTop="350dp"
android:layout_marginLeft="100dp"
android:text="Paz y amor"/>
<Button
android:id="@+id/ok"
android:layout_width="133dp"
android:layout_height="52dp"
android:layout_marginTop="400dp"
android:layout_marginLeft="100dp"
android:text="Ok"/>
<Button
android:id="@+id/saludo"
android:layout_width="133dp"
android:layout_height="52dp"
android:layout_marginTop="450dp"
android:layout_marginLeft="100dp"
android:text="Saludo"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Desconectar"
android:id="@+id/des"
android:layout_marginTop="500dp"
android:layout_marginLeft="100dp"
/>
</RelativeLayout>
Por último nos vamos a la clase ManoControl.java
package com.tutosoftware.mano;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
public class ManoControl extends AppCompatActivity {
Button uno,dos,tres,cuatro,cinco,seis,abrir,cerrar,paz,ok,saludo,desconectar;
String address = null;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mano_control);
Intent newint = getIntent();
address = newint.getStringExtra(MainActivity.EXTRA_ADDRESS);
//receive the address of the bluetooth device
uno = (Button) findViewById(R.id.uno);
dos = (Button) findViewById(R.id.dos);
tres = (Button) findViewById(R.id.tres);
cuatro = (Button) findViewById(R.id.cuatro);
cinco = (Button) findViewById(R.id.cinco);
abrir = (Button) findViewById(R.id.abrir);
cerrar = (Button) findViewById(R.id.cerrar);
paz = (Button) findViewById(R.id.paz);
ok = (Button) findViewById(R.id.ok);
saludo = (Button) findViewById(R.id.saludo);
desconectar = (Button) findViewById(R.id.des);
new ConnectBT().execute();
//commands to be sent to bluetooth
uno.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("1"); //method to turn on
}
});
dos.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("2"); //method to turn on
}
});
tres.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("3"); //method to turn on
}
});
cuatro.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("4"); //method to turn on
}
});
cinco.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("5"); //method to turn on
}
});
abrir.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("a"); //method to turn on
}
});
cerrar.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("b"); //method to turn on
}
});
paz.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("c"); //method to turn on
}
});
ok.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("d"); //method to turn on
}
});
saludo.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mandarComando("e"); //method to turn on
}
});
desconectar.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void mandarComando(String comando)
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write(comando.getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ManoControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
@Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
@Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}
Ejecutando la aplicación
El video se ve un poco difuso ya que no cuento con el equipo para filmar el ejemplo pero logre capturar lo siguiente.Código
El código de lo puedes descargar de:Ejecutable
Aqui te dejo el ejecutable para que lo instales en tu teléfonoIr a comando de voz