我有一个连接到蓝牙设备的代码,打开一个与正在运行的线程通信的蓝牙套接字,该线程运行在主要活动中运行的函数。我想将所有连接序列移动到另一个活动,然后像现在一样从主线程操作线程。问题是它们都是相连的。我希望可以选择在这些活动之间发送消息(意味着保持套接字从其他活动运行),即这条消息: mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name) .sendToTarget();
因为不可能在活动之间传递处理程序,我不知道如何/如果可能的话。做这样的事情最好的方法是什么?添加了部分代码。谢谢。
mHandler = new Handler(){
public void handleMessage(android.os.Message msg){
if(msg.what == MESSAGE_READ){
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
RxMessage = readMessage.split(" ");
if (sH.isStringInCorrectOrder(RxMessage,Weight))
populateListView(RxMessage);
mReadBuffer.setText(readMessage);
}
if(msg.what == CONNECTING_STATUS){
if(msg.arg1 == 1)
mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj));
else
mBluetoothStatus.setText("Connection Failed");
}
}
};
private void connectBT (){
mBluetoothStatus.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
final String address = "98:D3:31:30:39:75";
final String name = "HC-06";
// Spawn a new thread to avoid blocking the GUI one
new Thread()
{
public void run() {
boolean fail = false;
BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
皈依舞
相关分类