android - 如何从 Android 上的蓝牙 InputStream 中读取

标签 android io bluetooth inputstream android-bluetooth

我正在尝试测试 this bluetooth communication example between a PC and an Android phone .我的 SPP 客户端正是来自那里的客户端,并且运行良好。我是 Android 的新手,我不想让它在单独的线程中运行,因为我不知道如何,所以我只是在 onCreate() 方法中做了所有事情。如果这不是最好的方法,请随时指出更好的方法,但这不是我的主要问题。

问题是我想在 textView 上显示通过蓝牙接收的文本,但我不知道如何从 InputStream 中读取。当代码保持这样时,它会显示类似 java.io.DataInputStream@41b0cb68 的内容 我试过 here它没有显示任何内容,我也不知道正在使用什么编码。

这是我的安卓应用的代码:

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.*;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

//based on java.util.UUID
private static UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66");

// The local server socket
private BluetoothServerSocket mmServerSocket;

// based on android.bluetooth.BluetoothAdapter
private BluetoothAdapter mAdapter;
private BluetoothDevice remoteDevice;
TextView text;

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

    text = (TextView) findViewById(R.id.textView_Text);

    BluetoothSocket socket = null;
    mAdapter = BluetoothAdapter.getDefaultAdapter();        

    // Listen to the server socket if we're not connected
   // while (true) {

        try {
            // Create a new listening server socket
            Log.d((String) this.getTitle(), ".....Initializing RFCOMM SERVER....");

            // MY_UUID is the UUID you want to use for communication
            mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("MyService",    MY_UUID);
            //mmServerSocket =  mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID); // you can also try  using In Secure connection...

            // This is a blocking call and will only return on a
            // successful connection or an exception
            socket = mmServerSocket.accept();

        } catch (Exception e) {

        }

        try {
            Log.d((String) this.getTitle(), "Closing Server Socket.....");
            mmServerSocket.close();

            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams

            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();

            DataInputStream mmInStream = new DataInputStream(tmpIn);
            DataOutputStream mmOutStream = new DataOutputStream(tmpOut);

            // here you can use the Input Stream to take the string from the client  whoever is connecting
            //similarly use the output stream to send the data to the client


            text.setText(mmInStream.toString());
        } catch (Exception e) {
            //catch your exception here
        }
   // }
}
}

我注释掉了 while(true) 循环,因为我认为它在调用 onPause() 时导致我的应用程序崩溃。我知道这不是最好的实现,但我真的很想从蓝牙读取我觉得我非常接近:),其他方面将在之后处理(比如使用线程等)。

最佳答案

我终于设法在 TextView 中正确显示从 PC 发送的字符串(“来自 SPP 客户端的测试字符串\r\n”)。

我用了this question ,即这段代码,就在 DataOutputStream mmOutStream = new DataOutputStream(tmpOut); 的下方:

// Read from the InputStream
            bytes = mmInStream.read(buffer);
            String readMessage = new String(buffer, 0, bytes);
            // Send the obtained bytes to the UI Activity

这是一个非常初级的示例,旨在展示如何在设备屏幕上显示通过蓝牙接收的字符串。它不是在单独的线程中完成的,在它收到字符串后,您必须关闭应用程序并再次重新启动它,但是应用程序的主要目的已经实现(正如我在问这个问题时所说的那样)。我真正想要的是从 PC 接收字符串并将其显示在屏幕上。

这是我完整的 MainActivity,如果有人希望我发布更完整的方法(例如使用单独的线程),我会在完成后将其发布在这里。

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.*;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

//based on java.util.UUID
private static UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66");

// The local server socket
private BluetoothServerSocket mmServerSocket;

// based on android.bluetooth.BluetoothAdapter
private BluetoothAdapter mAdapter;
private BluetoothDevice remoteDevice;
TextView text;

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

    text = (TextView) findViewById(R.id.textView_Text);

    BluetoothSocket socket = null;
    mAdapter = BluetoothAdapter.getDefaultAdapter();        

    // Listen to the server socket if we're not connected
   // while (true) {

        try {
            // Create a new listening server socket
            Log.d((String) this.getTitle(), ".....Initializing RFCOMM SERVER....");

            // MY_UUID is the UUID you want to use for communication
            mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("MyService",    MY_UUID);
            //mmServerSocket =  mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID); // you can also try  using In Secure connection...

            // This is a blocking call and will only return on a
            // successful connection or an exception
            socket = mmServerSocket.accept();

        } catch (Exception e) {

        }

        byte[] buffer = new byte[256];  // buffer store for the stream
        int bytes; // bytes returned from read()
        try {
            Log.d((String) this.getTitle(), "Closing Server Socket.....");
            mmServerSocket.close();

            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams

            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();

            DataInputStream mmInStream = new DataInputStream(tmpIn);
            DataOutputStream mmOutStream = new DataOutputStream(tmpOut);            
            // here you can use the Input Stream to take the string from the client  whoever is connecting
            //similarly use the output stream to send the data to the client

         // Read from the InputStream
            bytes = mmInStream.read(buffer);
            String readMessage = new String(buffer, 0, bytes);
            // Send the obtained bytes to the UI Activity


            text.setText(readMessage);
        } catch (Exception e) {
            //catch your exception here
        }
   // }
}
}

有什么问题吗? :)

关于android - 如何从 Android 上的蓝牙 InputStream 中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25443297/

相关文章:

io - "Read a byte from an I/O port"与 "Read a byte from an address of memory"?

android - 使用 HC-05 将连续数据从 arduino 发送到 Android 应用程序

bash - 在 bash 脚本中,是否可以将由后台进程计算的值分配给变量?

c - 'write' 函数的正确缓冲区大小是多少?

mobile - 将 Adob​​e AIR 移动应用程序无线连接到 Arduino - 有哪些选项?

安卓连接配对的蓝牙耳机

安卓。解析.com : Invalid Session Token

android - 复选框未显示在 CheckedTextView Android 中

java - 对于我不明白的事情,在这里得到一个空指针异常

Android:如何将参数放入配置文件