这是我的代码
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.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private final BroadcastReceiver 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);
devices.add(device.getName());
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mBtAdapter.startDiscovery();
Toast.makeText(MainActivity.this,"Discovering "+devices.size(),Toast.LENGTH_SHORT).show();
ArrayAdapter arrayAdapter=new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,devices);
listView.setAdapter(arrayAdapter);
}
}
};
ListView listView;
ArrayList<String> devices;
private BluetoothAdapter mBtAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.listView);
devices=new ArrayList<String>();
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();
if(!mBtAdapter.isEnabled()){
mBtAdapter.enable();
}
mBtAdapter.startDiscovery();
}
@Override
protected void onDestroy(){
super.onDestroy();
mBtAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}
}
问题是它始终显示发现0 ,因为设备的大小arrayList始终为0.但是手机检测到附近的可用设备,如下图Screenshot of phone bluetooth settings所示。我认为我的应用广播接收器没有检测到可用的蓝牙设备,因为我的代码中有错误。请帮助我
答案 0 :(得分:1)
您不必两次注册接收器,意图过滤器可以执行多个操作。
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(yourReceiver, intentFilter);
检查您是否具有扫描所需的权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
在正常模式下,并非所有蓝牙设备都可以被发现,请查看BluetoothLeScanner和蓝牙适配器的startLeScan方法:
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
bluetoothAdapter.getBluetoothLeScanner().startScan(yourCallback); // API 21+
bluetoothAdapter.startLeScan(yourCallback); // API 18+
此外,打开设备上的蓝牙需要一些时间,您应该听取蓝牙状态更改并在打开并准备使用后启动发现,请查看此answer。