读取蓝牙数据并放入MainActivity
Reading Bluetooth data and putting it to MainActivity
我一直在寻找这个,但我尝试过的一切都没有奏效。我实施了蓝牙连接服务 class,让我可以通过蓝牙连接并向 HC-05 模块发送消息。我能够在控制台中看到每条消息(带有日志),但是,无论我尝试了什么,我似乎都无法将接收到的字节放入我可以处理的主 activity 中。这是我在我的日志所在的 BluetoothConnectionService class 中的代码:
蓝牙连接服务:
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 ?
}
});
我仍然是蓝牙通信处理程序的新手。我想我已经接近答案了,但我真的不知道如何在字节中获取消息并将其保存到我的主 activity.
中的值
有人能帮忙吗?
谢谢,
luisarcher.
方法 1:如果此服务 运行 与 activity 在同一线程上,则将服务与 activity 绑定。
//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 中的按钮时,它 returns 您将收到消息。
方法 2(通过 HANDLER):如果您需要一个界面来跨进程通信,您可以创建一个 Messenger。它处理单线程上的通信。
我还没有这样做,但是可以找到关于此的很好的 post here。
方法 3(通过 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();
}
此外,我建议查看此 link 以了解 service and activity.
之间的通信
P.S:看看这个 library for bluetooth communication.It 确实提供了从蓝牙获取数据的方法,我亲自测试过它可以与 HC-05 一起使用,并且有例子。
我一直在寻找这个,但我尝试过的一切都没有奏效。我实施了蓝牙连接服务 class,让我可以通过蓝牙连接并向 HC-05 模块发送消息。我能够在控制台中看到每条消息(带有日志),但是,无论我尝试了什么,我似乎都无法将接收到的字节放入我可以处理的主 activity 中。这是我在我的日志所在的 BluetoothConnectionService class 中的代码:
蓝牙连接服务:
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 ?
}
});
我仍然是蓝牙通信处理程序的新手。我想我已经接近答案了,但我真的不知道如何在字节中获取消息并将其保存到我的主 activity.
中的值有人能帮忙吗?
谢谢, luisarcher.
方法 1:如果此服务 运行 与 activity 在同一线程上,则将服务与 activity 绑定。
//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 中的按钮时,它 returns 您将收到消息。
方法 2(通过 HANDLER):如果您需要一个界面来跨进程通信,您可以创建一个 Messenger。它处理单线程上的通信。 我还没有这样做,但是可以找到关于此的很好的 post here。
方法 3(通过 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();
}
此外,我建议查看此 link 以了解 service and activity.
之间的通信P.S:看看这个 library for bluetooth communication.It 确实提供了从蓝牙获取数据的方法,我亲自测试过它可以与 HC-05 一起使用,并且有例子。