I'm trying to get a list of devices with bluetooth but not ACTION_FOUND is not working, it's my first bluetooth test app, I hope you can help me.
this is my MainActivity
public class MainActivity extends AppCompatActivity {
private ListView listView;
private BluetoothAdapter bluetoothAdapter;
private static final int PETICION_BLUETOOTH = 0;
private ArrayAdapter<String> dispositivosArrayAdapter;
private BluetoothSocket socketBT;
private PrintWriter salidaSocket;
private EditText texto;
private Button enviar;
//Identificador único , en ambos proyectos debe estar el mismo.
private static final UUID MI_UUID = UUID.fromString("6049a354-3df0-11e3-8e7a-ce3f5508acd9");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
listView.setEmptyView(findViewById(android.R.id.empty));
texto = (EditText) findViewById(R.id.edit_mensaje);
enviar = (Button) findViewById(R.id.button_enviar);
//Se obtiene el adaptador Bluetooth...
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// se valida que bluetooth este habilitado
if (bluetoothAdapter == null) {
Toast.makeText(MainActivity.this, "No se encontraron dispositivos", Toast.LENGTH_LONG).show();
finish();
} else {
if (bluetoothAdapter.isEnabled()) {
Intent intentHabilitarBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intentHabilitarBT, PETICION_BLUETOOTH);
}
}
//LISTA DE DISPOSITIVOS
dispositivosArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(dispositivosArrayAdapter);
listView.setOnItemClickListener(itemClickListener);
//Botón ENVIAR
enviar.setOnClickListener(onClickListener);
// Botón inhabilitado
enviar.setEnabled(false);
registrarBroadcast();
}
//Clic en algún elemento de la lista.
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
private BluetoothDevice dispositivo;
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery(); //cancela descubrimiento de bluetooth
String nombreBluetooth = ((TextView) view).getText().toString();
String direccionBluetooth = nombreBluetooth.substring(nombreBluetooth.length() - 17);
dispositivo = bluetoothAdapter.getRemoteDevice(direccionBluetooth);
Toast.makeText(getApplicationContext(), "Intentando conectar con : "+dispositivo, Toast.LENGTH_SHORT).show();
//Clase Asincrona para activar la conexión con el servidor
HiloClienteConexionAsync hiloClienteConexionAsync = new HiloClienteConexionAsync();
hiloClienteConexionAsync.execute(dispositivo);
}
};
//Evento clic para enviar mensaje.
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
enviaMensajeASocketServidor();
}
};
//Actualizar descubrimiento de Dispositivos Bluetooth.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.actualizar) {
//Limpiar la lista
dispositivosArrayAdapter.clear();
iniciarDescubrimiento();
return true;
}
return super.onOptionsItemSelected(item);
}
//Conexión con el servidor
class HiloClienteConexionAsync extends AsyncTask<BluetoothDevice, String, Integer> {
private BluetoothDevice dispositivo;
@Override
protected Integer doInBackground(BluetoothDevice... arg0) {
this.dispositivo = arg0[0];
// se conecta a un bluetoothdevice
try {
//Se crea un Socket con los protocolos RFCOMM, y SDP para conectarse al servicio provisto por el UUID,
//la comunicacion esta encriptada por default
socketBT = dispositivo.createRfcommSocketToServiceRecord(MI_UUID);
} catch (IOException e) {
Log.e("BluetoothClienteApp", "Error : "+e.toString());
}
try {
//conecta el dispositivo a traves del socket
socketBT.connect();
} catch (IOException e) {
Log.e("BluetoothClienteApp", "Error : "+e.toString());
}
// para mandar cadenas string,Se crea un objeto PrintWriter con autoFlush (envio de todos los datos sin esperar nuevos datos.)
// a partir de objetos intermedios que envuelven a la salida en flujo del socket (socket.getOutputStream())
try {
salidaSocket = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socketBT.getOutputStream())), true);
} catch (IOException e) {
Log.e("BluetoothClienteApp", "Error : "+e.toString());
}
publishProgress("Conexion establecida...");
return 0;
}
//se realiza la conexión y se habilita el botón de enviar.
@Override
protected void onProgressUpdate(String... values) {
Toast.makeText(MainActivity.this, values[0], Toast.LENGTH_SHORT).show();
enviar.setEnabled(true);
super.onProgressUpdate(values);
}
}
/*
* Para cuando se habilita o deshabilita el Bluetooth aqui llega el resultado si esta activo mi bluetoohadapter
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PETICION_BLUETOOTH:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Habilitacion Realizada...", Toast.LENGTH_SHORT).show();
iniciarDescubrimiento();//
}
else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Habilitacion cancelada...", Toast.LENGTH_SHORT).show();
finish();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
//Método para iniciar la busqueda de dispositivos.
private void iniciarDescubrimiento(){
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
Toast.makeText(MainActivity.this, "Buscando nuevos dispositivos", Toast.LENGTH_LONG).show();
bluetoothAdapter.startDiscovery();
}
//Broadcast que esta a la escucha de terminar de encontrar dispositivos
private void registrarBroadcast(){
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(broadcastReceiver, intentFilter);
intentFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(broadcastReceiver, intentFilter);
intentFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
this.registerReceiver(broadcastReceiver, intentFilter);
}
//Broadcast desde código y método onReceive escucha cuando la busqueda fue finalizada.
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String accion = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(accion)){
Toast.makeText(context, "j", Toast.LENGTH_SHORT).show();
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED){
dispositivosArrayAdapter.add(bluetoothDevice.getName()+"\n"+bluetoothDevice.getAddress());
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(accion)) {
Toast.makeText(MainActivity.this, "Busqueda finalizada", Toast.LENGTH_SHORT).show();
if (dispositivosArrayAdapter.getCount() == 0) {
dispositivosArrayAdapter.add("No se encontraron dispositivos");
}
}
}
};
//Callback Broadcast
@Override
protected void onPause() {
super.onPause();
if(bluetoothAdapter != null){
bluetoothAdapter.cancelDiscovery();
this.unregisterReceiver(broadcastReceiver);
}
}
@Override
protected void onResume() {
super.onResume();
registrarBroadcast();
}
//Metodo para enviar una cadena al socket servidor
public void enviaMensajeASocketServidor() {
if (salidaSocket!=null){
try {
String str = texto.getText().toString();
//se envia mediante el objeto de tipo PrintWriter el flujo (Stream)
//de la cadena recogida del EditText al socket
salidaSocket.println(str);
Toast.makeText(this,"Mensaje Enviado",Toast.LENGTH_LONG).show();
borrartxt();
} catch (Exception e) {
Log.e("BluetoothClienteApp", e.getMessage());
Toast.makeText(this,"Mensaje NO enviado",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(), "Conexion no establecia...", Toast.LENGTH_LONG).show();
}
}
///Método para borrar el texto del mensaje
private void borrartxt() {
texto.setText("");
}
}
I read that in the Marshmallow android paritr, the ACCESS_COARSE_LOCATION permission is needed, I already placed it and gave the app permission and nothing
this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mx.com.omnius.BluetoothCliente">
<uses-feature android:name="android.hardware.bluetooth" android:required="true"></uses-feature>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
>
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
When I run, enter this if of the BroadcastReceiver
if (dispositivosArrayAdapter.getCount() == 0) {
dispositivosArrayAdapter.add("No se encontraron dispositivos");
}
I hope you can help me. thank you very much: D