0
我正在開發一個應用程序,我必須連接到藍牙設備。 我使用「adb push」將我的apk推送到android x86。 Android-x86的藍牙是正常的,它可以掃描藍牙設備。如何在Android中發現藍牙設備?
我在這裏使用兩個按鈕。 按鈕調用「掃描」之一,它列出我已配對的設備。 另一個呼叫發現,它工作是掃描藍牙設備。
現在我可以使用「掃描按鈕」列出已配對的設備。 但是當我想用我的應用程序使用「發現」按鈕來掃描設備時,它總是會在我輸入代碼時崩潰btn_discover.setOnClickListener:
我該怎麼辦?
這是我的代碼。
公共類主要延伸活動{
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_SELECT_DEVICE = 1;
private Button btn_scan;
private Button btn_discover;
private TextView pair_list;
private TextView scan_list;
private Set<BluetoothDevice> pairedDevices;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_scan = (Button)findViewById(R.id.btn_scan);
pair_list = (TextView)findViewById(R.id.pair_list);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
Toast.makeText(this, "No support bluetooth", Toast.LENGTH_SHORT).show();
return;
}else if(mBluetoothAdapter != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_SELECT_DEVICE);
}
//******************scan按鈕動作-將已配對過的藍芽裝置列出來
btn_scan.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0) {
for(BluetoothDevice bDevice : pairedDevices) {
pair_list.append(bDevice.getName() + "\n" + bDevice.getAddress() + "\n" + bDevice.getBondState() + "\n");
}
}
}
});
//******************scan按鈕動作結束
btn_discover.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
});
}
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
scan_list.append(device.getName() + "\n" + device.getAddress() + "\n");
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
} `