这已经讨论过很多次了,但对我来说仍然是一个真正的痛苦。
问题:每当我尝试更新 TextView 中的文本时,应用程序就会崩溃
上下文:我使用具有多线程的蓝牙应用程序。每当获得新消息时,“监听”线程 (ConnectedThread) 都会发送 Handler。然后在初始化 TextView 的主 Activity 中解析此处理程序。
到目前为止我已经尝试/检查过的内容:
- 我想我没有从不同的活动/线程更新 TextView
- 在 setContentView(R.layout.main) 之后初始化 TextView;(好吧,在其他帖子中,这引起了麻烦)
代码:(简而言之)
主要活动
public class BluetoothActivity extends Activity {
private TextView mDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
.....
..
}
private void setupApp() {
// Initialize the BluetoothService to perform bluetooth connections
// This is where the Handler is passed to "ConnectedThread" (it is part of
mService)
mService = new BluetoothService(this, mHandler);
}
// The Handler that gets information back from the BluetoothService
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
......
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
if(D) Log.d(TAG, "Received: " + readMessage);
mDisplay.setText(readMessage); <----- THIS IS THE ISSUE
break;
.......
....
}
}
};
连接线程
private class ConnectedThread extends Thread {
......
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch ...
}
}
}
主要是用于显示传入消息的功能
Toast.makeText(getApplicationContext(), "Received: " + readMessage,
Toast.LENGTH_SHORT).show();