简体   繁体   English

使用Android Studio在蓝牙中连接配对的设备

[英]connecting paired devices in Bluetooth using android studio

I have created an app to display paired devices successfully but not able to connect to it. 我创建了一个可成功显示配对设备但无法连接的应用程序。

I tried a lot but i'm getting "app has been stopped working". 我做了很多尝试,但是我发现“应用已停止工作”。

Please advise on issues in my code to connect to paired devices: 请在我的代码中建议问题以连接到配对的设备:

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();
        }
    }

when I wanted to get a list of connected Bluetooth devices for my app aw well and this helped me, 当我想为我的应用程序很好地获取连接的蓝牙设备的列表时,这对我有所帮助,

Get List Of Paired Bluetooth Devices 获取配对的蓝牙设备列表

in the first link, besides giving you a list of paired devices it has onclick, which then I used second link (how to send images via Bluetooth) to communicate with my selected device 在第一个链接中,除了为您提供已配对的设备列表外,它还具有onclick功能,然后我使用了第二个链接(如何通过蓝牙发送图像)与所选设备通信

Sending Images Over Bluetooth In Android 在Android中通过蓝牙发送图像

example: 例:

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) {
 }
 }
 }
 }

hope it helps you too! 希望对您有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM