socket close!! 什么原因导致的呢
08-09 22:01:27.945: E/mango(9898): +++start discovering+++
08-09 22:01:54.445: D/ActivityThread(9898): test selfappwidget getPackageInfo,packageInfo 000=android.app.LoadedApk@40515458
08-09 22:01:54.476: E/mango(9898): +++start discovering+++
08-09 22:01:58.257: I/System.out(9898): 新发现的设备:mango
08-09 22:01:58.273: E/mango(9898): +++与设备配对+++
08-09 22:01:58.273: E/mango(9898): 获取远程设备
08-09 22:01:58.289: I/System.out(9898): 客户端的socket连接开始
08-09 22:02:05.750: I/System.out(9898): socket1android.bluetooth.BluetoothSocket@4055b5a0
08-09 22:02:05.750: I/System.out(9898): socket2android.bluetooth.BluetoothSocket@4055b5a0
08-09 22:02:05.757: I/System.out(9898): 进入管理线程的函数:connected
08-09 22:02:05.812: I/System.out(9898): 进入clientthread,开始write数据流
08-09 22:02:05.812: I/System.out(9898): send:[B@405604f8
08-09 22:02:05.820: W/System.err(9898): java.io.IOException: socket closed
08-09 22:02:05.820: W/System.err(9898): at android.bluetooth.BluetoothSocket.write(BluetoothSocket.java:316)
08-09 22:02:05.820: W/System.err(9898): at android.bluetooth.BluetoothOutputStream.write(BluetoothOutputStream.java:85)
08-09 22:02:05.820: W/System.err(9898): at java.io.OutputStream.write(OutputStream.java:80)
08-09 22:02:05.820: W/System.err(9898): at com.card.mango.sendcard$ClientThread.<init>(sendcard.java:223)
08-09 22:02:05.820: W/System.err(9898): at com.card.mango.sendcard.connected(sendcard.java:202)
08-09 22:02:05.820: W/System.err(9898): at com.card.mango.sendcard$ConnectThread.run(sendcard.java:169)
代码如下
//客户端 需要开启蓝牙 搜索设备 建立socket write数据
package com.card.mango;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class sendcard extends Activity {
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
private ConnectThread mConnectThread;
private ClientThread mClientThread;
private static final String Name = "mango";
String defaultname = "abc";
User user; //得到user实例和需要交换的数据
String exchange_name="0";
int exchange_image=0;
private TextView et_name;
private ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exchange);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_LONG).show();
finish();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
//直接打开蓝牙设备
mBluetoothAdapter.enable();
}
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
}
@Override
public void onStart() {
super.onStart();
//搜索周围的蓝牙设备
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
if(true){Log.e(Name, "+++start discovering+++");}//test
}
//自定义广播类
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("新发现的设备:"+device.getName());
// 如果查找到的设备符合要连接的设备,处理
if (device.getName().equalsIgnoreCase(Name)) {
// 搜索蓝牙设备的过程占用资源比较多,一旦找到需要连接的设备后需要及时关闭搜索
mBluetoothAdapter.cancelDiscovery();
//与搜索到的设备连接
if(true){Log.e(Name, "+++与设备配对+++");}//test
try {
//调用connect函数与设备连接
connect(device);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{ System.out.println("未找到想要的设备");
}
}
}
};
//与蓝牙设备连接
private void connect(BluetoothDevice device) throws IOException {
// Get the BLuetoothDevice object
String macadress=device.getAddress();
if (BluetoothAdapter.checkBluetoothAddress(macadress)){
BluetoothDevice mdevice = mBluetoothAdapter.getRemoteDevice(macadress);
if(true){Log.e(Name, "获取远程设备");}//test
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(mdevice);
mConnectThread.start();
}
};
private class ConnectThread extends Thread {
private final BluetoothSocket msocket;
private final BluetoothDevice mdevice;
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
UUID uuid = UUID.fromString(SPP_UUID);
public ConnectThread(BluetoothDevice device) {
//建立socket连接
BluetoothSocket tmp = null;
mdevice = device;
try {
tmp = mdevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) { e.printStackTrace(); }
msocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
System.out.println("客户端的socket连接开始");
msocket.connect();
System.out.println("socket1"+msocket);
} catch (IOException e) {e.printStackTrace();
// Unable to connect; close the socket and get out
// try {
// msocket.close();
// System.out.println("客户端的socket连接失败,无法连接到对方");
// } catch (IOException closeException) {}
// return;
}
// Do work to manage the connection (in a separate thread)
try {
System.out.println("socket2"+msocket);
connected(msocket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
msocket.close();
} catch (IOException e) { }
}
}
public synchronized void connected(BluetoothSocket socket) throws IOException {
// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
System.out.println("进入管理线程的函数:connected");
//获得意图
Intent intent = getIntent();
//从意图中得到需要的user对象 并保存即将用蓝牙传输的数据
user = (User) intent.getSerializableExtra("user");
et_name = (TextView) findViewById(R.id.username);
imageView = (ImageView)findViewById(R.id.imageId);
exchange_name=user.username;
exchange_image=user.imageId;
// Start the thread to manage the connection and perform transmissions
if(socket!=null){
mClientThread = new ClientThread(socket, exchange_name, exchange_image);
mClientThread.start();
}
}
private class ClientThread extends Thread {
private final BluetoothSocket mmSocket;
private final OutputStream mmOutStream;
public ClientThread(BluetoothSocket socket , String exchange_name , int exchange_image) throws IOException{
System.out.println("进入clientthread,开始write数据流");
mmSocket = socket;
mmOutStream = mmSocket.getOutputStream();
// 向socket对象所获取的流中发送数据
try {
byte[] send = exchange_name.getBytes();
System.out.println("send:"+send);
mmOutStream.write(send);
mmOutStream.flush();
} catch (IOException e) {e.printStackTrace(); }
finally{
cancel();
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
public synchronized void stop() {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mClientThread != null) {
mClientThread.cancel();
mClientThread = null;
}
}
}
[解决办法]
try {
byte[] send = exchange_name.getBytes();
System.out.println("send:"+send);
mmOutStream.write(send);
mmOutStream.flush();
} catch (IOException e) {e.printStackTrace(); }
finally{
cancel();////////////////////流出错,到finally,执行cancel方法关闭了socket
}
}