2014-02-04 3 views
0

Это абсолютно здорово, я получил свое приложение, работающее на 100% (это только устройства, которые не подключены), но когда я его запускаю, в моем ListView не появляется какое-либо устройство Bluetooth, самая забавная часть когда я выполняю его с помощью отладчика, они появляются. Здесь вы мой код, я смотрел на него в течение последних 3-х часов, надеюсь, что вы можете посадить меня за руку :(Список устройств Bluetooth для Android

import android.os.Bundle; 
import android.app.Activity; 
import android.app.ListActivity; 
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.view.Menu; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 

public class ListarDispositivos extends ListActivity { 
    //this, R.layout.activity_listar_dispositivos, s 

    private BluetoothAdapter mBtAdapter; 
    private ArrayAdapter<String> mNewDevicesArrayAdapter; 
    private static String EXTRA_DEVICE_ADDRESS = "device_address"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_listar_dispositivos); 

     mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.nombres_dispositivos,R.id.txvNombreDispositivo); 

     ListView listview = getListView(); 

     setListAdapter(mNewDevicesArrayAdapter); 
     //listview.setOnItemClickListener(mDeviceClickListener); 

     IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
     this.registerReceiver(mReceiver, filter); 

     filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
     this.registerReceiver(mReceiver, filter); 

     mBtAdapter = BluetoothAdapter.getDefaultAdapter(); 

     doDiscovery(); 

     Intent discoverableIntent = new 
       Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 
       discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); 
       startActivity(discoverableIntent); 


    } 

    protected void onDestroy() { 
     super.onDestroy(); 

     // Make sure we're not doing discovery anymore 
     if (mBtAdapter != null) { 
      mBtAdapter.cancelDiscovery(); 
     } 

     mBtAdapter.disable(); 

     // Unregister broadcast listeners 
     this.unregisterReceiver(mReceiver); 

    } 

    private void doDiscovery() { 

     // Indicate scanning in the title 
     setTitle("Escaneando"); 

     // If we're already discovering, stop it 
     if (mBtAdapter.isDiscovering()) { 
      mBtAdapter.cancelDiscovery(); 
     } 

     // Request discover from BluetoothAdapter 
     mBtAdapter.startDiscovery(); 
       Toast toast1 = 
         Toast.makeText(getApplicationContext(), 
           "Estoy buscando", Toast.LENGTH_SHORT); 

       toast1.show(); 

    } 

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { 
      // Cancel discovery because it's costly and we're about to connect 
      mBtAdapter.cancelDiscovery(); 

      // Get the device MAC address, which is the last 17 chars in the View 
      String info = ((TextView)v).getText().toString(); 
      String address = info.substring(info.length() - 17); 

      // Create the result Intent and include the MAC address 
      Intent intent = new Intent(); 
      intent.putExtra(EXTRA_DEVICE_ADDRESS, address); 

      // Set result and finish this Activity 
      setResult(Activity.RESULT_OK, intent); 
      finish(); 
     } 
    }; 

    //Salta cada vez que encuentra un dispositivo o eso deberia el cabron 

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      // When discovery finds a device 
      if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
       // Get the BluetoothDevice object from the Intent 
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
       // If it's already paired, skip it, because it's been listed already 
       if (device.getBondState() != BluetoothDevice.BOND_BONDED) { 
        mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
       } 
      // When discovery is finished, change the Activity title 
      } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 

       setTitle("Elija dispositivo"); 
       if (mNewDevicesArrayAdapter.getCount() == 0) { 
        String noDevices = "No encontrado"; 
        mNewDevicesArrayAdapter.add(noDevices); 
       } 
      } 
     } 

    }; 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.listar_dispositivos, menu); 
     return true; 
    } 

} 

ответ

1

После добавления найденных устройств к mNewDevicesArrayAdapter, вы должны вызвать notifyDataSetChanged() так, что ListView обновляется.

+0

Я пробовал ваше решение, но оно не работает, проблема в том, что когда я пытаюсь использовать его на устройствах отладчика, другие, но они не ... Во всяком случае, спасибо за быстрый ответ :) – Ejher

Смежные вопросы