Я новичок в разработке Android и в настоящее время я пытаюсь изменить пример кода для интерфейса Bluetooth LE, найденного здесь https://developer.android.com/samples/BluetoothLeGatt/index.html.
Этот демонстрационный проект разделен на два действия, но я хочу свести его к одному виду деятельности; DeviceControlActivity изменен на «обычный» Java-класс. После нескольких попыток я сделал BluetoothLeService работать с этим конструктором моего класса Control Device:Мой широковещательный приемник не принимает трансляции с местной службы
public DeviceControl (BluetoothDevice device, Context context) {
mDeviceName = device.getName();
mDeviceAddress = device.getAddress();
this.context = context;
Log.d(TAG, "DeviceControl construktor");
Log.d(TAG, "Context = " + context);
Intent gattServiceIntent = new Intent(context, BluetoothLeService.class);
context.bindService(gattServiceIntent, mServiceConnection, context.BIND_AUTO_CREATE);
}
Класс BluetoothLeService едут с Log.d() 'ы и, кажется, работает нормально; Однако, вещает он не излучает здесь:
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
};
private void broadcastUpdate(final String action) {
Log.d(TAG, "Methode broadcastUpdate aufgerufen. Action = " + action);
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
Однако они никогда не прибывают в DeviceControl класса я изначально связала обслуживание:
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Broadcast received");
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// Show all the supported services and characteristics on the user interface.
System.out.println("GATT-services discovered");
displayGattServices(mBluetoothLeService.getSupportedGattServices());
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
Что случилось здесь?
Это выглядит хорошо, но помещено в onResume на самом деле было бы правильно. Соедините его с вызовом unregisterReceiver в методе onPause. Это позволит убедиться, что он зарегистрирован только при активном действии. В противном случае он будет всегда зарегистрирован (до тех пор, пока процесс не будет убит), и активность никогда не сможет быть собрана в мусор, в основном это утечка памяти. Вы также можете сделать это в паре onStart/onStop. – RobCo