读取蓝牙数据并将其置于MainActivity

时间:2017-12-02 18:14:49

标签: java android bluetooth handler

我一直在寻找这个,我尝试过的一切都还没有用。我实现了一个蓝牙连接服务类,让我连接并通过蓝牙发送消息到HC-05模块。我能够在控制台中看到每条消息(带有日志),但是,无论我尝试什么,我似乎都无法将收到的字节放入我可以处理它的主要活动中。以下是我的Log所在的BluetoothConnectionService类中的代码:

BluetoothConnectionService:

private Handler mHandler; // handler that gets info from Bluetooth service

// Defines several constants used when transmitting messages between the
// service and the UI.
private interface MessageConstants {
    public static final int MESSAGE_READ = 0;
    public static final int MESSAGE_WRITE = 1;
    public static final int MESSAGE_TOAST = 2;

    // ... (Add other message types here as needed.)
}    

public void run(){
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                // Read from the InputStream
                try {
                    bytes = mmInStream.read(buffer);
                    String incomingMessage = new String(buffer, 0, bytes);
                    Log.d(TAG, "InputStream: " + incomingMessage);

                    // Send the obtained bytes to the MainActivity
                    Handler mainActivityHandler = new Handler();
                    mainActivityHandler.obtainMessage(MessageConstants.MESSAGE_READ, bytes, -1, buffer);

                    // Send the obtained bytes to the UI activity.
                    /*Message readMsg = mHandler.obtainMessage(
                            MessageConstants.MESSAGE_READ, bytes, -1,
                            buffer);
                    readMsg.sendToTarget();*/
                } catch (IOException e) {
                    Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
                    break;
                }
            }
        }

MainActivity :(在onCreate中)

btnReadGlucose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //On va envoyer quelle personne il faut lire le data
                String patientName = mSpinner.getSelectedItem().toString();
                int patientPosition = mSpinner.getSelectedItemPosition();
                Log.d(TAG, "Le patient " + patientName + " a la position " + patientPosition + " est selectionne");

                //Trouver quelle lettre envoyer
                DataEnvoyer = mappingPatients(patientPosition);
                RequestData = true;

                //Envoi du data
                envoyerCommandeBluetooth(DataEnvoyer);

                //How do I call my handler ?

            }
        });

我还是蓝牙通讯处理程序的新手。我想我接近答案但我真的不知道如何在字节中获取消息并将其保存到我的主要活动中的值。

有人可以帮忙吗?

谢谢, luisarcher。

1 个答案:

答案 0 :(得分:1)

方法1:如果此服务在与活动相同的线程上运行,则将服务与活动绑定。

//IN YOUR ACTIVITY 
startService(new Intent(getApplicationContext(), BluetoothService.class));
bindService(new Intent(getApplicationContext(), BluetoothService.class), mServiceConnection, Context.BIND_AUTO_CREATE);


private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        BluetoothService.BackgroundBinder backgroundBinder = (BluetoothService.BackgroundBinder) iBinder;
        mBackgroundService = backgroundBinder.getBackgroundService();
        startPinging();
}

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

//IN SERVICE
public class BluetoothBinder extends Binder {
    public BluetoothService getBluetoothService() {
        return BluetoothService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    Log.d(TAG, "Inside onBind");
    return new BluetoothBinder();
}

现在该服务已绑定,您可以为incomingMessage声明一个getter服务器,因此当您按下activity中的按钮时,它会返回该消息。

方法2(VIA HANDLER):如果您需要一个界面来跨进程进行通信,您可以创建一个Messenger。它处理单线程上的通信。 我还没有做到这一点,但可以找到关于此的好文章here

方法3(VIA LocalBroadCast):在您的蓝牙服务中,每当收到消息时发送localBroadcast

//SERVICE
private void sendMessage(String incomingMessage) {
    Intent intent = new Intent("UNIQUE_ACTION");
    intent.putExtra("incomingMessage", incomingMessage);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

public void run(){
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                // Read from the InputStream
                try {
                    bytes = mmInStream.read(buffer);
                    String incomingMessage = new String(buffer, 0, bytes);
                    Log.d(TAG, "InputStream: " + incomingMessage);
                    sendMessage(incomingMessage);

//ACTIVITY
@Override
public void onResume() {
    super.onResume();
    // This registers mMessageReceiver to receive messages.
    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,new IntentFilter("UNIQUE_ACTION"));
}

// Handling the received Intents for the "UNIQUE_ACTION" event 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
    // Extract data included in the Intent
    String incomingMessage = intent.getStringExtra()("incomingMessage");
    Log.d(TAG, incomingMessage);
    }
};

@Override
protected void onPause() {
    // Unregister since the activity is not visible
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
    super.onPause();
}

另外,我建议查看此链接以便service and activity之间进行通信。

P.S:看看这个library用于蓝牙通信。它确实提供了从蓝牙获取数据的方法,我亲自测试过它与HC-05一起工作并且也有例子。