Error returning list to activity

2

I made an implementation on Android to return all Bluetooth devices (paired and connected) in a list. It worked correctly to return paired devices. For the connected ones it worked also, if I go through the debug mode I see that the application goes through the coding of BroadcastReceiver and fills my list of devices, but when calling the method in activity the return I have is always 0. I just can not understand what's wrong. Could someone give me a hand? Thanks for the help right now!

Reader.java

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

import android.app.Activity;
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 android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import br.ufscar.dc.controledepatrimonio.R;

public class Leitor {
    public enum BluetoothEstado {LIGADO, DESLIGADO, NAO_COMPATIVEL;}
    private BluetoothEstado estado;

    public final String ACTION_DISCOVERY_STARTED = BluetoothAdapter.ACTION_DISCOVERY_STARTED;
    public final String ACTION_FOUND = BluetoothDevice.ACTION_FOUND;
    public final String ACTION_DISCOVERY_FINISHED = BluetoothAdapter.ACTION_DISCOVERY_FINISHED;
    public static final String ACTION_REQUEST_ENABLE = BluetoothAdapter.ACTION_REQUEST_ENABLE;
    public static final int REQUEST_ENABLE_BT = 0;

    private List<BluetoothDevice> listaDispositivo = new ArrayList<>();
    private BluetoothAdapter bluetoothAdapter;
    private Activity activity;

    public List<BluetoothDevice> getListaDispositivo() {
        return listaDispositivo;
    }

    public BluetoothEstado getEstado() {
        if (bluetoothAdapter == null) {
            return BluetoothEstado.NAO_COMPATIVEL;
        } else {
            if (!bluetoothAdapter.isEnabled()) {
                return BluetoothEstado.DESLIGADO;
            }
            return BluetoothEstado.LIGADO;
        }
    }

    public Leitor(Activity activity) {
        this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        this.activity = activity;

        buscarBluetooth();
        registrarBroadcast();
    }

    //region buscarBluetooth: RETORNA TODOS DISPOSITIVOS BLUETOOTH
    public void buscarBluetooth() {
        listaDispositivo.clear();

        if (getEstado() == BluetoothEstado.LIGADO) {
            dispositivosPareados();
            dispositivosConectados();
        }
    }
    ///endregion

    //region dispositivosPareados: RETORNA OS DISPOSITIVOS PAREADOS COM O APARELHO
    private void dispositivosPareados() {
        Set<BluetoothDevice> pairedDevicesList = bluetoothAdapter.getBondedDevices();

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

    private void registrarBroadcast () {
        // Registro os Broadcast necessarios para a busca de dispositivos
        IntentFilter filter = new IntentFilter(LeitorListener.ACTION_FOUND);
        IntentFilter filter2 = new IntentFilter(LeitorListener.ACTION_DISCOVERY_FINISHED);
        IntentFilter filter3 = new IntentFilter(LeitorListener.ACTION_DISCOVERY_STARTED);
        activity.registerReceiver(mReceiver, filter);
        activity.registerReceiver(mReceiver, filter2);
        activity.registerReceiver(mReceiver, filter3);
    }

    private void dispositivosConectados() {
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        bluetoothAdapter.startDiscovery();
    }

    //region pararBusca: PARA DE PROCURAR POR DISPOSITIVOS BLUETOOTH
    public void pararBusca ()  {
        if (bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.cancelDiscovery();
        }
    }
    //endregion

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.compareTo(BluetoothDevice.ACTION_FOUND) == 0) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                listaDispositivo.add(device);
            }
        }
    };
}

ListBluetoothActivity.java

package br.ufscar.dc.controledepatrimonio.Forms;

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 br.ufscar.dc.controledepatrimonio.R;
import br.ufscar.dc.controledepatrimonio.Util.RFID.Leitor;

public class ListarBluetoothActivity extends AppCompatActivity {
    private ListView lstBluetooth;
    private Leitor leitor;

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

        iniciarTela();

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

            @Override
            public void onClick(View arg0) {
                leitor.buscarBluetooth();
                Toast.makeText(getApplicationContext(), "TOTAL DISPOSITIVOS: " + leitor.getListaDispositivo().size(), Toast.LENGTH_LONG).show();
            }
        });
        //endregion
    }

    //region Métodos da tela
    private void iniciarTela() {
        leitor = new Leitor(this);

        switch (leitor.getEstado()) {
            case LIGADO:
                Toast.makeText(getApplicationContext(), "TOTAL DISPOSITIVOS: " + leitor.getListaDispositivo().size(), Toast.LENGTH_LONG).show();
                break;
            case DESLIGADO:
                Intent enableBtIntent = new Intent(Leitor.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, Leitor.REQUEST_ENABLE_BT);
                break;
            case NAO_COMPATIVEL:
                Toast.makeText(getApplicationContext(), R.string.msg_bluetooth_nao_suportado, Toast.LENGTH_LONG).show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == leitor.REQUEST_ENABLE_BT) {
            switch (resultCode) {
                case RESULT_CANCELED:
                    //Não habilitou Bluetooth, então fecha a tela.
                    finish();
                    break;
                case RESULT_OK:
                    leitor.buscarBluetooth();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            leitor.pararBusca();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finish();
    }
    //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
}
    
asked by anonymous 09.08.2015 / 00:32

1 answer

2

The process of getting connected / paired devices takes some time to complete. At the time that Toast is run, in the onClick() method, shortly after the leitor.buscarBluetooth(); call, there was not enough time for the device list to be populated.

You have to declare a method in your Activity , which will be called after the process of getting the devices finished.

In this method you pass the list to your adapter to appear in ListView .

I've never written code that uses Bluetooth but I believe that in BradcastReceiver , if the Action received is BluetoothAdapter.ACTION_DISCOVERY_FINISHED already has the list filled . Call the Activity method at this point.

It would be something like this:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.compareTo(BluetoothDevice.ACTION_FOUND) == 0) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            listaDispositivo.add(device);
        }
        else if(action.compareTo(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) == 0){

            activity.onDiscoveryFinished(listaDispositivo);
        }
    }
};
    
09.08.2015 / 15:58