无法连接蓝牙设备

时间:2016-03-22 05:21:44

标签: android eclipse bluetooth device connectivity

我成功启用了蓝牙并显示了附近设备的列表,但只要我点击列表中显示的设备,app就会关闭。无法弄清问题是什么,如果有人回答这个问题会很有帮助

package com.android.clickandsend;

import java.io.IOException;
import java.util.Set;
import java.util.UUID;







import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
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.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
 import android.widget.Button;
 import android.widget.ListView;
 import android.widget.Toast;
 import android.widget.AdapterView.OnItemClickListener;

 public class Bluetooth extends Activity{
 final BroadcastReceiver bReceiver = new BroadcastReceiver() {
        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);
                 // add the name and the MAC address of the object to the arrayAdapter
                 BTArrayAdapter.add(device.getName() );
                 BTArrayAdapter.notifyDataSetChanged();
            }
        }
    };
private static final int REQUEST_ENABLE_BT = 1;
public static BluetoothAdapter myBluetoothAdapter;
private ListView myListView;
public final static UUID my_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
private ArrayAdapter<String> BTArrayAdapter;
private Set<BluetoothDevice> pairedDevices;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
     setContentView(R.layout.bluetooth);
     myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
     Button b=(Button)findViewById(R.id.button1);
     if(myBluetoothAdapter == null){
         Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
                 Toast.LENGTH_LONG).show();
         finish();
     }
     else {
         if (!myBluetoothAdapter.isEnabled()) {
             Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);

             Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
                     Toast.LENGTH_LONG).show();
          }
          else{
             Toast.makeText(getApplicationContext(),"Bluetooth is already on",
                     Toast.LENGTH_LONG).show();
          }
     }
     myListView=(ListView)findViewById(R.id.listView1);

     BTArrayAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

     myListView.setAdapter(BTArrayAdapter);



     b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


                   if (myBluetoothAdapter.isDiscovering()) {
                       // the button is pressed when it discovers, so cancel the discovery
                       myBluetoothAdapter.cancelDiscovery();
                       Toast.makeText(getApplicationContext(), "cancel dis", Toast.LENGTH_SHORT).show();
                   }
                   else {
                        BTArrayAdapter.clear();
                        myBluetoothAdapter.startDiscovery();
                         Toast.makeText(getApplicationContext(), "start dis", Toast.LENGTH_SHORT).show();
                        registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));    
                    } 





             myListView.setOnItemClickListener(new OnItemClickListener() {
                 @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                     String  itemValue = (String) myListView.getItemAtPosition(position);

                        String MAC = itemValue.substring(itemValue.length() - 17);

                        BluetoothDevice bluetoothDevice = myBluetoothAdapter.getRemoteDevice(MAC);
                        ConnectingThread t = new ConnectingThread(bluetoothDevice);
                        t.start();
                    }
            });
        }
    });
     Button c=(Button)findViewById(R.id.button2);
     c.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            ListeningThread t = new ListeningThread();
            t.start();
        }
    });

}




@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    unregisterReceiver(bReceiver);
}

     }
    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(Bluetooth.my_UUID);
    } catch (IOException e) {
        e.printStackTrace();
    }
    bluetoothSocket = temp;
}

public void run() {
    Bluetooth.myBluetoothAdapter.cancelDiscovery();
    // Cancel any discovery as it will slow down the connection


    try {
        // This will block until it succeeds in connecting to the device
        // through the bluetoothSocket or throws an exception
        bluetoothSocket.connect();
    } 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();
    }
}
}
class ListeningThread extends Thread {
private final BluetoothServerSocket bluetoothServerSocket;
private final static UUID uuid = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
String name="help";
public ListeningThread() {
    BluetoothServerSocket temp = null;
    try {
        temp = Bluetooth.myBluetoothAdapter.listenUsingRfcommWithServiceRecord(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) {

            Toast.makeText(getApplicationContext(), "A connection has been accepted.",
                    Toast.LENGTH_SHORT).show();
            break;
        }
            // Manage the connection in a separate thread

            try {
                bluetoothServerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        }
    }


private Context getApplicationContext() {
    // TODO Auto-generated method stub
    return null;
}

// Cancel the listening socket and terminate the thread
public void cancel() {
    try {
        bluetoothServerSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

1 个答案:

答案 0 :(得分:0)

只需用下面的代码替换你的run(),问题就像当你试图连接可能已经与某些外围设备连接的特定设备,所以你必须先断开它。如果你有任何问题,请告诉我面对。

 try {

  bluetoothSocket.close();
  bluetoothSocket.disconnect();
    bluetoothSocket.connect();
} catch (IOException connectException) {
    connectException.printStackTrace();
    try {
        bluetoothSocket.close();
    } catch (IOException closeException) {
        closeException.printStackTrace();
    }
}
相关问题