我有一个通过蓝牙与 Arduino 连接的应用程序。该应用程序正常,但是当我开始另一个 Activity 时,我的 textview
没有更新。
我有一个读取蓝牙数据的 Thread
,还有一个刷新 textview
的计时器。
如果您第一次启动 Activity 并且我返回主 Activity textview
刷新正常,但是如果我在返回主 Activity 时再次启动 Activity textview
则不会'刷新。
帮助!!!
创建时:
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
MetrosRecorridos += ((Calibracion / Imanes / 1000) * readMessage.length()) * Sentido;
}
}
};
在连接蓝牙的按钮中:
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
线程
:
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
txtConectado = "Sonda: Desconectado";
//Toast.makeText(getBaseContext(), "Fallo de conexión", Toast.LENGTH_LONG).show();
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
刷新textview
的Timer
:
public void startTimer(){
t = new Timer();
task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView t;
t=(TextView)findViewById(R.id.txtA);
t.setText(""+MetrosRecorridos);
}
});
}
};
t.scheduleAtFixedRate(task, 0, 10);
}
以及我调用另一个 Activity 时的代码:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.opc_ajustes) {
bluetoothIn.removeCallbacksAndMessages(null);
Intent i = new Intent(getApplicationContext(), AjustesActivity.class);
i.putExtra("distancia", Math.floor(MetrosRecorridos / 10));
startActivityForResult(i, 3);
return true;
}
}
谢谢!!!
最佳答案
我无法清楚地理解问题。但我认为线程在暂停 Activity 时停止。在那种情况下,您应该为此目的创建一个单例计时器或将计时器用于应用程序类。在 onResume 方法中的 Activity 中,启动另一个线程来刷新 Textview。希望对您有所帮助
关于java - 两次启动另一个 Activity 时,线程不更新 textview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31329119/