2016-04-06 3 views
2

Я разрабатываю приложение для проекта. Он использует bluetooth. Я выполнил шаги для настройки bluetooth с страницы разработчика Google. Я достиг этапа, в котором я могу обеспечить возможность обнаружения. Проблема в том, что я хочу отображать устройства в списке, и они не отображаются. Может быть, кто-то может указать на мою неуклюжесть, поскольку я не вижу проблемы.Проблемы с Bluetooth с моим приложением

public class MainActivity extends AppCompatActivity { 
    private final static int REQUEST_ENABLE_BT = 1; 
    Set<BluetoothDevice> pairedDevices; 
    ArrayAdapter<String> deviceAdapter; 
    ArrayList<String> list; 
    ListView listView; 
    BroadcastReceiver mReceiver; 
    Intent discoverableIntent; 
    IntentFilter intentFilter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     listView = (ListView) findViewById(R.id.devices); 
     list = new ArrayList<>(); 
     deviceAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list); 
     listView.setAdapter(deviceAdapter); 

     BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
     if (bluetoothAdapter == null) 
      Toast.makeText(this, "Bluetooth is not supported!", Toast.LENGTH_SHORT).show(); 
     else { 
      if (!bluetoothAdapter.isEnabled()) { 
       Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
       startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
      } 
     } 

     if (bluetoothAdapter != null) { 
      pairedDevices = bluetoothAdapter.getBondedDevices(); 
     } 
     if (pairedDevices.size() > 0) { 
      for (BluetoothDevice device : pairedDevices) { 
       deviceAdapter.add(device.getName() + "\n" + device.getAddress()); 
      } 
     } 

     mReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       String action = intent.getAction(); 
       if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
        deviceAdapter.add(device.getName() + "\n" + device.getAddress()); 
        Log.d("BT", device.getName() + "\n" + device.getAddress()); 
       } 
      } 
     }; 
     intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
     registerReceiver(mReceiver, intentFilter); 

     if (bluetoothAdapter.isDiscovering()) { 
     bluetoothAdapter.cancelDiscovery(); 
    } 
    bluetoothAdapter.startDiscovery(); 



     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     unregisterReceiver(mReceiver); 
    } 
} 

<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.szili.bluetoothclient.MainActivity"> 

    <ListView 
     android:id="@+id/devices" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 

    </ListView> 
</LinearLayout> 


<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.szili.bluetoothclient"> 
    <uses-permission android:name="android.permission.BLUETOOTH" /> 
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
     <!-- ATTENTION: This was auto-generated to add Google Play services to your project for 
      App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. --> 
     <meta-data 
      android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version" /> 
    </application> 

</manifest> 
+0

Пожалуйста, добавьте манифест. У вас есть разрешение BT? – morynicz

+0

Да. Извините за отсутствие манифеста. –

ответ

1

Вы забыли сканировать устройства:

// Create a BroadcastReceiver for ACTION_FOUND 
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 
    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); 
      // Add the name and address to an array adapter to show in a ListView 
      mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); 
     } 
    } 
}; 
// Register the BroadcastReceiver 
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy 

Для запуска обнаружения устройств, просто вызовите startDiscovery() От: http://developer.android.com/intl/es/guide/topics/connectivity/bluetooth.html

+0

Итак, в основном я вызываю startDiscovery(), прежде чем я создаю широковещательный приемник? –

+1

Вы должны запуститьDiscovery() после создания широковещательного приемника, если вы хотите, чтобы какой-либо прослушиватель обнаружен на устройстве –

+0

Все еще не отображаются устройства в списке. –

1

После некоторых исследований я смог выяснить, в чем проблема. В основном с Android Marshmallow мне нужно было предоставить разрешение на размещение для моего приложения, иначе он не мог сканировать соседние устройства.

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