【问题标题】:android bluetooth pairing request and wait for successandroid蓝牙配对请求并等待成功
【发布时间】:2016-07-27 15:06:08
【问题描述】:

我正在为 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){}
}

}

【问题讨论】:

    标签: android bluetooth


    【解决方案1】:

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

    【讨论】:

    • 没有什么像“ACTION_BOND_STATE_CHANGED”
    • 根据官方文档,从 API LEVEL 5 开始就有这个广播动作,所以试一试。如果我创建一个侦听 android.bluetooth.device.action.BOND_STATE_CHANGED 的 BroadcastReceiver 组件,它对我有用
    猜你喜欢
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 2017-04-21
    • 2015-05-15
    相关资源
    最近更新 更多