建立蓝牙连接

时间:2016-01-08 09:13:09

标签: java android bluetooth

我不知道问题是什么。我已经尝试了其他解决方案,但没有真正有效这是我的代码。我只需建立与我的蓝牙盾的连接。 Mac地址已经确定。一旦我点击了蓝牙盾牌的mac添加,它就会关闭。拜托,拜托。帮助

package aijm.pd.testing;

/**
 * Created by Alyssa on 1/7/2016.
 */
 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.view.View;
 import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
 import android.widget.Button;
 import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.Toast;

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

public class newConnection extends Activity {

    private static final int REQUEST_ENABLE_BT = 1;

    ListView listDevicesFound;
    Button btnScanDevice;
    TextView stateBluetooth;
    BluetoothAdapter bluetoothAdapter;

    ArrayAdapter<String> btArrayAdapter;

    // universal UUID
    private static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
    // bluetooth device MAC address
    private static String address = "20:00:06:08:10:40";


    ThreadConnectBTDevice myThreadConnectBTDevice;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newconnection);

        btnScanDevice = (Button)findViewById(R.id.scandevice);
        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        listDevicesFound = (ListView)findViewById(R.id.devicesfound);
        btArrayAdapter = new ArrayAdapter<String>(newConnection.this, android.R.layout.simple_list_item_1);
        listDevicesFound.setAdapter(btArrayAdapter);

        listDevicesFound.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                BluetoothDevice device = (BluetoothDevice)parent.getItemAtPosition(position);
                Toast.makeText(newConnection.this, "Name: "+device.getName()+ "\n"
                + "Address: " +device.getAddress()+ "\n"
                + "Bond state: " +device.getBondState()+ "\n"
                + "Bluetooth class: " +device.getBluetoothClass()+ "\n"
                + "Class: " +device.getClass(), Toast.LENGTH_LONG).show();

                myThreadConnectBTDevice = new ThreadConnectBTDevice(device);
                myThreadConnectBTDevice.start();

            }
        });

        CheckBlueToothState();

        btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);

        registerReceiver(ActionFoundReceiver,
                new IntentFilter(BluetoothDevice.ACTION_FOUND));
    }

    private class ThreadConnectBTDevice extends Thread {

        private BluetoothSocket bluetoothsocket = null;
        private BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);

        public ThreadConnectBTDevice(BluetoothDevice device) {
            try {
                bluetoothsocket = device.createRfcommSocketToServiceRecord(myUUID);
                stateBluetooth.setText("Bluetooth socket: " + bluetoothsocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
            bluetoothAdapter.cancelDiscovery();

            try {
                bluetoothsocket.connect();
                stateBluetooth.setText("Connection Established!");
            } catch (IOException e) {
                try {
                    bluetoothsocket.close();
                } catch (IOException ee) {
                    stateBluetooth.setText("Unable to close socket during connection failure." + ee.getMessage());
                }
            }

        }
    }

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

    private void CheckBlueToothState(){
        if (bluetoothAdapter == null){
            stateBluetooth.setText("Bluetooth NOT support");
        }else{
            if (bluetoothAdapter.isEnabled()){
                if(bluetoothAdapter.isDiscovering()){
                    stateBluetooth.setText("Bluetooth is currently in device discovery process.");
                }else{
                    stateBluetooth.setText("Bluetooth is Enabled.");
                    btnScanDevice.setEnabled(true);
                }
            }else{
                stateBluetooth.setText("Bluetooth is NOT Enabled!");
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
    }

    private Button.OnClickListener btnScanDeviceOnClickListener
            = new Button.OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            btArrayAdapter.clear();
            bluetoothAdapter.startDiscovery();
        }};

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if(requestCode == REQUEST_ENABLE_BT){
            CheckBlueToothState();
        }
    }

    private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                btArrayAdapter.notifyDataSetChanged();
            }
        }};

}

1 个答案:

答案 0 :(得分:0)

尝试更换:

   BluetoothDevice device = (BluetoothDevice)parent.getItemAtPosition(position);

使用以下代码:

    String tmp = (String) parent.getItemAtPosition(position);
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(tmp.split("\n")[1]);

问题在于,不可能直接将“getItemAtPostion(position)”的输出强制转换为“BluetoothDevice”对象。所以你首先得到getItemAtPostion(position)的输出作为字符串,然后从字符串中提取设备信息。

希望它对你有所帮助。