Java Android rfcomm ioexception
我正在尝试在Android上学习rfcomm,并做了这个活动来帮助我…问题是我总是在显示Java Android rfcomm ioexception,java,android,ioexception,rfcomm,Java,Android,Ioexception,Rfcomm,我正在尝试在Android上学习rfcomm,并做了这个活动来帮助我…问题是我总是在显示***的行中遇到IOException 这是我的密码: import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.U
***
的行中遇到IOException
这是我的密码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi")
public class BluetoothCom extends Fragment {
private static final int REQUEST_ENABLE_BT = 1;
private static final String TAG = "APP";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
static BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
TextView bluetoothState;
ArrayAdapter<String> bluetoothDevices;
List<String> btDevicesList;
List<UUID> uuids;
ListView bluetoothDevicesAvailable;
View v;
Button startBluetooth, searchForDevices;
ConnectThread mConnectThread;
ConnectedThread mConnectedThread;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
int STATE = STATE_NONE;
public BluetoothCom(Context context) {
super();
// TODO Auto-generated constructor stub
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_bluetooth, container,
false);
v = view;
searchForDevices = (Button) getActivity().findViewById(
R.id.bSearchDevices);
bluetoothState = (TextView) getActivity().findViewById(
R.id.tvBluetoothState);
bluetoothDevicesAvailable = (ListView) view
.findViewById(R.id.lvBluetoothDevicesAvailable);
configBluetooth();
// LinearLayout ll = (LinearLayout)
// inflater.inflate(R.layout.activity_bluetooth, container, false);
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
getActivity();
if (resultCode == Activity.RESULT_OK) {
configBluetooth();
}
}
private void configBluetooth() {
if (bluetooth != null) {
if (bluetooth.isEnabled()) {
searchForDevices.setVisibility(View.VISIBLE);
bluetoothState.setText("Bluetooth is Enabled");
searchForDevices.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
searchBluetoothDevices();
}
});
} else {
startBluetooth = (Button) getActivity().findViewById(
R.id.bActivateBluetooth);
startBluetooth.setVisibility(View.VISIBLE);
startBluetooth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
bluetooth.enable();
bluetoothState.setText("Bluetooth has been enabled");
startBluetooth.setVisibility(View.GONE);
configBluetooth();
}
});
bluetoothState.setText("Bluetooth is Disabled.");
}
} else {
new AlertDialog.Builder(v.getContext())
.setTitle("Error")
.setMessage(
"It seems that your device does not have any bluetooth adapter.")
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// continue with delete
getActivity().finish();
}
}).setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
@SuppressLint("NewApi")
private void searchBluetoothDevices() {
final List<BluetoothDevice> tmpBtChecker = new ArrayList<BluetoothDevice>();
bluetooth.startDiscovery();
uuids = new ArrayList<UUID>();
final ArrayAdapter<String> ar = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1);
final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
// clearing any existing list data
tmpBtChecker.clear();
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery has finished
}
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (!tmpBtChecker.contains(device)) {
tmpBtChecker.add(device);
ar.add(device.getName() + " " + device.getAddress());
}
bluetoothDevicesAvailable.setAdapter(ar);
bluetoothDevicesAvailable.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
BluetoothDevice device = tmpBtChecker.get(position);
mConnectThread = new ConnectThread(device);
mConnectThread.start();
}
});
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(receiver, filter);
}
public synchronized void connect(BluetoothDevice device) {
// Cancel any thread attempting to make a connection
if (STATE == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
STATE = STATE_CONNECTING;
}
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
STATE = STATE_CONNECTED;
}
private void connectionLost() {
STATE = STATE_NONE;
// Send a failure message back to the Activity
Toast t = new Toast(getActivity());
t.makeText(getActivity(), "Conexiune pierduta!", Toast.LENGTH_LONG).show();
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
bluetooth.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect(); //Here is the problematic line***
//HERE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(getActivity(), "Failed Connecting to the device!", Toast.LENGTH_LONG).show();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
// Start the service over to restart listening mode
//BluetoothChatService.this.start();
return;
}
// Reset the ConnectThread because we're done
mConnectThread = null;
// Start the connected thread
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
// Read from the InputStream
//bytes = mmInStream.read(buffer);
String a = "50";
buffer = a.getBytes();
try {
mmOutStream.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
//mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}
import java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.UUID;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.bluetooth.BluetoothSocket;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.os.Bundle;
导入android.support.v4.app.Fragment;
导入android.util.Log;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.TextView;
导入android.widget.Toast;
@SuppressLint(“新API”)
公共类BluetoothCom扩展片段{
私有静态最终整数请求_ENABLE_BT=1;
私有静态最终字符串TAG=“APP”;
私有静态最终UUID MY_UUID=UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
静态BluetoothAdapter bluetooth=BluetoothAdapter.getDefaultAdapter();
文本视图蓝牙状态;
ArrayAdapter蓝牙设备;
列出设备列表;
列出UUID;
ListView蓝牙设备可用;
观点五;
按钮启动蓝牙,搜索设备;
连接线程mConnectThread;
ConnectedThread mConnectedThread;
//指示当前连接状态的常量
public static final int STATE_NONE=0;//我们什么也没做
public static final int STATE_LISTEN=1;//正在侦听传入连接
public static final int STATE_CONNECTING=2;//正在启动传出连接
public static final int STATE_CONNECTED=3;//现在已连接到远程设备
int STATE=STATE_NONE;
公共BluetoothCom(上下文){
超级();
//TODO自动生成的构造函数存根
}
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图=充气机。充气(R.layout.activity\u蓝牙,容器,
假);
v=视图;
searchForDevices=(按钮)getActivity().findViewById(
R.id.b搜索设备);
bluetoothState=(TextView)getActivity().findViewById(
R.id.tvBluetoothState);
bluetoothDevicesAvailable=(ListView)视图
.findViewById(R.id.LVBluetoothDevices可用);
配置蓝牙();
//LinearLayout ll=(LinearLayout)
//充气机。充气(R.layout.activity\u蓝牙,容器,错误);
返回视图;
}
@凌驾
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
//TODO自动生成的方法存根
super.onActivityResult(请求代码、结果代码、数据);
getActivity();
if(resultCode==Activity.RESULT\u确定){
配置蓝牙();
}
}
私有无效配置蓝牙(){
如果(蓝牙!=null){
如果(bluetooth.isEnabled()){
searchForDevices.setVisibility(View.VISIBLE);
setText(“蓝牙已启用”);
searchForDevices.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
搜索蓝牙设备();
}
});
}否则{
startBluetooth=(按钮)getActivity().findViewById(
R.id.bactivatebooth);
startBluetooth.setVisibility(View.VISIBLE);
startBluetooth.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
bluetooth.enable();
bluetoothState.setText(“蓝牙已启用”);
startBluetooth.setVisibility(View.GONE);
配置蓝牙();
}
});
setText(“蓝牙已禁用”);
}
}否则{
新建AlertDialog.Builder(v.getContext())
.setTitle(“错误”)
.setMessage(
“您的设备似乎没有任何蓝牙适配器。”)
.setPositiveButton(android.R.string.ok,
新建DialogInterface.OnClickListener(){
公共void onClick(对话框接口对话框,
int(其中){
//继续删除
getActivity().finish();
}
}).setIcon(android.R.drawable.ic_d