草庐IT

android - 无法连接到android上的蓝牙 socket

coder 2023-12-17 原文

我正在尝试通过蓝牙从 Android 客户端向 Mac OS X 发送消息。 我在 Mac OS X Snow Leopard 上使用 bluecove 2.0.1 Java 蓝牙库。

服务器代码:

public class EchoServer2 {
private static final String UUID_STRING = "00001101-0000-1000-8000-00805F9B34FB"; // 32 hex digits
private static final String SERVICE_NAME = "echoserver";

private LocalDevice mLocalDevice;

public EchoServer2() {
    try {
        mLocalDevice = LocalDevice.getLocalDevice();
    } catch(IOException e) {
        System.err.print("Error connection to bluetooth");
    }   
}

public void start() throws IOException {
    StreamConnectionNotifier connectionNotifier =
        (StreamConnectionNotifier) Connector.open(
                "btspp://localhost:" + UUID_STRING +
                ";name=" + SERVICE_NAME + ";authenticate=false");

    System.out.println("Bluetooth Address: " + mLocalDevice.getBluetoothAddress());

    System.out.println("Waiting for a connection...");
    StreamConnection streamConnection = connectionNotifier.acceptAndOpen();

    System.out.println("Found a new device.");

    RemoteDevice device = RemoteDevice.getRemoteDevice(streamConnection);
    System.out.println("New Device connected: " + device.getFriendlyName(false).toString());

    DataInputStream is = streamConnection.openDataInputStream();

    byte[] bytes = new byte[1024];
    int r;
    while((r = is.read(bytes)) > 0) {
        System.out.println(new String(bytes, 0, r));
    }

}

Android 客户端代码:

public class MainActivity extends Activity {

private static final String TAG = "MainActivity";

EditText editText;
TextView textView;

String send_msg;
String rcv_msg;

private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // 32 hex digits

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

    Log.d(TAG, "onCreate");

    editText = (EditText) findViewById(R.id.edit_msg);
    textView = (TextView) findViewById(R.id.rcv_msg);

    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    if(adapter == null) {
        textView.append("Bluetooth NOT Supported!");
        return;
    }

    // Request user to turn ON Bluetooth
    if(!adapter.isEnabled()) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, RESULT_OK);
    }




}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public void onClick(View view) {
    Log.d(TAG, "onClick");
    new SendMessageToServer().execute(send_msg);
}

private class SendMessageToServer extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... msg) {
        Log.d(TAG, "doInBackground");

        BluetoothSocket clientSocket = null;
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        mBluetoothAdapter.enable();
        // Client knows the server MAC address 
        BluetoothDevice mmDevice = mBluetoothAdapter.getRemoteDevice("00:25:00:C3:1C:FE");
        Log.d(TAG, "got hold of remote device");
        Log.d(TAG, "remote device: " + mmDevice.getName().toString());

        try {
            // UUID string same used by server 
            clientSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);

            Log.d(TAG, "bluetooth socket created");

            mBluetoothAdapter.cancelDiscovery();    // Cancel, discovery slows connection

            clientSocket.connect();
            Log.d(TAG, "connected to server");

            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());

            out.writeUTF(msg[0]);           // Send message to server
            Log.d(TAG, "Message Successfully sent to server");
            return in.readUTF();            // Read response from server
        } catch (Exception e) {

            Log.d(TAG, "Error creating bluetooth socket");
            Log.d(TAG, e.getMessage());

            return "";
        }

    }

    @Override
    protected void onPostExecute(String result) {
        Log.d(TAG, "onPostExecute");
        rcv_msg = result;
        textView.setText(rcv_msg);
    }

}

即使客户端和服务器的 UUID 相同,我也无法连接到服务器。 Android 抛出异常:服务发现失败。 但是我能够在服务器上打印远程设备(客户端)的名称。因此 acceptAndOpen() 无法接受套接字连接。

请帮助我理解为什么我无法clientSocket.connect();在安卓上?

最佳答案

我会猜测并说它与您使用的 UUID 号码有关。它们完全取决于您使用的设备类型。因此,请确保您查看了这些内容,并确保它们对 Android 设备是正确的。当我在做 android 的时候,这让我很困惑。 UUID 不是你设置的。 这是一个链接 How can I get the UUID of my Android phone in an application? 或这个 Android - Get Bluetooth UUID for this device

如果不是这样。 两端的发现都失败了吗?你能看到两端的设备吗?你可以在哪一面打印名字? 您可能想看看 google 的蓝牙示例程序。并用它来帮助您入门。

关于android - 无法连接到android上的蓝牙 socket ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14040730/

有关android - 无法连接到android上的蓝牙 socket的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  3. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  4. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  5. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  6. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  7. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  8. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

  9. ruby-on-rails - openshift 上的 rails 控制台 - 2

    我将我的Rails应用程序部署到OpenShift,它运行良好,但我无法在生产服务器上运行“Rails控制台”。它给了我这个错误。我该如何解决这个问题?我尝试更新ruby​​gems,但它也给出了权限被拒绝的错误,我也无法做到。railsc错误:Warning:You'reusingRubygems1.8.24withSpring.UpgradetoatleastRubygems2.1.0andrun`gempristine--all`forbetterstartupperformance./opt/rh/ruby193/root/usr/share/rubygems/rubygems

  10. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

随机推荐