2
我有一個應用程序,通過藍牙與Arduino連接。該應用程序是可以的,但是當我開始另一個活動時,我的textview
不會更新。 我有一個Thread
讀取藍牙的數據,我有一個計時器刷新textview
。線程不會更新textview兩次啓動另一個活動
如果您第一次啓動活動並返回主活動textview
刷新正常,但是如果我在返回主時再次啓動活動textview
不刷新。
幫助!!!
的OnCreate:
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();
的Thread
:
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();
}
}
}
的Timer
是刷新textview
:
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);
}
而且代碼時,我調用另一個活動:
@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;
}
}
謝謝!
對不起,我從西班牙語和我的英語是非常糟糕的。但是,因爲第一次它做得很好,並且當我第二次爲線程運行該活動時? –
它可能是由於多種原因發生的,例如內存泄漏,或者您嘗試重新創建相同的事物,或者另一個線程可能會阻止它等等。這就是爲什麼您應該使用單例方法。在最糟糕的情況下,如果它不工作,您可以將計時器值保存到內部,並在恢復時重新讀取並再次調用該線程。 –