使用android studio连接蓝牙中的配对设备

时间:2015-11-17 08:50:53

标签: android bluetooth

我创建了一个应用程序来成功显示配对设备但无法连接到它。

我尝试了很多,但我得到了#34; app已停止工作"。

请告知我的代码中连接到配对设备的问题:

public class MainActivity extends AppCompatActivity  {

    public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    BluetoothAdapter bt;
    ArrayAdapter<String> listAdapter;
    Set<BluetoothDevice> devicesArray;
    ListView listview;
    Button connectbutton;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub

            super.handleMessage(msg);
                    Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        if(bt==null){
            Toast.makeText(getApplicationContext(), "no bluetooth on device",Toast.LENGTH_SHORT).show();
            finish();

        }
        else
        {
            if(!bt.isEnabled()){
                Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent,1);
            }

        }
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int arg2, long arg3) {

                Toast.makeText(getApplicationContext(), (CharSequence) parent.getItemAtPosition(arg2), Toast.LENGTH_SHORT).show();
                if(bt.isDiscovering())
                {
                    bt.cancelDiscovery();
                }
                BluetoothDevice selectedDevice = (BluetoothDevice) parent.getItemAtPosition(arg2);


            }
        });
    }

    public void onButtonClick(View v)
    {
        getpaireddevices();

    }

    public void onButtonClick2(View v)
    {
        startdiscovery();
    }

    private void getpaireddevices() {
        devicesArray = bt.getBondedDevices();
        if (devicesArray.size() > 0) {
            for (BluetoothDevice device : devicesArray)
                listAdapter.add(device.getName());
        }
    }

    private void startdiscovery()
    {
        bt.cancelDiscovery();
        bt.startDiscovery();
    }




    private void init() {
        listview = (ListView)findViewById(R.id.listView);    
        connectbutton = (Button)findViewById(R.id.button);
        listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
        listview.setAdapter(listAdapter);
        bt= BluetoothAdapter.getDefaultAdapter();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_CANCELED)
        {
            Toast.makeText(getApplicationContext(), "bluetooth must be turned on to continue",Toast.LENGTH_SHORT).show();
            finish();
        }
    }

1 个答案:

答案 0 :(得分:0)

当我想为我的应用程序获取连接的蓝牙设备列表时,这对我很有帮助,

Get List Of Paired Bluetooth Devices

在第一个链接中,除了给你一个已点击的配对设备列表,然后我使用第二个链接(如何通过蓝牙发送图像)与我选择的设备进行通信

Sending Images Over Bluetooth In Android

示例:

class SendData extends Thread {
 private BluetoothDevice device = null;
 private BluetoothSocket btSocket = null;
 private OutputStream outStream = null;

 public SendData(){
 device = mBluetoothAdapter.getRemoteDevice(address);
 try
 {
 btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
 }
 catch (Exception e) {
 // TODO: handle exception
 }
 mBluetoothAdapter.cancelDiscovery();
 try {
 btSocket.connect();
 } catch (IOException e) {
 try {
 btSocket.close();
 } catch (IOException e2) {
 }
 }
 Toast.makeText(getBaseContext(), "Connected to " + device.getName(), Toast.LENGTH_SHORT).show();
 try {
 outStream = btSocket.getOutputStream();
 } catch (IOException e) {
 }
 }

 public void sendMessage()
 {
 try {
 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.white);
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 bm.compress(Bitmap.CompressFormat.JPEG, 100,baos); //bm is the bitmap object
 byte[] b = baos.toByteArray();
 Toast.makeText(getBaseContext(), String.valueOf(b.length), Toast.LENGTH_SHORT).show();
 outStream.write(b);
 outStream.flush();
 } catch (IOException e) {
 }
 }
 }
 }

希望它对你有所帮助!