简体   繁体   English

android蓝牙配对请求并等待成功

[英]android bluetooth pairing request and wait for success

I am designing this app for api level 2.2 我正在为API级别2.2设计此应用

I want pair with a available bluetooth device and then listen the ststus, I have done that by the following way: 我想与一个可用的蓝牙设备配对,然后收听听音乐,我通过以下方式做到了:

 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();
    }
}

Here listView contain all the available devices, listAdapter is an ArrayAdapter which contain the available device name and for pair device concate "(Paired)" with device name. 这里listView包含所有可用的设备,listAdapter是一个ArrayAdapter,其中包含可用的设备名称,并且配对设备将“(Paired)”与设备名称配对。 You can clearly see I want to open a new activity if the device already paired and if not paired then initiate the pairing process. 您可以清楚地看到,如果设备已经配对,则我想打开一个新活动;如果尚未配对,则启动配对过程。 Now issue is that pairDevice() is a multi threaded process that means does not wait until the pairing is complete. 现在的问题是pairDevice()是一个多线程进程,这意味着不要等到配对完成。 I want to listen whether the pairing is done or not after that new activity should open. 我想听听在新活动打开后配对是否完成。 For better clarification I am posting full code: 为了更好的说明,我将发布完整代码:

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){}
}

} }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM