Android 通过蓝牙发送和接收数据

Android 通过蓝牙发送和接收数据,android,bluetooth,Android,Bluetooth,你可以说我是android开发的新手,我需要一些帮助来将两台设备中的一些数据与我的应用程序同步,我已经做了所有必要的事情,比如搜索可用设备、配对和取消配对。。。我现在需要的是如何在两个设备之间建立连接并发送和接收数据,为了进一步解释,我需要从我的listview中选择一个设备并与之连接,然后让我们假设我有一个文本字段、一个textview和一个按钮,当我点击按钮时,我需要将第一台设备的文本字段中的文本发送到其他设备的文本视图,反之亦然。 以下是我的全部代码: import android.os.

你可以说我是android开发的新手,我需要一些帮助来将两台设备中的一些数据与我的应用程序同步,我已经做了所有必要的事情,比如搜索可用设备、配对和取消配对。。。我现在需要的是如何在两个设备之间建立连接并发送和接收数据,为了进一步解释,我需要从我的listview中选择一个设备并与之连接,然后让我们假设我有一个文本字段、一个textview和一个按钮,当我点击按钮时,我需要将第一台设备的文本字段中的文本发送到其他设备的文本视图,反之亦然。 以下是我的全部代码:

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final int REQUEST_ENABLE_BT = 1;
    private Button onBtn;
    private Button offBtn;
    private Button listBtn;
    private Button findBtn;
    private TextView text;
    private BluetoothAdapter myBluetoothAdapter;
    private Set<BluetoothDevice> pairedDevices;
    private ArrayList<BluetoothDevice> devices;
    private ListView myListView;
    private ArrayAdapter<String> BTArrayAdapter;
    private String tag = "debugging";
    protected static final UUID MY_UUID = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");
    protected static final int SUCCESS_CONNECT = 0;
    protected static final int MESSAGE_READ = 1;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i(tag, "in handler");
            super.handleMessage(msg);
            switch (msg.what) {
            case SUCCESS_CONNECT:
                // DO something
                ConnectedThread connectedThread = new ConnectedThread(
                        (BluetoothSocket) msg.obj);
                Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
                String s = "successfully connected";
                connectedThread.write(s.getBytes());
                Log.i(tag, "connected");
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                String string = new String(readBuf);
                Toast.makeText(getApplicationContext(), string, 0).show();
                break;
            }
        }
    };

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

        // take an instance of BluetoothAdapter - Bluetooth radio
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (myBluetoothAdapter == null) {
            onBtn.setEnabled(false);
            offBtn.setEnabled(false);
            listBtn.setEnabled(false);
            findBtn.setEnabled(false);
            text.setText("Status: not supported");

            Toast.makeText(getApplicationContext(),
                    "Your device does not support Bluetooth", Toast.LENGTH_LONG)
                    .show();
        } else {
            myListView = (ListView) findViewById(R.id.listView1);
            BTArrayAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1);
            devices = new ArrayList<BluetoothDevice>();
            myListView.setAdapter(BTArrayAdapter);
            text = (TextView) findViewById(R.id.text);
            onBtn = (Button) findViewById(R.id.turnOn);
            onBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    on(v);
                }
            });

            offBtn = (Button) findViewById(R.id.turnOff);
            offBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    off(v);
                }
            });

            listBtn = (Button) findViewById(R.id.paired);
            listBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    list(v);
                }
            });

            findBtn = (Button) findViewById(R.id.search);
            findBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    find(v);
                }
            });

            // create the arrayAdapter that contains the BTDevices, and set it
            // to the ListView

            myListView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    if (myBluetoothAdapter.isDiscovering()) {
                        myBluetoothAdapter.cancelDiscovery();
                    }

                    BluetoothDevice selectedDevice = devices.get(position);
                    if (pairedDevices.contains(selectedDevice)) {

                        if (unpairDevice(selectedDevice))
                            Toast.makeText(getApplicationContext(),
                                    "Device unpaired", Toast.LENGTH_LONG)
                                    .show();
                        else
                            Toast.makeText(getApplicationContext(),
                                    "Problem while unpairing device",
                                    Toast.LENGTH_LONG).show();
                    } else {
                        if (pairDevice(selectedDevice)) {
                            Toast.makeText(getApplicationContext(),
                                    "Device paired", Toast.LENGTH_LONG).show();
                            ConnectThread connect = new ConnectThread(
                                    selectedDevice);
                            connect.start();
                        } else
                            Toast.makeText(getApplicationContext(),
                                    "Problem while pairing device",
                                    Toast.LENGTH_LONG).show();
                    }
                }

            });

        }
    }

    // For Pairing
    private boolean pairDevice(BluetoothDevice device) {
        try {
            Log.d("pairDevice()", "Start Pairing...");
            Method m = device.getClass()
                    .getMethod("createBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // For UnPairing
    private boolean unpairDevice(BluetoothDevice device) {
        try {
            Log.d("unpairDevice()", "Start Un-Pairing...");
            Method m = device.getClass()
                    .getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public void on(View view) {
        if (!myBluetoothAdapter.isEnabled()) {
            Intent turnOnIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);

            Toast.makeText(getApplicationContext(), "Bluetooth turned on",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Bluetooth is already on",
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (myBluetoothAdapter.isEnabled()) {
                text.setText("Status: Enabled");
            } else {
                text.setText("Status: Disabled");
            }
        }
    }

    public void list(View view) {
        BTArrayAdapter.clear();
        // get paired devices
        // pairedDevices.clear();
        pairedDevices = myBluetoothAdapter.getBondedDevices();

        // put it's one to the adapter
        for (BluetoothDevice device : pairedDevices)
            BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());

        Toast.makeText(getApplicationContext(), "Show Paired Devices",
                Toast.LENGTH_SHORT).show();

    }

    final BroadcastReceiver bReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // add the name and the MAC address of the object to the
                // arrayAdapter
                devices.add(device);
                BTArrayAdapter.add(device.getName() + "\n"
                        + device.getAddress());
                BTArrayAdapter.notifyDataSetChanged();
            }
        }
    };

    public void find(View view) {
        if (myBluetoothAdapter.isDiscovering()) {
            // the button is pressed when it discovers, so cancel the discovery
            Toast.makeText(getApplicationContext(), "Discovery cancelled",
                    Toast.LENGTH_SHORT).show();
            myBluetoothAdapter.cancelDiscovery();
        } else {
            Toast.makeText(getApplicationContext(), "Discovering new devices",
                    Toast.LENGTH_SHORT).show();
            BTArrayAdapter.clear();
            myBluetoothAdapter.startDiscovery();
            registerReceiver(bReceiver, new IntentFilter(
                    BluetoothDevice.ACTION_FOUND));
        }
    }

    public void off(View view) {
        myBluetoothAdapter.disable();
        text.setText("Status: Disconnected");

        Toast.makeText(getApplicationContext(), "Bluetooth turned off",
                Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bReceiver);
    }

    private class ConnectThread extends Thread {

        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            // Use a temporary object that is later assigned to mmSocket,
            // because mmSocket is final
            BluetoothSocket tmp = null;
            mmDevice = device;
            Log.i(tag, "construct");
            // Get a BluetoothSocket to connect with the given BluetoothDevice
            try {
                // MY_UUID is the app's UUID string, also used by the server
                // code
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.i(tag, "get socket failed");

            }
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discovery because it will slow down the connection
            myBluetoothAdapter.cancelDiscovery();
            Log.i(tag, "connect - run");
            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
                Log.i(tag, "connect - succeeded");
            } catch (IOException connectException) {
                Log.i(tag, "connect failed");
                // Unable to connect; close the socket and get out
                try {
                    mmSocket.close();
                } catch (IOException closeException) {
                }
                return;
            }

            // Do work to manage the connection (in a separate thread)

            mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
        }

        /** Will cancel an in-progress connection, and close the socket */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
            }
        }
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer; // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    buffer = new byte[1024];
                    bytes = mmInStream.read(buffer);
                    // Send the obtained bytes to the UI activity
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();

                } catch (IOException e) {
                    break;
                }
            }
        }

        /* Call this from the main activity to send data to the remote device */
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
            }
        }

        /* Call this from the main activity to shutdown the connection */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
            }
        }
    }

}
导入android.os.Bundle;
导入android.os.Handler;
导入android.os.Message;
导入android.app.Activity;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.bluetooth.BluetoothSocket;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.lang.reflect.Method;
导入java.util.ArrayList;
导入java.util.Set;
导入java.util.UUID;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.util.Log;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.ListView;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity扩展了活动{
私有静态最终整数请求_ENABLE_BT=1;
专用按钮onBtn;
专用按钮OFBTN;
私人按钮列表;
专用按钮findBtn;
私有文本查看文本;
私人蓝牙适配器myBluetoothAdapter;
专用配对设备;
专用阵列列表设备;
私有列表视图myListView;
专用阵列适配器BTArrayAdapter;
私有字符串tag=“调试”;
受保护的静态最终UUID MY_UUID=UUID
.fromString(“000011101-0000-1000-8000-00805F9B34FB”);
受保护的静态最终int成功连接=0;
受保护的静态最终int消息_READ=1;
私有处理程序mHandler=新处理程序(){
@凌驾
公共无效handleMessage(消息消息消息){
Log.i(标记“in handler”);
超级handleMessage(msg);
开关(msg.what){
成功案例(u CONNECT):
//做点什么
ConnectedThread ConnectedThread=新的ConnectedThread(
(蓝牙插座)msg.obj);
Toast.makeText(getApplicationContext(),“CONNECT”,0.show();
字符串s=“已成功连接”;
connectedThread.write(s.getBytes());
Log.i(标记“已连接”);
打破
案例信息如下:
字节[]readBuf=(字节[])msg.obj;
字符串字符串=新字符串(readBuf);
Toast.makeText(getApplicationContext(),string,0.show();
打破
}
}
};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//以蓝牙适配器-蓝牙收音机为例
myBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter==null){
onBtn.setEnabled(false);
offBtn.setEnabled(假);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText(“状态:不支持”);
Toast.makeText(getApplicationContext(),
“您的设备不支持蓝牙”,Toast.LENGTH\u LONG)
.show();
}否则{
myListView=(ListView)findViewById(R.id.listView1);
BTArrayAdapter=新的ArrayAdapter(此,
android.R.layout.simple\u list\u item\u 1);
设备=新的ArrayList();
setAdapter(BTArrayAdapter);
text=(TextView)findViewById(R.id.text);
onBtn=(按钮)findViewById(R.id.turnOn);
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
关于(v);
}
});
offBtn=(按钮)findViewById(R.id.关闭);
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
关(五);;
}
});
listBtn=(按钮)findviewbyd(R.id.paired);
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
名单(五);
}
});
findBtn=(按钮)findviewbyd(R.id.search);
findBtn.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
发现(v);
}
});
//创建包含BTDevices的arrayAdapter,并对其进行设置
//到ListView
myListView.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
if(myBluetoothAdapter.isDiscovering()){
myBluetoothAdapter.cancelDiscovery();
}
Bluetooth设备selectedDevice=devices.get(位置);
if(pairedDevices.contains(selectedDevice)){
if(未配对设备(选定设备))
Toast.makeText(getApplicationContext(),