如何从Android上蓝牙的InputStream读入(how to read from the I

2019-10-20 18:05发布

我想测试一个PC和Android手机之间的蓝牙通信例子 。 我SPP客户正是从那里之一,它工作正常。 我是新来的Android,我不希望把它在一个单独的线程中运行,因为我不知道怎么回事,所以我只是做的一切onCreate()方法。 如果这是不是最好的方式,随意点我一个更好的办法,但这不是我的主要问题。

问题是我想显示通过蓝牙收到一个文本textView ,我不知道如何读取InputStream 。 当代码留下这样的,它显示像java.io.DataInputStream@41b0cb68我试着像这里并没有显示任何东西,也不知正在使用的编码。

这里是我的Android应用程序的代码:

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()被调用。 我知道这是不是最好的实现,但我真的希望像我从蓝牙我觉得阅读很接近:),其它方面与事后处理(如使用线程等)。

Answer 1:

我终于成功地在正确显示TextView从PC(“从SPP客户端\ r \ n测试字符串”)发送的字符串。

我用这个问题 ,即这一段代码,略低于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
        }
   // }
}
}

任何问题? :)



Answer 2:

基本上,你需要匹配数据的方式从一个设备发送到数据由另一个接收方式。

SPP是数据的基于数据流和传输字节。 因此,无论字节发送设备发送必须正确由接收器解释。

一个InputStream ,您可以访问传输的原始字节,你就必须做一些与他们; 即根据需要以某种方式对它们进行解码。 例如,如果发送者使用的ObjectOutputStream做编码之前传输,接收器将必须使用ObjectInputStream到输入进行解码。

您可能需要阅读了关于InputStreamread() ObjectInputStream ,和toString()

此外,从阻挡流应当总是在一个单独的线程来完成阅读; 尤其是从这样一些远程设备/主机/网络读出时/ ...具有可能未知的延迟或传输速度。



文章来源: how to read from the InputStream of a bluetooth on Android