如何持续显示蓝牙设备连接/断开状态

时间:2017-07-02 08:50:58

标签: java android bluetooth-lowenergy

我正在尝试开发一个应用程序,用户可以在启动应用程序后知道他/她的Bluetooth Le设备的状态,并在Home Fragment的文本视图中更新连接状态。我试图实现它通过从Ble服务发送Broadcast并在onResume of Home片段中捕获它,然后在状态文本视图中更新它。状态确实会更新但是如果我更改了片段并返回到主片段,则文本视图显示状态变为空白,尽管蓝牙乐器设备已连接。如何解决此问题以便状态显示连接完全如果设备已断开连接并断开连接?

任何形式的指导都将受到高度赞赏。

这是我用来实现上述

的代码段

Bleservice.java

 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);
        }
    }

 private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

在HomeFragment.java

public class HomeFragment extends Fragment 
{
    private BroadcastReceiver mReceiver;
@Override
protected void onResume() {
    super.onResume();
mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (Bleservice.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected = true;
                updateConnectionState(R.string.connected);


            } else if (Bleservice.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected = false;
                updateConnectionState(R.string.disconnected);


            }
        }


    };
    getActivity().registerReceiver(mReceiver,makeGattUpdateIntentFilter());

}

private void updateConnectionState(final int resourceId) {
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {

            tv_connected_disconnected.setText(resourceId);

        }
    });
}

@Override
public void onDestroy() {
    super.onDestroy();
    getActivity().unregisterReceiver(mReceiver);
}

 private static IntentFilter makeGattUpdateIntentFilter() {
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Bleservice.ACTION_GATT_CONNECTED);
    intentFilter.addAction(Bleservice.ACTION_GATT_DISCONNECTED);
    return intentFilter;

}

1 个答案:

答案 0 :(得分:0)

通过bindService连接到BleService。查看活动与服务的示例。

private BleService mBluetoothLeService;
private boolean isConnected;

@Override
protected void onStart() {
    super.onStart();
    Intent bindIntent = new Intent(this, BleService.class);
    startService(bindIntent);
    bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
    registerServiceReceiver(); //register here your mGattCallback that get actions from BleService
}

@Override
protected void onStop() {
    super.onStop();
    unbindService(mServiceConnection);
    mBluetoothLeService = null;
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mGattUpdateReceiver);
}

在方法bindService中,您需要传递一个管理Service Lifecycle的ServiceConnection。

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

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {

        mBluetoothLeService = ((BleService.LocalBinder) service).getService();
        isConnected = (mBluetoothLeService.getConnectionState() != BleService.STATE_CONNECTED) 

    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBluetoothLeService = null;
    }
};

在服务中,您需要声明Binder。

private final IBinder mBinder = new LocalBinder();

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}
public class LocalBinder extends Binder {
    public BleService getService() {
        return BleService.this;
    }
}


public int getConnectionState() {
    return mConnectionState;
}

现在,在绑定到BleService之后,您可以获得连接状态。