当前位置: 首页 > 知识库问答 >
问题:

通过蓝牙编程连接两台Android设备

别俊誉
2023-03-14

我正试图通过蓝牙将数据从一台设备传输到另一台设备。

我之前曾尝试在android网站上运行bluetoothChat示例代码,但没有成功。

现在,我继续研究我发现的这段代码,虽然它在我的设备上编译,但它们之间没有连接。

有人看到下面的代码有什么问题吗?如果有人知道android上蓝牙的一些好资源,如果他们能与我分享,我将不胜感激!

package com.example.bluetooth;

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

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 android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener {

ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public 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;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        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", Toast.LENGTH_SHORT).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
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
    if(btAdapter==null){
        Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
        finish();
    }
    else{
        if(!btAdapter.isEnabled()){
            turnOnBT();
        }

        getPairedDevices();
        startDiscovery();//
    }


}

public void resumeDiscovery(View view){
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();

}
private void turnOnBT() {
    // TODO Auto-generated method stub
    Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}
private void getPairedDevices() {
    // TODO Auto-generated method stub
    devicesArray = btAdapter.getBondedDevices();
    if(devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());

        }
    }
}
private void init() {
    // TODO Auto-generated method stub
    listView=(ListView)findViewById(R.id.listView);
    listView.setOnItemClickListener(this);
    listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>();
    receiver = 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);
                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_DISCOVERY_STARTED.equals(action)){
                // run some code
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                // run some code



            }
            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);
}


@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_CANCELED){
            Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        BluetoothDevice selectedDevice = devices.get(arg2);
        if(btAdapter.isDiscovering()){
            btAdapter.cancelDiscovery();
        }
        if(listAdapter.getItem(arg2).contains("Paired")){


            ConnectThread connect = new ConnectThread(selectedDevice);
            connect.start();
            Log.i(tag, "in click listener");
        }
        else{
            Toast.makeText(getApplicationContext(), "pairing", 0).show();
            //pair device
        }
    }

    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
            btAdapter.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) { }
        }
    }
}

共有1个答案

边意
2023-03-14

问题在于init()方法在onCreate()方法中使用此活动注册BroadcastReceiver,而在onPause()中取消注册BroadcastReceiver。

尝试在onResume()方法中注册它,以便在恢复此活动时可以接收广播。

 类似资料:
  • 它是蓝牙耳机还是手机? 如何在android代码中区分蓝牙耳机和支持蓝牙的android设备。 我正在开发一个小应用程序,我有一个功能,阻止通过蓝牙数据传输,但它需要允许通过蓝牙耳机通信。 > 我引用了示例和代码,因为它们建议我仅配对/取消配对蓝牙设备。Android:如何以编程方式配对蓝牙设备? 获取所有连接的设备。在Android中,如何获取已连接蓝牙设备的配置文件? 我是否可以在设备中获得与

  • 我正在尝试通过蓝牙连接两台Android设备(已经配对),并在其中一台设备上自动访问互联网。 这可以通过在设置中访问并启用以下复选框来实现: 你知道我怎么用程序来做这个吗? 谢谢。

  • 我如何获得Android所有已连接蓝牙设备的列表,而不考虑配置文件? 或者,我看到您可以通过BluetoothManager获取特定配置文件的所有连接设备。获取连接的设备。 我想我可以通过ACTION_ACL_CONNECTED/ACTION_ACL_DISCONNECTED监听连接/断开来查看哪些设备连接...似乎容易出错。 但我想知道是否有更简单的方法来获取所有已连接蓝牙设备的列表。

  • 连接设备 接口说明 用于连接 扫描出来的蓝牙设备。 参数说明 字段 类型 必须? 说明 device RKBLEDevice 是 蓝牙设备 示例代码 Swift: RokidMobileSDK.binder.connect(device: RKBLEDevice) Objc: [RokidMobileSDK.binder connect:device]; 断开设备 接口说明 用于断开已经连接的

  • 连接蓝牙设备 接口说明 接口需传入蓝牙名称(蓝牙address重启后会变) 参数说明 字段 类型 必须? 说明 name String 是 设备名称 举个大栗子 RokidMobileSDK.binder.connectBT(name, new IBTConnectCallBack() { @Override public void onConnectSucceed(BTDevic

  • 我想连接第三方蓝牙设备到我的Android Wear手表(三星Gear Live)。我试图找到留档如何做到这一点,但我没有任何运气。所有的搜索,我似乎都认为我想连接到手机上。 有谁知道一个很好的例子来演示如何将蓝牙心率监视器(或其他设备)连接到Android Wear,以便我在手机不存在时保存历史记录?这可能吗?它是否与从手机/平板电脑上执行相同的协议?