Andriod Studio
Abrimos nuestro Android Studio y selecionamos New Project selecionamos un Empty Activity y presionamos NextEl nombre de nuestra aplicación manovoz2El nivel de nuestra api: 19 el package name: com.tutosoftware.manovoz2 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.manavoz2">
<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=".BtDevicesActivity"></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"?>
<android.support.constraint.ConstraintLayout 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">
<Button
android:id="@+id/SpeakButton"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginTop="390dp"
android:text="@string/speak_but_text"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/SpokenText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/text_hint"
android:padding="2dp"
android:textAppearance="@android:style/TextAppearance.DeviceDefault"
app:layout_constraintBottom_toTopOf="@+id/SpeakButton"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
En la clase MainActivity.java escribimos lo siguiente:
package com.tutosoftware.manavoz2;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.AsyncTask;
import android.speech.RecognizerIntent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ProgressDialog progress;
public boolean isBtConnected = false;
String address = null;
Button speak;
TextView VoiceToWordText;
private final int REQ_CODE_SPEECH_INPUT = 100;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent newint = getIntent();
address = newint.getStringExtra(BtDevicesActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device
speak = (Button) findViewById(R.id.SpeakButton);
VoiceToWordText = (TextView) findViewById(R.id.SpokenText);
speak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
promptSpeechInput();
}
});
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if (myBluetooth == null) {
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", 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);
}
}
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(MainActivity.this, "Mano voz...", "Espera un poco!!!"); //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("Conexion cortada.");
finish();
} else {
msg("Cihaza Baðlandý.");
isBtConnected = true;
}
progress.dismiss();
}
}
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
// fast way to call Toast
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
VoiceToWordText.setText(result.get(0));
String input = VoiceToWordText.getText().toString();
if (input.equals("dispositivos")) {
Intent i = new Intent(MainActivity.this,BtDevicesActivity.class);
startActivity(i);
}
if (input.equals("conectar")) {
if(!isBtConnected ){
new ConnectBT().execute();}
else {
Toast.makeText(getApplicationContext(),"Dispositivo emparejado",Toast.LENGTH_LONG).show();
}}
if (input.equals("1")) {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("1".getBytes());
} catch (IOException e) {
msg("Error");
}
}
//textoPulgar.setText("Dedo pulgar");
}
if (input.equals("2")) {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("2".getBytes());
} catch (IOException e) {
msg("Error");
}
}
//textoIndice.setText("Dedo Indice");
}
if (input.equals("3")) {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("3".getBytes());
} catch (IOException e) {
msg("Error");
}
}
//textoMedio.setText("Dedo medio");
}
if (input.equals("4")) {
if (btSocket != null) {
try {
btSocket.getOutputStream().write("5".getBytes());
} catch (IOException e) {
msg("Error");
}
}
// textoAnular.setText("Dedo anular");
}
}
break;
}
}
}
}
Ahora creamos una Activity selecionamos New->Activity->Empty Activity y la nombramos BtDevicesActivity
Ahora nos vamos al directorio app/res/layout y en el archivo activity_bt_devices.xml agregamos los siguientes elementos.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".BtDevicesActivity">
<ListView
android:id="@+id/BluetoothListview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
</android.support.constraint.ConstraintLayout>
Por último nos vamos a la clase BtDevicesActivity.java
package com.tutosoftware.manavoz2;
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.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
public class BtDevicesActivity extends AppCompatActivity {
ListView devicelist;
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_bt_devices);
devicelist = (ListView)findViewById(R.id.BluetoothListview);
//if the device has bluetooth
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", 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);
}
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 Devices", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
devicelist.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(BtDevicesActivity.this, MainActivity.class);
Toast.makeText(getApplicationContext(), "Dispositivo elegido mano voz", Toast.LENGTH_LONG).show();
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
startActivity(i);
}
};
}
Por último nos vamos al directorio app/res/values y en el archivo strings.xml colocamos lo siguiente:
<resources>
<string name="app_name">manavoz2</string>
<string name="speech_prompt">Say something…</string>
<string name="speech_not_supported">Sorry! Your device doesn\'t support speech input</string>
<string name="text_hint">Su comando será escrito aquí</string>
<string name="speak_but_text">Tocar y comando</string>
<string name="title_activity_bt_devices">BtDevicesActivity</string>
<string name="Eslesmis_CihazlarButon">Eþleþmiþ Cihazlarý Göster</string>
</resources>
Ejecutando la aplicación
El funcionamiento es siguiente:- Presionas el boton que dice tocar y comando y cuando aparece el microfono de google hablas y dispositivos
- Aparece una lista de dispositivos emparejados seleccionas el de tu bluetooth de tu mano que seria HC-06 vuelves presionar el boton y una vez que aparece la pantalla dices el comando conectar
-
Una vez que se conecta los comandos siguientes son:
- comando uno para dedo pulgar
- comando dos para dedo indice
- comando tres para dedo medio
- comando cuatro para dedo anular y meñique
- Nota: no olvidar que debe presionar el boton por cada comando