Активность соединения Bluetooth и служба Android

Я собираю источник для подключения Bluetooth и связи приложения с устройством...

Мой источник подключается после Активности, а также с момента активации Сервиса с AlarmManager, который хорошо работает отдельно, но если соединение Активности используется, сервис не может подключиться.

Как я могу сделать так, чтобы использовать только одно Соединение от Деятельности и от Сервиса (и еще одна необходимость).

это моя основная деятельность

public class MainActivity extends AppCompatActivity{

private BluetoothLeService mBluetoothLeService;
private String mDeviceAddress;

private final BroadcastReceiver BLEStatusChangeReceiver = new BroadcastReceiver() {
    @SuppressLint("UseValueOf")
    public void onReceive(Context context, Intent intent) {
        /**
         * Reception INFORMATION from bluetooth by activity
         */
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    ButterKnife.inject(this);
    EventBus.getDefault().register(this);

    Intent bindIntent = new Intent(this, BluetoothLeService.class);
    bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);

    LocalBroadcastManager.getInstance(this).registerReceiver(
            BLEStatusChangeReceiver, makeGattUpdateIntentFilter());

}

private IntentFilter makeGattUpdateIntentFilter() {
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BroadcastCommand.ACTION_DATA_AVAILABLE);
    intentFilter.addAction(BroadcastCommand.ACTION_GATT_CONNECTED);
    intentFilter.addAction(BroadcastCommand.ACTION_GATT_DISCONNECTED);
    return intentFilter;
}

// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();

        Log.e("BLE", "onServiceConnected---==---");
        if (!mBluetoothLeService.initialize())
            finish(); // no existe bluetooth

        if (!mBluetoothLeService.bluetoothStatus()){
            mBluetoothLeService.onBluetooth();
            try { Thread.sleep(2000); } // bluetooth apagado
            catch (InterruptedException e) { e.printStackTrace(); }
        }
        mDeviceAddress = "00:11:22:33:44:55";// MAC HERE
        mBluetoothLeService.connect(mDeviceAddress,false);

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBluetoothLeService = null;
        Log.i("BLE", "onServiceDisconnected");
    }
};

@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(BLEStatusChangeReceiver);
    unbindService(mServiceConnection);
    mBluetoothLeService = null;
}

/**
 * Usado por la app para la deteccion del estado del bluetooth
 */
public void onEventMainThread(BaseEvent baseEvent) {
    Log.e("event",baseEvent.toString());
    switch (baseEvent.getEventType()) {
        case BLUETOOTH_CONNECTED:
            Log.e("STATUS",MessageFormat.format("{0} connect", mDeviceAddress));
            break;
        case BLUETOOTH_DISCONNECTED:
            Log.e("STATUS",MessageFormat.format("{0} disconnect", mDeviceAddress));
            break;
        default:
            break;
    }
}

}

Следующим является мой сервис, вызванный из AlarmManager

public class MyService extends Service {

private boolean isRunning;
private String dato = "";
private BackgroundService bs;
private CommandManager manager;
private Thread backgroundThread;
private BluetoothLeService mBluetoothLeService;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    Log.e("BackgroundService","onCreate()");

    bs = this;
    this.isRunning = false;

    manager = CommandManager.getInstance(getApplicationContext());
    Intent bindIntent = new Intent(getApplicationContext(), BluetoothLeService.class);
    bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(
            BLEStatusChangeReceiver, makeGattUpdateIntentFilter());
    this.backgroundThread = new Thread(myTask);

}

private Runnable myTask = new Runnable() {
    public void run() {
        /**
         * Here interaction with device
         */
    }
};


@Override
public void onDestroy() {

    Log.e("onDestroy","YES");
    unbindService(mServiceConnection);
    this.isRunning = false;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if(!this.isRunning) {
        this.isRunning = true;
        this.backgroundThread.start();
    }
    return START_STICKY;
}

// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {

        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        mBluetoothLeService.CallClass(bs,null);

        Log.i("BLE", "onServiceConnected");
        if (!mBluetoothLeService.initialize()) {
            stopSelf(); // no existe bluetooth
        }
        if (!mBluetoothLeService.bluetoothStatus()){
            mBluetoothLeService.onBluetooth();
            try { Thread.sleep(2000); } // bluetooth apagado
            catch (InterruptedException e) { e.printStackTrace(); }
        }

        mBluetoothLeService.connect("00:11:22:33:44:55",false); // MAC HERE
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBluetoothLeService = null;
        Log.i("zgy", "onServiceDisconnected");
    }
};

private final BroadcastReceiver BLEStatusChangeReceiver = new BroadcastReceiver() {
    @SuppressLint("UseValueOf")
    public void onReceive(Context context, Intent intent) {
        /**
         * Reception INFORMATION from bluetooth
         */
    }
};

private IntentFilter makeGattUpdateIntentFilter() {
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BroadcastCommand.ACTION_DATA_AVAILABLE);
    intentFilter.addAction(BroadcastCommand.ACTION_GATT_CONNECTED);
    intentFilter.addAction(BroadcastCommand.ACTION_GATT_DISCONNECTED);
    return intentFilter;
}

}

В итоге: как преобразовать соединения MainActivity и MyService в одно? -Чтобы избежать конфликтов и лишнего кода

0 ответов

Другие вопросы по тегам