I am recently working with Android,I have MainActivity class .
I am using Android Studio and my problem is that
I want to connect to a bluetooth device by connect method, but it takes time and I want this method to be done and then the next line to be executed. Unfortunately synchronized and thraed do not work, moreover i have generate a sample in Intellij idea and it has worked.I should say ,i am using callback in connect method.
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));
}
and my connect method is :
@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;
}
question from:
https://stackoverflow.com/questions/65885930/how-can-i-implement-thread-in-android-mainactivity-class 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…