首页 > 解决方案 > 无法在 Android Studio 中配对蓝牙设备

问题描述

我正在创建一个应用程序,它将连接到通过蓝牙配对或发现的设备。

我能够发现新设备并能够看到配对的设备,但是当我从列表中单击设备时,我无法连接到它。

在下面的代码中,在代码的最后,我在行后收到了 toast 消息“test”:

BTSocket = device.createRfcommSocketToServiceRecord(BTMODULEUUID);

任何人都可以帮助我/给我关于代码有什么问题的建议吗?

package com.example.Pillwoah;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

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.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity4 extends AppCompatActivity {

    TextView phoneName, deviceList;

    private BluetoothAdapter BA;
    private Set<BluetoothDevice> pairedDevices;
    private ArrayAdapter<String> BAarray, BANewArray;
    private ListView DeviceList, NewDevice;

    private BluetoothSocket BTSocket = null;
    private BluetoothDevice device = null;

    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private final static int REQUEST_ENABLE_BT = 1;
    private final static int REQUEST_COARSE_LOCATION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);

        Button mEnable = (Button) findViewById(R.id.enable);
        Button mOff = (Button) findViewById(R.id.off);
        Button mPaired = (Button) findViewById(R.id.paired);
        Button mDiscover = (Button) findViewById(R.id.discover);

        deviceList = findViewById(R.id.deviceTitle);
        deviceList.setText(null);
        phoneName = findViewById(R.id.name);
        phoneName.setText(getLocalBtName());

        BA = BluetoothAdapter.getDefaultAdapter();

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

        DeviceList = (ListView)findViewById(R.id.deviceListView);
        DeviceList.setAdapter(BAarray);
        DeviceList.setOnItemClickListener(DeviceClickListener);

        NewDevice = (ListView)findViewById(R.id.newDeviceView);
        NewDevice.setAdapter(BANewArray);
        NewDevice.setOnItemClickListener(DeviceClickListener);

        if (BA == null) {
            Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            mEnable.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bluetoothOn(v);
                }
            });

            mOff.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bluetoothOff(v);
                }
            });

            mPaired.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkLocationPermission();
                    listPairedDevices(v);
                }
            });

            mDiscover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkLocationPermission();
                    discover(v);
                }
            });
        }
    };

    protected void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_COARSE_LOCATION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_COARSE_LOCATION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //discover(view); // --->
                } else {
                    //TODO re-request
                }
                break;
            }
        }
    }

    public String getLocalBtName(){
        if(BA == null){
            BA = BluetoothAdapter.getDefaultAdapter();
        }
        String name = BA.getName();
        if(name == null){
            name = BA.getAddress();
        }

        return name;
    }

    private void bluetoothOn(View view){
        if(!BA.isEnabled()){
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            Toast.makeText(getApplicationContext(), "Bluetooth turned on", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "Bluetooth is already on", Toast.LENGTH_SHORT).show();
        }
    }

    private void bluetoothOff(View view){
        BA.disable();
        BAarray.clear();
        Toast.makeText(getApplicationContext(), "Bluetooth turned off", Toast.LENGTH_SHORT).show();
    }

    private void discover(View view) {
        deviceList.setText("Available Devices");
        if (BA.isDiscovering()) {
            BA.cancelDiscovery();
            deviceList.setText(null);
            BANewArray.clear();
            Toast.makeText(getApplicationContext(), "Discovery stopped", Toast.LENGTH_SHORT).show();
        }
        else {
            if (BA.isEnabled()) {
                Intent discoverIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 50);
                startActivity(discoverIntent);
                BANewArray.clear();
                BAarray.clear();
                BA.startDiscovery();
                Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
                registerReceiver(BReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
            }
            else {
                Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private final BroadcastReceiver BReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                BANewArray.add(device.getName() + "\n" + device.getAddress());
                BANewArray.notifyDataSetChanged();
            }
        }
    };

    private void listPairedDevices(View view){
        deviceList.setText("Previously Connected Devices");
        pairedDevices = BA.getBondedDevices();
        if(BA.isEnabled()){
            BANewArray.clear();
            BAarray.clear();
            for(BluetoothDevice device : pairedDevices)
                BAarray.add(device.getName() + "\n" + device.getAddress());

            Toast.makeText(getApplicationContext(), "Show paired devices", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
        }
    }

    private AdapterView.OnItemClickListener DeviceClickListener = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {

            if(!BA.isEnabled()) {
                Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
                return;
            }

            String info = ((TextView) v).getText().toString();
            final String address = info.substring(info.length() - 17);
            final String name = info.substring(0,info.length() - 17);

            new Thread() {
                public void run() {
                    device = BA.getRemoteDevice(address);

                    try {
                        BTSocket = device.createRfcommSocketToServiceRecord(BTMODULEUUID);
                        getMainLooper().prepare();
                        Toast.makeText(getBaseContext(), "test", Toast.LENGTH_SHORT).show();
                        getMainLooper().loop();
                    } catch (IOException e) {
                        getMainLooper().prepare();
                        Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                        getMainLooper().loop();
                    }
                    // Establish the Bluetooth socket connection.
                    try {
                        BTSocket.connect();
                        getMainLooper().prepare();
                        Toast.makeText(getBaseContext(), "test 2", Toast.LENGTH_SHORT).show();
                        getMainLooper().loop();
                    } catch (IOException e) {
                        try {
                            BTSocket.close();
                            getMainLooper().prepare();
                            Toast.makeText(getBaseContext(), "test 3", Toast.LENGTH_SHORT).show();
                            getMainLooper().loop();
                        } catch (IOException e2) {
                            //insert code to deal with this
                            getMainLooper().prepare();
                            Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                            getMainLooper().loop();
                        }
                    }
                }

                public void cancel() {
                    try {
                        BTSocket.close();
                    } catch (IOException e3) {
                        getMainLooper().prepare();
                        Toast.makeText(getBaseContext(), "Could not close the client socket", Toast.LENGTH_SHORT).show();
                        getMainLooper().loop();
                    }
                }
            }.start();
        }
    };
}

标签: javaandroidbluetoothandroid-bluetooth

解决方案


推荐阅读