我一直在问这个问题,但是代码可能太乱了,影响了大家阅读,现在简化了代码,希望你能帮助我,非常感谢你;
有时CPU扫描上的几个小时占用太高,但有时候会有几天。抓取logcat日志发现睡眠方法有时候不执行,如果没有连续执行会导致CPU使用率过高,但我不知道为什么睡眠方法不会执行。
private void startReceive() {
stopReceive = false;
new Thread(new Runnable() {
@Override
public void run() {
int timeout = 1000;
while (!stopReceive) {
if (mUsbDeviceConnection != null) {
try {
byte[] receiveBytes = new byte[64];
int value = mUsbDeviceConnection.bulkTransfer(mUsbEndpoint, receiveBytes,
receiveBytes.length, timeout);
if (value > 0) {
for (int i = 2; !stopReceive && i < receiveBytes.length; i++) {
byte b = receiveBytes[i];
if (b != 0) {
result += new String(new byte[]{b});
}
if (!stopReceive && !result.equals("") && result != null) {
Runtime.getRuntime().exec("input text " + result);
}
}
}
Thread.sleep(100);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}).start();
}
答案 0 :(得分:1)
您应该更好地查看此帖子并尝试查找哪种方法占用更多系统资源:https://stackoverflow.com/a/14688291/6176003
答案 1 :(得分:0)
这似乎是在主线程上运行的一个巨大的线程,这将大大降低设备的性能。
您应该以异步方式运行大型操作,这意味着它将在后台线程中运行,而不会影响现在出现问题的UI线程:
以下是实现方式的示例:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// StartReceive code..
stopReceive = false;
new Thread(new Runnable() {
@Override
public void run() {
int timeout = 1000;
while (!stopReceive) {
if (mUsbDeviceConnection != null) {
try {
byte[] receiveBytes = new byte[64];
int value = mUsbDeviceConnection.bulkTransfer(mUsbEndpoint, receiveBytes,
receiveBytes.length, timeout);
if (value > 0) {
for (int i = 2; !stopReceive && i < receiveBytes.length; i++) {
byte b = receiveBytes[i];
if (b != 0) {
result += new String(new byte[]{b});
}
if (!stopReceive && !result.equals("") && result != null) {
Runtime.getRuntime().exec("input text " + result);
}
}
}
Thread.sleep(100);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}).start();
return "Done";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// We're done
}
@Override
protected void onPreExecute() {
// Before starting operation
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
如何启动线程:
LongOperation longOp = new LongOperation();
longOp.execute();