Return Bluetooth devices on Android

0

Hello,

After much research and study I was able to finish a class that returns me the bluetooth devices paired and connected near an Android. The problem I'm encountering is when it's time to update my ListView with the devices that are connected. The couplet already gave it right.

The problem is as follows, the list I am setting in setAdapter() does not have the Bluetooth device I connected, for some reason that list is populated after that setAdapter() runs and does not I could understand why.

ListBluetoothActivity.java

package br.ufscar.dc.controledepatrimonio.Forms;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import br.ufscar.dc.controledepatrimonio.R;
import br.ufscar.dc.controledepatrimonio.Util.RFID.Bluetooth;
import br.ufscar.dc.controledepatrimonio.Util.RFID.BluetoothListener;

public class ListarBluetoothActivity extends AppCompatActivity implements BluetoothListener {
    private Bluetooth bluetooth = new Bluetooth(this);
    private final static int REQUEST_ENABLE_BT = 1;
    private List<BluetoothDevice> listaDispositivos = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listar_bluetooth);

        //region Bluetooth
        switch (bluetooth.verificarEstado()) {
            case LIGADO:
                bluetooth.iniciarBusca(this, this);

                listaDispositivos = bluetooth.getListaDispostivo();
                ListView lstBluetooth = (ListView) findViewById(R.id.lstBluetooth);
                BluetoothAdapter itemBluetooth = new BluetoothAdapter(this, listaDispositivos);

                lstBluetooth.setAdapter(itemBluetooth);
                break;
            case DESLIGADO:
                Intent enableBtIntent = new Intent(bluetooth.getDispositivo().ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                break;
            case NAO_COMPATIVEL:
                Toast.makeText(getApplicationContext(), R.string.msg_bluetooth_nao_suportado, Toast.LENGTH_SHORT).show();
                break;
        }
        //endregion

        //region Botão Procurar
        Button btnProcurar = (Button) findViewById(R.id.btnProcurar_Bluetooth);
        btnProcurar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

            }
        });
        //endregion
    }

    //region Bluetooth
    @Override
    public void action(String action) {
        if (action.compareTo(ACTION_DISCOVERY_FINISHED) == 0) {
            listaDispositivos = bluetooth.getListaDispostivo();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub

        if (requestCode == REQUEST_ENABLE_BT) {
            switch (resultCode) {
                case RESULT_CANCELED:
                    //Não habilitou Bluetooth, então fecha a tela.
                    finish();
                    break;
            }
        }
    }
    //endregion

    //region Métodos não utilizados
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_listar_bluetooth, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    //endregion
}

Bluetooth.java

package br.ufscar.dc.controledepatrimonio.Util.RFID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class Bluetooth extends BroadcastReceiver {
    private BluetoothListener listener;
    private BluetoothAdapter dispositivo;
    private List<BluetoothDevice> listaDispostivo = new ArrayList<>();

    public enum Estado {
        LIGADO, DESLIGADO, NAO_COMPATIVEL
    }

    public Bluetooth (BluetoothListener listener) {
        dispositivo = BluetoothAdapter.getDefaultAdapter();
        this.listener = listener;
        getDispositivosPareados();
    }

    public BluetoothAdapter getDispositivo() {
        return dispositivo;
    }

    public List<BluetoothDevice> getListaDispostivo(){
        return listaDispostivo;
    }

    //region getDispositivosPareados: Retorna todos dispositivos que já estão pareados com o aparelho
    private void getDispositivosPareados() {
        Set<BluetoothDevice> pairedDevicesList = dispositivo.getBondedDevices();

        if (pairedDevicesList.size() > 0) {
            for (BluetoothDevice device : pairedDevicesList) {
                listaDispostivo.add(device);
            }
        }
    }
    //endregion

    //region verificarEstado: Verifica se o recurso do Bluetooth está ativo
    public Estado verificarEstado() {
        if (dispositivo == null) {
            return Estado.NAO_COMPATIVEL;
        }
        if (!dispositivo.isEnabled()) {
            return Estado.DESLIGADO;
        }

        return Estado.LIGADO;
    }
    //endregion

    //region iniciarBusca: Inicia a busca de dispositivos que não estão pareados
    public void iniciarBusca(Context context, BluetoothListener listener) {
        Bluetooth bluetooth = new Bluetooth(listener);

        // Registro os Broadcast necessarios para a busca de dispositivos
        IntentFilter filter = new IntentFilter(BluetoothListener.ACTION_FOUND);
        IntentFilter filter2 = new IntentFilter(BluetoothListener.ACTION_DISCOVERY_FINISHED);
        IntentFilter filter3 = new IntentFilter(BluetoothListener.ACTION_DISCOVERY_STARTED);
        context.registerReceiver(bluetooth, filter);
        context.registerReceiver(bluetooth, filter2);
        context.registerReceiver(bluetooth, filter3);

        // inicio a busca e retorno a classe instanciada.
        dispositivo.startDiscovery();
    }
    //endregion

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        //caso encontre um dispositivo:
        if (action.compareTo(BluetoothDevice.ACTION_FOUND) == 0) {

            //pega as o dispositivo encontrado:
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            //se a lista já tiver esse dispositivo eu retorno para o proximo
            //isso permite que sejá mostrado somente uma vez meu dispositivo
            //problema muito comum em exemplos
            if (listaDispostivo.contains(device)) {
                return;
            }

            //adiciono o dispositivo na minha lista:
            listaDispostivo.add(device);

        } else if (action.compareTo(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) == 0) {
            //caso o discovery chegue ao fim eu desregistro meus broadcasts
            //SEMPRE FAÇA ISSO quando terminar de usar um broadcast
            context.unregisterReceiver(this);
        }

        if (listener != null) {
            //se foi definido o listener eu aviso a quem ta gerenciando.
            listener.action(action);
        }
    }
}

I put the break-point on the listaDispostivo.add(device) line of the Bluetooth class and it's passing through it normally. Even filling the list with the expected value. The error is that this is not reported in the setAdapter() list.

If anyone can give me a light of where I am wrong I thank:)

    
asked by anonymous 06.08.2015 / 18:46

1 answer

1

After filling in the List lstBluetooth you should call the notifyDataSetChanged(); event of your Adapter as follows:

itemBluetooth.notifyDataSetChanged();

So it updates your ListView

    
11.09.2015 / 21:48