带有动态OBD命令的Android共享阵列
在我的应用程序中,我通过OBD端口和蓝牙与汽车建立了通信。 我有一个带有动态OBD命令的Android共享阵列,android,multithreading,arraylist,bluetooth,obd-ii,Android,Multithreading,Arraylist,Bluetooth,Obd Ii,在我的应用程序中,我通过OBD端口和蓝牙与汽车建立了通信。 我有一个SharedReferences,其中包含由首选项活动设置的要显示的命令的首选项 我希望使用一个共享的命令数组,可以动态地更改它们的内容,并将新的ArrayList发送到管理通信的线程 有一些方法可以做到这一点,或者简单地使用SharedReferences,当更改阵列的内容时,我会重新启动管理与设备通信的线程 我需要一些可以更改的内容(从ArrayList添加或删除命令),同时通知发送命令的线程ArrayList已更改了项目
SharedReferences
,其中包含由首选项活动设置的要显示的命令的首选项
我希望使用一个共享的命令数组,可以动态地更改它们的内容,并将新的ArrayList
发送到管理通信的线程
有一些方法可以做到这一点,或者简单地使用SharedReferences
,当更改阵列的内容时,我会重新启动管理与设备通信的线程
我需要一些可以更改的内容(从ArrayList
添加或删除命令),同时通知发送命令的线程ArrayList
已更改了项目
管理连接的方法
private synchronized void manage() {
Log.d(TAG, "connected, Socket Type:");
// Cancel the thread that completed the connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Cancel any thread currently managing connections
if (mManageThread != null) {
mManageThread.cancel();
mManageThread = null;
}
if (mmSocket != null && mmDevice != null) {
// Start the thread to manage the connection and perform transmissions
mManageThread = new ManageDataThread(mmSocket);
mManageThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Constants.DEVICE_NAME, mmDevice.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
// Update UI title
updateUserInterfaceTitle();
}
}
以及管理连接和消息交换的线程mManageThread
public class ManageDataThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private boolean wait_response = false;
private String typeCommand;
public ManageDataThread(BluetoothSocket socket) {
Log.d(TAG, "create ManageDataThread: ");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
mState = STATE_CONNECTED;
}
public void run() {
ObdCommand obc = new ObdCommand();
while(canGo) {
for (final String command : commandArray) {
byte[] send = command.getBytes();
write(send); //Setta la wait_response come true
//mState = STATE_WAIT_RESPONSE;
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (wait_response) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
obc.readResult(mmInStream);
//formattedMessage = obc.getResult();
formattedMessage = obc.getCalculatedResult();
//Ritorno la ripologia di comando
typeCommand = obc.getCommandType();
//buffer = (byte) obc.getBuffer();
// Send the obtained bytes to the UI Activity
/*mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, formattedMessage)
.sendToTarget();*/
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, typeCommand
+ ""
+ formattedMessage)
.sendToTarget();
wait_response = false;
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
try {
ManageDataThread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Write to the connected OutStream.
*
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
wait_response = true;
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
canGo = false;
}
}
public void cancel() {
try {
canGo = false;
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
在这里,我不能使用一些方法来检查数组是否已更改,并更改线程中的命令列表?
唯一的方法是停止并重新启动方法
这里是呼叫主活动
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
rpmTxt = (TextView) findViewById(R.id.rpmText);
speedTxt = (TextView) findViewById(R.id.speedText);
coolantTxt = (TextView) findViewById(R.id.colantTempText);
carbTxt = (TextView) findViewById(R.id.carbTypeText);
nodata = (TextView) findViewById(R.id.nodataTxt);
canerror = (TextView) findViewById(R.id.canErrorTxt);
/**
* SharedPreferences per gestire quali cose mostrare nell'activity
*/
showUserSettings();
/*Check bluetooth sensor*/
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(getApplicationContext(), "Il telefono NON supporta il bluetooth",
Toast.LENGTH_LONG).show();
}
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (mBluetoothService == null) {
setupChat();
}
}
和setupchat()方法调用MyBluetoothService.java中的线程
/**
* Set up the UI and background operations for chat.
*/
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the BluetoothChatService to perform bluetooth connections
mBluetoothService = new MyBluetoothService(MainActivity.this, mHandler, commandArray);
// Initialize the buffer for outgoing messages
//mOutStringBuffer = new StringBuffer("");
}
将从SharedReferences读取的commandArray发送到启动线程的类我想你可以这样做,但这不会促进两个线程之间的通信,因为在主线程上调用了onSharedPreferenceChanged
,所以你仍然需要实现它。@Jonathan727但是我如何将此检查到管理通信的线程?正如您所说,我检查对MainActivity的更改,如果OnSharedPreferenceChangeListener是焦点,我会停止线程并用新数组启动另一个线程?我会发布一些代码,这样我的问题就更清楚了