Error returning list to Activity

Asked

Viewed 90 times

2

I made an implementation on Android to return all bluetooth devices (paired and connected) in a list. It all worked properly to return the paired devices. For connected also worked, if I go by debug mode I see that the application goes through the coding of BroadcastReceiver and fill in my list of devices, only when calling the method on activity the return I get is at all times 0. I simply cannot understand what is wrong. Could someone give me a hand? I thank you in advance for your help!!!

Java reader.

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);
            }
        }
    };
}

Listarbluetoothactivity.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
}
  • Do the following test: add one more button to your screen to run one Toast with leitor.getListaDispositivo().size(). When running the app. click the button that runs leitor.buscarBluetooth();, let a few seconds pass and click the other button.

  • Hello ramaral! I did the procedure that indicated me here and in this case it worked. There is no way to do the way I want to propose? If not, why not? Thank you very much for your reply!

1 answer

2


The process of obtaining connected/paired devices takes some time to complete.
At the time the Toast is executed, in the method onClick(), right after the call to leitor.buscarBluetooth();, there was not enough time for the list of devices to have been filled in.

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

In this method you pass the list to your Adapter to be presented in Listview.

I never wrote code I used Bluetooth but I believe that, in the Bradcastreceiver, if the Action received for BluetoothAdapter.ACTION_DISCOVERY_FINISHED you will already have the list filled out. Call the Activity then.

It would be something like that:

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);
        }
    }
};
  • I understand the concept! I will apply here. Thanks for the help!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.