无法在简单的应用程序中连接到BT扬声器

时间:2019-10-05 13:28:09

标签: java android bluetooth

我正在努力制作一个非常简单的应用程序,该应用程序必须执行以下操作:

  1. 打开BT
  2. 开始扫描
  3. 找到具有硬编码的MAC地址的设备后,连接到它。

我在第三点失败:

rfcommSocketToServiceRecord.connect();

方法connect引发了一个异常,不幸的是该异常并没有太多说明失败:

read failed, socket might closed or timeout, read ret: -1

我已允许我的应用使用以下特权:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

有人遇到上述问题吗?您是否有任何线索可能导致了问题? 这是应用程序的代码:

import androidx.appcompat.app.AppCompatActivity;

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.content.pm.PackageManager;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.os.Parcelable;
import android.widget.Toast;


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

public class MainActivity extends AppCompatActivity {

    private final String DEFAULT_MAC_ADDRESS = "";

    private static UUID MY_UUID = null;
    private static BluetoothAdapter mBluetoothAdapter = null;
    private static BluetoothDevice mDevice = null;
    private static BluetoothSocket rfcommSocketToServiceRecord = null;

    private final BroadcastReceiver mUUIDReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_UUID.equals(action)) {
                Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
                if (uuidExtra.length == 0) {
                    Toast.makeText(context, "uuidExtra.length == 0", Toast.LENGTH_LONG).show();
                    return;
                }
                ParcelUuid parcelUuid = (ParcelUuid) uuidExtra[0];
                MY_UUID = parcelUuid.getUuid()/*UUID.randomUUID()*/;

                try {
                    rfcommSocketToServiceRecord = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
                    mBluetoothAdapter.cancelDiscovery();
                    rfcommSocketToServiceRecord.connect();

                    PackageManager pm = context.getPackageManager();
                    Intent launchIntent = pm.getLaunchIntentForPackage("com.spotify.music");
                    context.startActivity(launchIntent);
                } catch (IOException e) {
                    Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                Toast.makeText(context, "FOUND DEVICE", Toast.LENGTH_SHORT).show();
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String deviceHardwareAddress = device.getAddress();
                if (deviceHardwareAddress.equals(DEFAULT_MAC_ADDRESS)) {
                    mDevice = device;
                    mBluetoothAdapter.cancelDiscovery();

                    ParcelUuid parcelUuid = mDevice.getUuids()[0];
//                    MY_UUID = parcelUuid.getUuid();
                    MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
                }
            }/* else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                Toast.makeText(context, "ACTION_DISCOVERY_STARTED", Toast.LENGTH_SHORT).show();
            }*/ else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (mDevice == null || mBluetoothAdapter.isDiscovering() || rfcommSocketToServiceRecord != null) {
                    return;
                }
                try {
                    rfcommSocketToServiceRecord = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
                    rfcommSocketToServiceRecord.connect();

                    Toast.makeText(context, "CONNECTED", Toast.LENGTH_SHORT).show();

                    PackageManager pm = context.getPackageManager();
                    Intent launchIntent = pm.getLaunchIntentForPackage("com.spotify.music");
                    context.startActivity(launchIntent);
                } catch (IOException e) {
                    Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
                }

//                if (mDevice == null) {
//                    return;
//                }
//
//                unregisterReceiver(mBTReceiver);
//                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_UUID);
//                registerReceiver(mUUIDReceiver, filter);
//
//                mDevice.fetchUuidsWithSdp();
            }
        }
    };

    private void startScanningBT() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }

        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mBTReceiver, filter);

        mBluetoothAdapter.startDiscovery();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, MainFragment.newInstance())
                    .commitNow();
        }
        startScanningBT();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBTReceiver);
        unregisterReceiver(mUUIDReceiver);
    }
}

我知道这很糟糕,但是它只需要做4件事。

0 个答案:

没有答案