android bluetooth配对请求并等待成功

时间:2016-07-27 15:06:09

标签: android bluetooth

我正在为api level 2.2

设计这个应用程序

我希望配对可用的蓝牙设备,然后听ststus, 我通过以下方式做到了这一点:

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if(btAdapter.isDiscovering()){
                btAdapter.cancelDiscovery();
            }
            if(!listAdapter.getItem(i).contains("Paired")){
                try {
                    BluetoothDevice selectedDevice = devices.get(i);
                    pairDevice(selectedDevice);
                    Intent intent=new Intent(getBaseContext(),ConnectedBtActivity.class);
                    intent.putExtra("MAC",selectedDevice.getAddress());
                    startActivity(intent);
                }
                catch (Exception e){}
            }
            else{
                BluetoothDevice selectedDevice = devices.get(i);
                Intent intent=new Intent(getBaseContext(),ConnectedBtActivity.class);
                intent.putExtra("MAC",selectedDevice.getAddress());
                startActivity(intent);
            }
        }
    });

private void pairDevice(BluetoothDevice device) {
    try {
        Method m = device.getClass().getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
    } catch (Exception e) {
        Toast.makeText(getBaseContext(),"Exception: "+e.getMessage(),Toast.LENGTH_LONG ).show();
    }
}

这里listView包含所有可用的设备,listAdapter是一个ArrayAdapter,它包含可用的设备名称,对于对设备,“(已配对)”包含设备名称。 如果设备已配对且未配对,则可以清楚地看到我想要打开新活动,然后启动配对过程。现在的问题是pairDevice()是一个多线程进程,这意味着不会等到配对完成。我想听听在新活动打开后是否完成配对。 为了更好地澄清,我发布了完整的代码:

public class MyBluetoothScanActivity extends AppCompatActivity{


Button bt,bt_count;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
IntentFilter filter;
BroadcastReceiver receiver;
ArrayAdapter<String> listAdapter;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;

int count=0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_bluetooth_scan);

    bt=(Button) findViewById(R.id.bT_scan2);
    bt.setTransformationMethod(null);

    bt_count=(Button) findViewById(R.id.bt_count);
    bt_count.setTransformationMethod(null);

    bt_count.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getBaseContext(),"Count: "+count,Toast.LENGTH_SHORT ).show();
        }
    });




    listView=(ListView) findViewById(R.id.listViewscan);

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

    if(!btAdapter.isEnabled()){
        turnOnBT();
    }


    init();

    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            newScan();
        }
    });


    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if(btAdapter.isDiscovering()){
                btAdapter.cancelDiscovery();
            }
            if(!listAdapter.getItem(i).contains("Paired")){
                try {
                    BluetoothDevice selectedDevice = devices.get(i);
                    pairDevice(selectedDevice);
                    Intent intent=new Intent(getBaseContext(),ConnectedBtActivity.class);
                    intent.putExtra("MAC",selectedDevice.getAddress());
                    startActivity(intent);
                }
                catch (Exception e){}
            }
            else{
                BluetoothDevice selectedDevice = devices.get(i);
                Intent intent=new Intent(getBaseContext(),ConnectedBtActivity.class);
                intent.putExtra("MAC",selectedDevice.getAddress());
                startActivity(intent);
            }
        }
    });
}

private void newScan(){
    btAdapter.cancelDiscovery();
    Toast.makeText(getBaseContext(),"New Scan Start",Toast.LENGTH_SHORT ).show();

    listAdapter= new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);

    devices = new ArrayList<BluetoothDevice>();
    btAdapter.startDiscovery();
}
private void getPairedDevices() {
    devicesArray = btAdapter.getBondedDevices();
    if(devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());

        }
    }
}

void turnOnBT(){
    Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivity(intent);
}

void init(){

    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            Toast.makeText(getBaseContext(),"new br: "+action,Toast.LENGTH_LONG ).show();

            if(BluetoothDevice.ACTION_FOUND.equals(action)){

                pairedDevices=new ArrayList<String>();
                getPairedDevices();
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                Toast.makeText(getBaseContext(),"Dev: "+device.getName(),Toast.LENGTH_LONG ).show();
                devices.add(device);
                String s = "";
                for(int a = 0; a < pairedDevices.size(); a++){
                    if(device.getName().equals(pairedDevices.get(a))){
                        //append
                        s = "(Paired)";
                        break;
                    }
                }

                listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());

            }
            else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if(btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }

        }
    };

    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(receiver, filter);

}

private void pairDevice(BluetoothDevice device) {
    try {
        Method m = device.getClass().getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
    } catch (Exception e) {
        Toast.makeText(getBaseContext(),"Exception: "+e.getMessage(),Toast.LENGTH_LONG ).show();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    try {
        Toast.makeText(getBaseContext(),"Un registration",Toast.LENGTH_SHORT ).show();
        unregisterReceiver(receiver);
    }
    catch (Exception e){}
}

}

1 个答案:

答案 0 :(得分:0)

您还可以注册 ACTION_BOND_STATE_CHANGED 广播,并检查其额外字段以检查绑定过程的结果。