我使用了这段代码:
public class MainActivity extends AppCompatActivity {
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// Whenever a remote Bluetooth device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
adapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
private ToggleButton toggleButton;
private ListView listview;
private ArrayAdapter adapter;
private static final int ENABLE_BT_REQUEST_CODE = 1;
private static final int DISCOVERABLE_BT_REQUEST_CODE = 2;
private static final int DISCOVERABLE_DURATION = 300;
BluetoothAdapter bluetoothAdapter;
BluetoothServerSocket bluetoothServerSocket;
private final static UUID uuid = UUID.fromString("fc5ffc49-00e3-4c8b-9cf1-6b72aad1001a");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
listview = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter
(this, android.R.layout.simple_list_item_1);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) listview.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
});
}
public void onToggleClicked(View view) {
adapter.clear();
ToggleButton toggleButton = (ToggleButton) view;
if (bluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(getApplicationContext(), "Oop! Your device does not support Bluetooth",
Toast.LENGTH_SHORT).show();
toggleButton.setChecked(false);
} else {
if (toggleButton.isChecked()){ // to turn on bluetooth
if (!bluetoothAdapter.isEnabled()) {
// A dialog will appear requesting user permission to enable Bluetooth
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, ENABLE_BT_REQUEST_CODE);
} else {
Toast.makeText(getApplicationContext(), "Your device has already been enabled." +
"\n" + "Scanning for remote Bluetooth devices...",
Toast.LENGTH_SHORT).show();
// To discover remote Bluetooth devices
discoverDevices();
// Make local device discoverable by other devices
makeDiscoverable();
}
} else { // Turn off bluetooth
bluetoothAdapter.disable();
adapter.clear();
Toast.makeText(getApplicationContext(), "Your device is now disabled.",
Toast.LENGTH_SHORT).show();
}
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ENABLE_BT_REQUEST_CODE) {
// Bluetooth successfully enabled!
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(getApplicationContext(), "Ha! Bluetooth is now enabled." +
"\n" + "Scanning for remote Bluetooth devices...",
Toast.LENGTH_SHORT).show();
// Make local device discoverable by other devices
makeDiscoverable();
// To discover remote Bluetooth devices
discoverDevices();
} else { // RESULT_CANCELED as user refused or failed to enable Bluetooth
Toast.makeText(getApplicationContext(), "Bluetooth is not enabled.",
Toast.LENGTH_SHORT).show();
// Turn off togglebutton
toggleButton.setChecked(false);
}
} else if (requestCode == DISCOVERABLE_BT_REQUEST_CODE){
if (resultCode == DISCOVERABLE_DURATION){
Toast.makeText(getApplicationContext(), "Your device is now discoverable by other devices for " +
DISCOVERABLE_DURATION + " seconds",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Fail to enable discoverability on your device.",
Toast.LENGTH_SHORT).show();
}
}
}
protected void discoverDevices(){
// To scan for remote Bluetooth devices
if (bluetoothAdapter.startDiscovery()) {
Toast.makeText(getApplicationContext(), "Discovering other bluetooth devices...",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Discovery failed to start.",
Toast.LENGTH_SHORT).show();
}
}
protected void makeDiscoverable(){
// Make local device discoverable
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}
@Override
protected void onResume() {
super.onResume();
// Register the BroadcastReceiver for ACTION_FOUND
ListeningThread listening = new ListeningThread();
listening.start();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(broadcastReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(broadcastReceiver);
}
private class ListeningThread extends Thread {
private final BluetoothServerSocket bluetoothServerSocket;
public ListeningThread() {
BluetoothServerSocket temp = null;
try {
temp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(getString(R.string.app_name), uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothServerSocket = temp;
}
public void run() {
BluetoothSocket bluetoothSocket;
// This will block while listening until a BluetoothSocket is returned
// or an exception occurs
while (true) {
try {
bluetoothSocket = bluetoothServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection is accepted
if (bluetoothSocket != null) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "A connection has been accepted.",
Toast.LENGTH_SHORT).show();
}
});
// Manage the connection in a separate thread
try {
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
// Cancel the listening socket and terminate the thread
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ConnectingThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
bluetoothAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
Log.e("TAG" , "Bluetooth socket is connected.");
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
// Code to manage the connection in a separate thread
/*
manageBluetoothConnection(bluetoothSocket);
*/
}
// Cancel an open connection and terminate the thread
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
清单文件中的权限。
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
我得到了记录。
D/BluetoothAdapter: cancelDiscovery
09-13 12:57:28.321 5687-5884/sony.ir.dumadu.com.bluetoothconnection D/BluetoothAdapter: cancelDiscovery = true
09-13 12:57:28.326 5687-5884/sony.ir.dumadu.com.bluetoothconnection D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
09-13 12:57:28.326 5687-5884/sony.ir.dumadu.com.bluetoothconnection D/BluetoothSocket: connect(): myUserId = 0
09-13 12:57:28.326 5687-5884/sony.ir.dumadu.com.bluetoothconnection W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
09-13 12:57:28.336 5687-5884/sony.ir.dumadu.com.bluetoothconnection D/BluetoothSocket: connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[43]}
09-13 12:57:29.976 5687-5884/sony.ir.dumadu.com.bluetoothconnection W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
09-13 12:57:29.976 5687-5884/sony.ir.dumadu.com.bluetoothconnection W/System.err: at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:739)
09-13 12:57:29.976 5687-5884/sony.ir.dumadu.com.bluetoothconnection W/System.err: at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:750)
09-13 12:57:29.976 5687-5884/sony.ir.dumadu.com.bluetoothconnection W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:478)
09-13 12:57:29.976 5687-5884/sony.ir.dumadu.com.bluetoothconnection W/System.err: at sony.ir.dumadu.com.bluetoothconnection.MainActivity$ConnectingThread.run(MainActivity.java:273)
09-13 12:57:29.976 5687-5884/sony.ir.dumadu.com.bluetoothconnection D/BluetoothSocket: close() in, this: android.bluetooth.BluetoothSocket@3c92d388, channel: -1, state: INIT
09-13 12:57:29.976 5687-5884/sony.ir.dumadu.com.bluetoothconnection D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@3c92d388, channel: -1, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@2a27b121, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@2b64a946mSocket: android.net.LocalSocket@17939707 impl:android.net.LocalSocketImpl@1845a034 fd:FileDescriptor[43]
09-13 12:57:29.976 5687-5884/sony.ir.dumadu.com.bluetoothconnection D/BluetoothSocket: Closing mSocket: android.net.LocalSocket@17939707 impl:android.net.LocalSocketImpl@1845a034 fd:FileDescriptor[43]
所以我需要删除log:
java.io.IOException:读取失败,socket可能关闭或超时,读取ret:-1。
请帮帮我。