我正在尝试从我的 android 应用程序中的串行蓝牙流读取数据。数据被发送到处理程序以显示它。它可以正常工作几分钟,然后停止显示数据(但该应用程序仍在运行)。我认为这与我的处理程序中的内存泄漏有关,但我不知道如何解决它..
This is where I found the code
如果有人能帮助我,我会很高兴。 提前致谢
public class MainActivity extends ActionBarActivity {
static BluetoothAdapter mBluetoothAdapter = null;
static Handler mHandler = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Does the device support bluetooth?
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Device does not support Bluetooth",Toast.LENGTH_LONG).show();
}
//Turn on Bluetooth if disabled
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
//Get the Bluetooth module device
BluetoothDevice mDevice = null;
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if(device.getName().equals("HC-06")) {
mDevice = device;
}
}
}
if(mDevice == null){
Toast.makeText(this,"Device not found",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this,"connected to " + mDevice.getName(),Toast.LENGTH_LONG).show();
ConnectThread mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
switch(msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
ScrollView scrollView1 = (ScrollView) findViewById(R.id.scroll);
TextView textView1 = (TextView) findViewById(R.id.statusText);
textView1.append(writeMessage + "\n");
scrollView1.fullScroll(View.FOCUS_DOWN);
break;
}
}
};
}
}
最佳答案
这不是内存泄漏, 在 handleMessage() 中,您应该执行轻量级操作,例如将文本设置为 textview。
但是将您的 scrollView1 和 textview 1 声明为全局参数,只是为了避免每次都执行 findViewById 操作,这应该会有所帮助。
您还传递了一些数据,但在生成字符串后对其进行了裁剪,因此您不需要完整数据,在您的 CommnadThread 中执行该操作并传递您需要显示的准确数据不是更好吗。
关于java - Android 处理程序中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30123611/