如何将数据(字符串)发送到android中的配对设备?

时间:2014-08-29 23:50:15

标签: android bluetooth android-bluetooth

我是第一次使用蓝牙技术。我得到了成对设备的列表。现在我的要求是我需要向设备发送一些数据(字符串)。我怎样才能做到这一点?我试过搜索,但没有找到任何有用的东西。有人可以帮帮忙吗?

1 个答案:

答案 0 :(得分:1)

这样的事情就足够了:

DataOutputStream os;

BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

BroadcastReceiver discoveryResult = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
        BluetoothDevice remoteDevice;

        remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        Toast.makeText(getApplicationContext(), "Discovered: " + remoteDeviceName + " address " + remoteDevice.getAddress(), Toast.LENGTH_SHORT).show();

        try{
            BluetoothDevice device = bluetooth.getRemoteDevice(remoteDevice.getAddress());

            Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});

            BluetoothSocket clientSocket =  (BluetoothSocket) m.invoke(device, 1);

            clientSocket.connect();

            os = new DataOutputStream(clientSocket.getOutputStream());

            new clientSock().start();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("BLUETOOTH", e.getMessage());
        }
    }
};

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

bluetooth.enable();
if (!bluetooth.isDiscovering()) {
    bluetooth.startDiscovery();
}

public class clientSock extends Thread {
    public void run () {
        try {
            os.writeBytes("anything you want"); // anything you want
            os.flush();
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }
    }
}

您还需要大量的导入,例如:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.UUID;

import android.os.Bundle;
import android.os.StrictMode;
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.util.Log;
import android.view.Menu;
import android.widget.Toast;

请注意,此示例代码并非所有导入都是必需的,您的IDE可能会帮助您为它们进行排序。

os.writeBytes("anything you want"); // anything you want行传递数据。

您还需要Permissions