本文介绍了使用API​​ RFCOMM Buletooth套接字创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建发送请求RFCOMM蓝牙接口,并使用blutooth得到服务器的响应。需要创造在客户端的蓝牙接口请求和响应采用了android蓝牙API。
如何创建这个..

I need to create RFCOMM Bluetooth socket for send request and get response from server using blutooth. need to creat bluetooth socket in client side for request and response using android bluetooth api.How can i create this..

我试过像这样

public class MainActivity extends Activity {
      TextView out;
      private static final int REQUEST_ENABLE_BT = 1;
      private BluetoothAdapter btAdapter = null;
      private BluetoothSocket btSocket = null;
      private OutputStream outStream = null;

      // Well known SPP UUID
      private static final UUID MY_UUID =
          UUID.fromString("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

      // Insert your server's MAC address
      private static String address = "xxxxxxxxxxxxxxxx";

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

        out = (TextView) findViewById(R.id.out);

      //  out.append("\n...In onCreate()...");

        btAdapter = BluetoothAdapter.getDefaultAdapter();
        CheckBTState();
      }

      @Override
      public void onStart() {
        super.onStart();
     //   out.append("\n...In onStart()...");
      }

      @Override
      public void onResume() {
        super.onResume();

        out.append("\n...In onResume...\n...Attempting client connect...");

        // Set up a pointer to the remote node using it's address.
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case we are using the
        //     UUID for SPP.
        try {
          btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
          AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }


        // Discovery is resource intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        try {
          btSocket.connect();
          out.append("\n...Connection established and data link opened...");
        } catch (IOException e) {
          try {
            btSocket.close();
          } catch (IOException e2) {
            AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
          }
        }

        // Create a data stream so we can talk to server.
        out.append("\n...Sending message to server...");

        try {
          outStream = btSocket.getOutputStream();
        } catch (IOException e) {
          AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
        }


        String message = "DECapabilities?$format=json";
        byte[] msgBuffer = message.getBytes();
        try {
          outStream.write(msgBuffer);
        } catch (IOException e) {
          String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
          if (address.equals("00:00:00:00:00:00")) 
            msg = msg + ".\n\nUpdate your server address from 08:ED:B9:48:EE:C0 to the correct address on line 37 in the java code";
          msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

          AlertBox("Fatal Error", msg);       
        }
      }

      @Override
      public void onPause() {
        super.onPause();

        out.append("\n...In onPause()...");

        if (outStream != null) {
          try {
            outStream.flush();
          } catch (IOException e) {
            AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
          }
        }

        try     {
          btSocket.close();
        } catch (IOException e2) {
          AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
        }
      }

      @Override
      public void onStop() {
        super.onStop();
        out.append("\n...In onStop()...");
      }

      @Override
      public void onDestroy() {
        super.onDestroy();
        out.append("\n...In onDestroy()...");
      }

      private void CheckBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on

        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) { 
          AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
        } else {
          if (btAdapter.isEnabled()) {
            out.append("\n...Bluetooth is enabled...");
          } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
          }
        }
      }

      public void AlertBox( String title, String message ){
        new AlertDialog.Builder(this)
        .setTitle( title )
        .setMessage( message + " Press OK to exit." )
        .setPositiveButton("OK", new OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
              finish();
            }
        }).show();
      }
    }

但得到插槽封闭例外。

but getting socket closed exception.

推荐答案

我解决了这个由BluetoothChat code它的帮助我非常多。

I solved this by BluetoothChat code its help me very much.

<一个href=\"http://grep$c$c.com/file/repository.grep$c$c.com/java/ext/com.google.android/android-apps/2.1_r2/com/example/android/BluetoothChat/BluetoothChat.java\" rel=\"nofollow\">http://grep$c$c.com/file/repository.grep$c$c.com/java/ext/com.google.android/android-apps/2.1_r2/com/example/android/BluetoothChat/BluetoothChat.java

这篇关于使用API​​ RFCOMM Buletooth套接字创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 02:50