有人知道为什么我的代码没有达到ACTION_DISCOVERY_STARTED吗?

时间:2014-12-28 19:03:44

标签: java android bluetooth device

我正在开发一个Android应用程序。此应用需要通过蓝牙查找和连接一台设备,但它无法正常工作。

当我点击按钮查找设备时,它无法正常工作。

这是我的代码:

package com.example.alvar.graficos;

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.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class Bluetooth extends ActionBarActivity {

    private Button btnBluetooth;
    private Button btnBuscarDispositivo;
    private ListView lvDispositivos;
    private BluetoothAdapter bAdapter;
    private BroadcastReceiver bReceiver;
    private List<BluetoothDevice> arrayDevices;

    private static final int REQUEST_ENABLE_BT = 1;

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

        btnBluetooth = (Button)findViewById(R.id.btnBluetooth);
        btnBuscarDispositivo = (Button)findViewById(R.id.btnBuscarDispositivo);
        lvDispositivos = (ListView)findViewById(R.id.lvDispositivos);
        bAdapter = BluetoothAdapter.getDefaultAdapter();
        arrayDevices = new ArrayList<BluetoothDevice>();
        ((Button) findViewById(R.id.btnBluetooth)).setText(R.string.ActivarBluetooth);
        bReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent){
                String action = intent.getAction();
                int estado = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.ERROR);
                    switch (action){
                        case BluetoothAdapter.ACTION_STATE_CHANGED: {
                            switch (estado){
                                case BluetoothAdapter.STATE_OFF:{
                                    ((Button)findViewById(R.id.btnBluetooth)).setText(R.string.ActivarBluetooth);
                                    break;
                                }
                                case BluetoothAdapter.STATE_ON: {
                                    ((Button) findViewById(R.id.btnBluetooth)).setText(R.string.DesactivarBluetooth);
                                    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                                    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
                                    startActivity(discoverableIntent);
                                    break;
                                }
                                default: break;
                            }
                        }
                        case BluetoothDevice.ACTION_FOUND:{
                            if(arrayDevices == null) {
                                arrayDevices = new ArrayList<BluetoothDevice>();
                            }
                            BluetoothDevice dispositivo = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            arrayDevices.add(dispositivo);
                            String descripcionDispositivo = dispositivo.getName() + " [" + dispositivo.getAddress() + "]";
                            Toast.makeText(getBaseContext(), "Dispositivo detectado: " + descripcionDispositivo, Toast.LENGTH_SHORT).show();
                            break;
                        }
                        case BluetoothAdapter.ACTION_DISCOVERY_STARTED:{
                            ((TextView) findViewById(R.id.estado)).setText("Buscando dispositivos");
                            break;
                        }
                        case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:{
                            ((TextView)findViewById(R.id.estado)).setText("Busqueda terminada");

                            ArrayAdapter arrayAdapter = new BluetoothDeviceArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_2, arrayDevices);

                            lvDispositivos.setAdapter(arrayAdapter);
                            Toast.makeText(getBaseContext(), "Fin de la búsqueda", Toast.LENGTH_LONG).show();
                            break;
                        }
                        default:break;
                    }

            }
        };
        registrarReciever();
    }

    private void registrarReciever() {
        IntentFilter filtro = new IntentFilter();
        filtro.addAction(BluetoothDevice.ACTION_FOUND);
        filtro.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filtro.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filtro.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(bReceiver, filtro);
    }


    @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_bluetooth, menu);
        return true;
    }

    @Override
    public void onDestroy() {
        this.unregisterReceiver(bReceiver);
        super.onDestroy();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

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

        return super.onOptionsItemSelected(item);
    }

    public void btnClick(View view){
        if(bAdapter.isEnabled()){
            bAdapter.disable();
        }else{
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }

    public void btnBuscar(View view){
        if(arrayDevices != null) {
            arrayDevices.clear();
        }
        if(bAdapter.isDiscovering()) {
            bAdapter.cancelDiscovery();
        }

        if(bAdapter.startDiscovery()) {
            Toast.makeText(this, "Iniciando búsqueda de dispositivos bluetooth", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this, "Error al iniciar búsqueda de dispositivos bluetooth", Toast.LENGTH_SHORT).show();
        }
        int cont=0;
        while(bAdapter.isDiscovering()){
            Toast.makeText(this, "Buscando -> "+(++cont), Toast.LENGTH_SHORT).show();
        }
    }

    public class BluetoothDeviceArrayAdapter extends ArrayAdapter {

        private List<BluetoothDevice> deviceList;
        private Context context;

        public BluetoothDeviceArrayAdapter(Context context, int textViewResourceId,
                                           List<BluetoothDevice> objects) {
            super(context, textViewResourceId, objects);

            this.deviceList = objects;
            this.context = context;
        }

        @Override
        public int getCount(){
            if(deviceList != null){
                return deviceList.size();
            }else{
                return 0;
            }
        }

        @Override
        public Object getItem(int position){
            if(deviceList!=null){
                return deviceList.get(position);
            }else{
                return null;
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            if((deviceList == null) || (context == null)) {
                return null;
            }
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View elemento = inflater.inflate(android.R.layout.simple_list_item_2, parent, false);
            TextView tvNombre = (TextView)elemento.findViewById(android.R.id.text1);
            TextView tvDireccion = (TextView)elemento.findViewById(android.R.id.text2);
            BluetoothDevice dispositivo = (BluetoothDevice)getItem(position);
            if(dispositivo != null){
                tvNombre.setText(dispositivo.getName());
                tvDireccion.setText(dispositivo.getAddress());
            }else{
                //txtNombre.setText("ERROR");
                tvNombre.setText("ERROR");
                tvDireccion.setText("No disponible");
            }
            return elemento;
        }
    }
}

这是布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.alvar.graficos.Bluetooth">

    <Button
        android:id="@+id/btnBluetooth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:onClick="btnClick"/>

    <Button
        android:id="@+id/btnBuscarDispositivo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="btnBuscar"
        android:layout_below="@+id/btnBluetooth"
        android:layout_alignLeft="@+id/btnBluetooth"
        android:layout_alignStart="@+id/btnBluetooth"
        android:text="@string/buscarDispositivos"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Busqueda no iniciada"
        android:id="@+id/estado"
        android:layout_below="@+id/btnBuscarDispositivo"
        android:layout_alignLeft="@+id/btnBuscarDispositivo"
        android:layout_alignStart="@+id/btnBuscarDispositivo"
        android:layout_centerHorizontal="true" />

    <ListView
        android:id="@+id/lvDispositivos"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="7"/>

</RelativeLayout>

由于frejese评论,我编辑帖子为您提供更多信息: 在这个活动中,我在这个应用程序中还有两个,我尝试通过blutooth找到并连接其他设备。我设法打开/关闭蓝牙。但是,当我尝试开始扫描它假定TextView应该改变

case BluetoothAdapter.ACTION_DISCOVERY_STARTED:{
                                ((TextView) findViewById(R.id.estado)).setText("Buscando dispositivos");
                                break;
                            }

但它确实做了什么。当我点击按钮。吐司出现,没有显示错误,但它确实找到任何设备。我不得不说通过设置 - &gt;连接 - &gt;蓝牙,手机正在寻找其他设备,所以我丢弃了蓝牙的选项。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

确保您对AndroidManifest.xml具有适当的权限

 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />

答案 1 :(得分:0)

谢谢你们,但我已经解决了。不知道怎么做。现在它的工作。我删除了所有的内容并重写了整个课程,现在它正在工作。