如何在 Android MainActivity 类中实现线程?

问题描述

我最近在使用 Android,我有 MainActivity 类。 我正在使用 Android Studio,我的问题是 我想通过连接方法连接到蓝牙设备,但这需要时间,我希望完成此方法,然后执行下一行。不幸的是,synchronized 和 thraed 不起作用,而且我在 Intellij 想法中生成了一个示例并且它起作用了。我应该说,我在连接方法中使用回调。

public class MainActivity extends AppCompatActivity{

    private BluetoothAdapter mBluetoothAdapter;
    private GenericBleService genericBleService;
    private BluetoothDevice bluetoothDevice;

    @Override
    protected  synchronized void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothDevice = mBluetoothAdapter.getRemoteDevice("D9:69:99:AA:67:47");

        genericBleService = new GenericBleService().getInstance(bluetoothDevice,getApplication());

        /////////////// this is connect method \\\\\\\\\\\\\\\\\\
        genericBleService.connect(bluetoothDevice.getAddress());

        System.out.println(Thread.currentThread().getName());
        System.out.println("getBatteryLevel " + genericBleService.getAttribute(GattAttribute.BATTERY_LEVEL));
        System.out.println("getBatteryLevel 2 : " + genericBleService.getAttribute(GattAttribute.BATTERY_LEVEL));

    }

我的连接方法是:

@Override
    public Boolean connect(String deviceAddr) {
        reentrantLock.lock();
        System.out.println("Generic Ble Service connect");
        if (GenericBleConfig.getBluetoothAdapter() == null || deviceAddr == null) {
            Log.w(TAG,"BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        // Previously connected device.  Try to reconnect.
        if (deviceAddress != null && deviceAddr.equals(deviceAddress)
                && mBluetoothGatt != null) {
            Log.d(TAG,"Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                return true;
            } else {
                return false;
            }
        }

        final BluetoothDevice device = GenericBleConfig.getBluetoothAdapter().getRemoteDevice(deviceAddr);
        if (device == null) {
            Log.w(TAG,"Device not found.  Unable to connect.");
            return false;
        }
        // We want to directly connect to the device,so we are setting the autoConnect
        // parameter to false.

        mBluetoothGatt = device.connectGatt(GenericBleConfig.getContext(),true,mGattCallback);
        Log.d(TAG,"Trying to create a new connection.");
        this.deviceAddress = deviceAddr;
        this.bluetoothDevice = device;
        System.out.println("Here is connect Thread : " + Thread.currentThread().getName());
        return true;
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)