我正在构建一个需要通过蓝牙与其他设备通信的应用,我正在使用http://developer.android.com/guide/topics/connectivity/bluetooth.html中的以下代码。
代码运行没有任何错误,但即使在附近的设备上打开可见性也没有发现设备,但是当我打开应用程序后手动在手机上进行蓝牙设置时突然发现,我已经测试过了这个在Android 6.0和Android 4.4.2上,任何帮助将不胜感激!代码如下:
private BluetoothAdapter mBluetoothAdapter;
Context context;
ListView lv;
ArrayList<String> listItems=new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkin);
context=getApplicationContext();
lv=(ListView)findViewById(R.id.listView);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listItems.add("Hello");
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
lv.setAdapter(adapter);
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
mBluetoothAdapter.startDiscovery();
}
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
listItems.add(device.getName());
adapter.notifyDataSetChanged();
if(device.getName().equalsIgnoreCase("AnoudisBT")) {
pairDevice(device);
unregisterReceiver(mReceiver);
}
}
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.d("antinom","Started Scan");
}
}
};
private void pairDevice(BluetoothDevice device) {
try {
Log.d("TAG", "Start Pairing...");
Method m = device.getClass()
.getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
Log.d("TAG", "Pairing finished.");
} catch (Exception e) {
Log.e("TAG", e.getMessage());
}
}