如何通过蓝牙android发送/接收字符串到另一个android手机 [英] How to Send/receive string via bluetooth android to another android phone

查看:112
本文介绍了如何通过蓝牙android发送/接收字符串到另一个android手机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的android应用程序中,我想通过蓝牙将字符串从一台设备发送到另一台设备.可用设备显示在列表视图中…….我想发送不成对的字符串...我无法在设备之间建立连接...谁能帮我建立连接并发送字符串...我有很多示例,但无法弄清楚文件传输需要什么东西.如果有人这样做已经请帮助我.未完成的代码在下面给出

In my android application I want to send the string from one device to another via Bluetooth. Available devices are shown in the list view…. I want to send the string with out pairing … I m failed to establish the connection between the devices… Can anyone help me to establish the connection and to send the string…i have lot of examples but cant figure out what stuff needed for file transfer. if anyone do it already pls help me. Uncompleted code is given below

public class MainActivity extends Activity 
{

    ToggleButton tb1;
    Button tb2, tb3;
    String tbstate1, tbstate2, tbstate3;
    EditText textPhoneNo, textTo;
    BluetoothAdapter myBTadapter;
    ArrayAdapter<String> btArrayAdapter;
    String tbstate;
    ListView listDevicesFound;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tb1 = (ToggleButton) findViewById(R.id.m_m_btn);
        tb2 = (Button) findViewById(R.id.sms_btn);
        tb3 = (Button) findViewById(R.id.email_btn);




        myBTadapter = BluetoothAdapter.getDefaultAdapter();


        listDevicesFound = (ListView) findViewById(R.id.devicesfound);
        btArrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1);
        listDevicesFound.setAdapter(btArrayAdapter);

//      listDevicesFound.setAdapter(detectedAdapter);
//      listDevicesFound = new ListItemClicked();
//       detectedAdapter.notifyDataSetChanged();
//      

        registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));



                tb1.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        tbstate = tb1.getText().toString();
                        if (tbstate.equals("ON"))
                        {
                            if (myBTadapter == null) 
                            {
                                tb1.setEnabled(false);

                            }
                            else
                            {
                                if (myBTadapter.isEnabled())

                                {
                                    myBTadapter.startDiscovery();

                                //  Toast.makeText(getApplicationContext(), "Bluetooth 1 ",Toast.LENGTH_LONG).show();

                                    //myBTadapter.disable();
                                }

                                else 
                                {

                                    myBTadapter.enable();
                                    myBTadapter.startDiscovery();

                                    //Toast.makeText(getApplicationContext(), "Bluetooth 2 ",Toast.LENGTH_LONG).show();

                                }


                            }


                            // check the status and set the button text
                            // accordingly

                                }
                        else
                        {
                            myBTadapter.disable();
                            btArrayAdapter.clear();
                            /*if (myBTadapter.isEnabled())

                            {
                                myBTadapter.disable();
                            }
                            else 
                            {
                                Toast.makeText(getApplicationContext(), "Bluetooth 3 ",Toast.LENGTH_LONG).show();
                            }   */
                        } 

                    }
                }
                );

            }



    private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() 
    {

        @Override
        public void onReceive(Context context, Intent intent) 
        {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action))
            {
                BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                btArrayAdapter.add(device.getName() + "\n"+ device.getAddress());
                btArrayAdapter.notifyDataSetChanged();
            }
        }

    };


}

推荐答案

如果通过蓝牙发送,则需要创建一个UUID对象并使用它来打开套接字连接.我使用了一个线程来监听即将到来的数据.您还需要一个功能来打开和关闭蓝牙连接.

If you are sending via Bluetooth, you need to make a UUID object and use it to open the socket connection. I used a thread to listen for in coming data. you will also need a function to open and close the bluetooth connection.

void openBT() throws IOException {
     UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard                //SerialPortService ID
     mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);    
     mmSocket.connect();
     mmOutputStream = mmSocket.getOutputStream();
     mmInputStream = mmSocket.getInputStream();
     beginListenForData();
     myLabel.setText("Bluetooth Opened");
}

void beginListenForData() {
     final Handler handler = new Handler(); 
     final byte delimiter = 10; //This is the ASCII code for a newline character

     stopWorker = false;
     readBufferPosition = 0;
     readBuffer = new byte[1024];
     workerThread = new Thread(new Runnable() {
          public void run() {
               while(!Thread.currentThread().isInterrupted() && !stopWorker) {
                    try {
                        int bytesAvailable = mmInputStream.available();            
                        if(bytesAvailable > 0) {
                        byte[] packetBytes = new byte[bytesAvailable];
                        mmInputStream.read(packetBytes);
                        for(int i=0;i<bytesAvailable;i++) {
                             byte b = packetBytes[i];
                             if(b == delimiter) {
                                  byte[] encodedBytes = new byte[readBufferPosition];
                                  System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                  final String data = new String(encodedBytes, "US-ASCII");
                                  readBufferPosition = 0;

                                  handler.post(new Runnable() {
                                       public void run() {
                                            myLabel.setText(data);
                                       }
                                  });
                             }else {
                                  readBuffer[readBufferPosition++] = b;
                             }
                        }
                   }
              }catch (IOException ex) {
                   stopWorker = true;
              }
         }
    }
});

workerThread.start();
}

void sendData() throws IOException {
     String msg = myTextbox.getText().toString();
     msg += "\n";
     //mmOutputStream.write(msg.getBytes());
     mmOutputStream.write('A');
     myLabel.setText("Data Sent");
}

这篇关于如何通过蓝牙android发送/接收字符串到另一个android手机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆