簡體   English   中英

android藍牙配對請求並等待成功

[英]android bluetooth pairing request and wait for success

我正在為API級別2.2設計此應用

我想與一個可用的藍牙設備配對,然后收聽聽音樂,我通過以下方式做到了:

 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,其中包含可用的設備名稱,並且配對設備將“(Paired)”與設備名稱配對。 您可以清楚地看到,如果設備已經配對,則我想打開一個新活動;如果尚未配對,則啟動配對過程。 現在的問題是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){}
}

}

您還可以注冊ACTION_BOND_STATE_CHANGED廣播,並檢查其額外字段以檢查綁定過程的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM