我遵循了以下示例程序的网址。它曾经用于通过android应用将消息发送至配对的蓝牙设备。
https://stackoverflow.com/a/22899728/1559331
IOException: read failed, socket might closed - Bluetooth on Android 4.3
代码试图做的是
1)连接到配对的设备并将数据写入到其outputstream中。要写入的数据取自edittext
2)代码还以编辑文本的形式显示输入流中的数据
在设备上进行测试时,我可以连接数据并将数据写入到outputstream,但无法读取。即使onclick的“读取”按钮不起作用
main_activity_xml-使用的UI的XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="horizontal"
android:layout_width="fill_parent">
<EditText
android:id="@+id/editText"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="fill_parent"
android:inputType="number"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"/>
<EditText
android:id="@+id/editText2"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="fill_parent"
/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
/>
</LinearLayout>
MainActivity.java-主要活动类
package com.example.dileep.blutooth_messenger;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.PointF;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Scanner;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final BluetoothSocketWrapper bluetoothSocketWrapper=new BluetoothSocketWrapper(getApplicationContext());
et = (EditText) findViewById(R.id.editText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "100")});
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bluetoothSocketWrapper.getSocket() != null) {
if (!bluetoothSocketWrapper.isConnected()) {
bluetoothSocketWrapper.init();
}
try {
bluetoothSocketWrapper.getOutputStream().write(et.getText().toString().getBytes());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Exception while writing to output stream-->" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
finally {
try { bluetoothSocketWrapper.getOutputStream().close();}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Exception whileclosing output stream-->" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Toast.makeText(getApplicationContext(), "Writing completed", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Not able to connect", Toast.LENGTH_SHORT).show();
}
}
});
et2 = (EditText) findViewById(R.id.editText2);
final Button button2 = (Button) findViewById(R.id.button2);
Toast.makeText(getApplicationContext(), "just beofre 2 nd listner", Toast.LENGTH_SHORT).show();
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "second listener", Toast.LENGTH_SHORT).show();
if(bluetoothSocketWrapper.getSocket()!=null){
if(!bluetoothSocketWrapper.isConnected()) {
bluetoothSocketWrapper.init();
}
StringBuilder builder=new StringBuilder();
Scanner s = null;//.useDelimiter("\n");
try {
s = new Scanner(bluetoothSocketWrapper.getInputStream());
while(s.hasNext()){
builder.append(s.next());
}
Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
et2.setText(builder.toString());
Toast.makeText(getApplicationContext(), "reading completed", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try { bluetoothSocketWrapper.getInputStream().close();}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Exception while closing input stream-->" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
else{
Toast.makeText(getApplicationContext(), "Not able to connect", Toast.LENGTH_SHORT).show();
}
}});
}
private OutputStream outputStream;
private InputStream inStream;
private EditText et;
private EditText et2;
}
BluetoothSocketWrapper类->用作蓝牙套接字的包装器
package com.example.dileep.blutooth_messenger;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.ParcelUuid;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Set;
import java.util.UUID;
public class BluetoothSocketWrapper {
private BluetoothSocket socket = null;
private OutputStream outputStream;
private InputStream inStream;
private Context context = null;
public BluetoothSocketWrapper(Context context) {
this.context = context;
init();
}
public void init() {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter == null) {
Toast.makeText(context, "Device doesnt Support Bluetooth", Toast.LENGTH_SHORT).show();
}
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if (bondedDevices.size() > 0) {
Object[] devices = (Object[]) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[0];
ParcelUuid[] uuids = device.getUuids();
// Toast.makeText(context,uuids[0].getUuid().toString(),Toast.LENGTH_LONG).show();
// BluetoothSocket socket=null;
try {
//socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {
Toast.makeText(context, "exc with 1st conn", Toast.LENGTH_LONG).show();
}
try {
socket.connect();
} catch (Exception e) {
Log.e("", e.getMessage());
try {
Toast.makeText(context, "tryiing fallback", Toast.LENGTH_LONG).show();
Class<?> clazz = socket.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[]{Integer.valueOf(2)};
socket = (BluetoothSocket) m.invoke(socket.getRemoteDevice(), params);
socket.connect();
Toast.makeText(context, "Connected", Toast.LENGTH_LONG).show();
} catch (Exception e2) {
Toast.makeText(context, "Couldn't establish Bluetooth connection -->" + e2.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public boolean isConnected(){
return this.socket.isConnected();
}
public OutputStream getOutputStream() throws IOException {
return this.socket.getOutputStream();
}
public InputStream getInputStream() throws IOException {
return this.socket.getInputStream();
}
public void close() throws IOException {
this.socket.close();
}
public BluetoothSocket getSocket(){
return socket;
}
}
用于edittext的InputFilter类
package com.example.dileep.blutooth_messenger;
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
有人可以解释为什么应用和设备挂起。也请提出所需的更改