【问题标题】:Android want to send bluetooth pair request to another devicesAndroid想向其他设备发送蓝牙配对请求
【发布时间】:2014-02-20 06:20:08
【问题描述】:

我想在 android 中搜索和列出蓝牙设备,我的程序现在能够列出所有活动设备但无法向其他设备发送配对请求。我想实现列表元素的这个 onItemClick。如果蓝牙未启用我的设备然后显示对活动设备的权限,如果我选择“是”则可以,但如果我选择“否”则再次显示权限,直到我按“是”..我该怎么做?请帮助代码..这是我的代码..

public class Main extends Activity  {  
    TextView out;
      private static final int REQUEST_ENABLE_BT = 1;
      private BluetoothAdapter btAdapter; 
      private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();
      private ArrayList<String> mylist= new ArrayList<String>();
      private ListView lv;
      private Button btn;
     public Parcelable[] uuidExtra;

      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

      }

      public void search(View view)
      {
          //Register the BroadcastReceiver
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothDevice.ACTION_UUID);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            registerReceiver(ActionFoundReceiver, filter); // Don't forget to unregister during onDestroy

            // Getting the Bluetooth adapter
            btAdapter = BluetoothAdapter.getDefaultAdapter();
            Toast.makeText(getApplicationContext(),"\nAdapter: " + btAdapter,5000).show();

            CheckBTState();
      }

      private void setDeviceList(ArrayList<String> list) {
          lv = (ListView) findViewById(R.id.listView);
            ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
            lv.setAdapter(adapter);

    }

    /* This routine is called when an activity completes.*/
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
          CheckBTState();
        }
      }

      @Override
      protected void onDestroy() {
        super.onDestroy();
        if (btAdapter != null) {
          btAdapter.cancelDiscovery();
        }
        unregisterReceiver(ActionFoundReceiver);
      }

      private void CheckBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on
        // If it isn't request to turn it on
        // List paired devices
        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) { 
          Toast.makeText(getApplicationContext(),"\nBluetooth NOT supported. Aborting.",5000).show();
          return;
        } else {
          if (btAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(),"\nBluetooth is enabled...",5000).show();

            // Starting the device discovery
            btAdapter.startDiscovery();
          } else if (!btAdapter.isEnabled()){
            Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
          }
         /* else{
              Intent intent = new Intent(btAdapter.ACTION_STATE_CHANGED);
            startActivityForResult(intent, RESULT_CANCELED);
          }*/
          }
      }

      private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
         String action = intent.getAction();
         if(BluetoothDevice.ACTION_FOUND.equals(action)) {
           BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
           Toast.makeText(getApplicationContext(),"\n  Device: " + device.getName() + ", " + device,5000).show();
           mylist.add(device.getName());
           setDeviceList(mylist);
         } else {
           if(BluetoothDevice.ACTION_UUID.equals(action)) {
             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
             Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
             for (int i=0; i<uuidExtra.length; i++) {
               Toast.makeText(getApplicationContext(),"\n  Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString(),5000).show();
             }
           } else {
             if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
               Toast.makeText(getApplicationContext(),"\nDiscovery Started...",5000).show();
             } else {
               if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                 Toast.makeText(getApplicationContext(),"\nDiscovery Finished",5000).show();
                 Iterator<BluetoothDevice> itr = btDeviceList.iterator();
                 while (itr.hasNext()) {
                   // Get Services for paired devices
                   BluetoothDevice device = itr.next();
                   Toast.makeText(getApplicationContext(),"\nGetting Services for " + device.getName() + ", " + device,5000).show();
                   if(!device.fetchUuidsWithSdp()) {
                     Toast.makeText(getApplicationContext(),"\nSDP Failed for " + device.getName(),5000).show();
                   }

                 }
               }
             }
           }
          }
        }
      };       

}  

【问题讨论】:

    标签: android bluetooth


    【解决方案1】:

    为时已晚,但这里是代码 -> 您需要使用后台线程作为客户端连接蓝牙设备。 UUID 是通用唯一标识,您可以使用在线 UUID 生成器。用于安全连接,然后与设备获取套接字并与之连接;

    ConnectWithDevice(context : ConnectWithBluetooth, device : BluetoothDevice) : Thread(){
    
        private val mContext : ConnectWithBluetooth = context
        private val mmSocket : BluetoothSocket
        private val mmDevice : BluetoothDevice
        // Default UUID
        private val mmDefaultUUID = UUID.fromString("78c374fd-f84d-4a9e-aa5b-9b0b6292952e")
    
        init {
            var temp : BluetoothSocket? = null
            mmDevice = device
            try {
                // Try here device.createInsecureConnect if it's work then start with this;
                temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)
            }catch (en : NullPointerException){
                en.printStackTrace()
                // Try here device.createInsecureConnect if it's work then start with this;
                temp = device.createRfcommSocketToServiceRecord(mmDefaultUUID)
            }catch (e : IOException){
                e.printStackTrace()
                Log.e("TAG","Socket's create() method failed",e)
            }
            mmSocket = temp!!
            Log.i("TAG","Got the Socket")
        }
    
        override fun run() {
            // Cancel discovery because it otherwise slows down the connection.
            if(mContext.bluetoothAdapter != null){
                mContext.bluetoothAdapter!!.cancelDiscovery()
            }
    
            try{
                // Connect to the remote device through the socket. This call blocks
                // until it succeeds or throws an exception.
                Log.i("TAG","Connecting...")
                mmSocket.connect()
                Log.i("TAG","Bluetooth Successfully Connected")
            }catch (connectException : IOException){
                // Unable to connect; close the socket and return.
                try{
                    mmSocket.close()
                }catch (closeException : IOException){
                    Log.e("TAG","Could not close the client socket",closeException)
                }
                return
            }
            // The connection attempt succeeded. Perform work associated with
            // the connection in a separate thread.
            Log.i("TAG","Device is Connected")
            //manageMyConnectedSocket(mmSocket)
        }
    
        // Closes the client socket and causes the thread to finish.
        // Call this method from the main activity to shut down the connection.
        fun cancel(){
            try {
                mmSocket.close()
            } catch (e: IOException) {
                Log.e(ContentValues.TAG, "Could not close the client socket", e)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-31
      • 1970-01-01
      • 2012-02-29
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多