gpt4 book ai didi

java - 多线程时 onClick 随机不被调用

转载 作者:行者123 更新时间:2023-12-01 18:43:03 25 4
gpt4 key购买 nike

所以基本上我的应用程序可以读取和处理加速度传感器值并实时显示它们。此功能就是我所说的测量,通过处理传感器值,我的意思是计算 FFT 以及将新值存储在临时内部文件中。

出于性能原因,我将测量的处理部分外包给两个单独的线程,一个用于 FFT 计算,另一个用于将值存储在临时文件中。两个线程的线程优先级均设置为 Process.THREAD_PRIORITY_BACKGROUND。传感器信号的绘制仍然发生在主线程中。

然后我有一个停止测量的按钮。我的问题是,这个随机失败,测量运行的时间越长,失败的机会就越大。在这些情况下,当我单击停止按钮时,会播放按下停止按钮的动画,但永远不会调用其 onClick 方法,导致测量继续运行。在那一刻,整个 UI 变得没有响应,因此,如果我单击另一个 UI 元素,它会对该元素进行动画处理,就像我按下它但从未释放它一样,并且它们的 onClick 方法也不会被调用。

在我实现多线程之前,这种情况不会发生。此时,我感谢有关此问题的解决方案的任何帮助、有关如何调试它的建议以及有关如何实现此测量功能的意见。我尝试在 Android Studio 中摆弄 Profiler,但无法从中提取相关信息。当它卡住时,Logcat 显示我按下并释放屏幕,但没有其他内容。

Measurement.java:

public class Measurement {

MainActivity activity;
HandlerThread fftThread;
HandlerThread fileWriterThread;
Handler fftHandler;
Handler fileWriterHandler;
FourierTransform fft;
double[] buffer;
int bufferIndex;
double[] spectrum;
FileOutputStream outputStream;
SensorManager sensorManager;
Sensor accelerationSensor;

Measurement(MainActivity activity, int bufferSize) {
this.activity = activity;
fft = new FourierTransform(bufferSize);
buffer = new double[bufferSize];
bufferIndex = 0;
spectrum = new double[bufferSize / 2];
// init threads
fftThread = new HandlerThread("FFTThread", Process.THREAD_PRIORITY_BACKGROUND);
fileWriterThread = new HandlerThread("FileWriterThread", Process.THREAD_PRIORITY_BACKGROUND);
// init sensor stuff
sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
accelerationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

// call this to start the measurement
void start() {
// open the temporary file so we can write to it continuously
try {
outputStream = activity.openFileOutput("data.tmp", Context.MODE_APPEND);

} catch (FileNotFoundException e) {
e.printStackTrace();
}
// start the threads
fftThread.start();
fileWriterThread.start();
// start their handlers
fftHandler = new Handler(fftThread.getLooper());
fileWriterHandler = new Handler(fileWriterThread.getLooper());
// register to acceleration sensor to receive values
sensorManager.registerListener(this, accelerationSensor, SensorManager.SENSOR_DELAY_FASTEST);
}

// call this to stop the measurement
void stop() {
// stop the threads without letting them finish their current task
fftThread.quit();
fileWriterThread.quit();
// close the temporary file
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

// this is called whenever the registered sensor has a new value
@Override
public void onSensorChanged(SensorEvent event) {
double value = event.values[2];
// write the new value to the buffer
buffer[bufferIndex++] = value;
if (bufferIndex == buffer.length)
bufferIndex = 0;
// draw the buffer on screen
activity.drawGsvTime(buffer);
// tell the fft thread what to do
fftHandler.post(new Runnable() {
@Override
public void run() {
// perform a fourier transform on the buffer
spectrum = fft.fft(buffer);
// draw the result of the fourier transform
activity.drawGsvFft(spectrum);
}
});
// tell the filewriter thread what to do
fileWriterHandler.post(new Runnable() {
@Override
public void run() {
// attempt to write the given data to the internal storage
try {
String line = value + "\n";
outputStream.write(line.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

Measurement measurement;
GraphSurfaceView gsvTime;
GraphSurfaceView gsvFft;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
initToolbar();
// init the measurement
measurement = new Measurement(this, 512);
}

@Override
protected void onStart() {
super.onStart();
// set the SurfaceViews
gsvTime = findViewById(R.id.gsvTime);
gsvFft = findViewById(R.id.gsvFft);
// set an onClickListener to the stop button
MaterialButton btnStop = findViewById(R.id.button_stop);
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// stop the measurement
measurement.stop();
}
});
}

@Override
protected void onResume() {
super.onResume();
// start the measurement
measurement.start();
}

public void drawGsvTime(double[] data){
gsvTime.drawGraph(data);
}

public void drawGsvFft(double[] data){
gsvFft.drawGraph(data);
}
}

GraphSurfaceView.java

public class GraphSurfaceView extends SurfaceView {

Context context;
double[] data;
Paint paint;
Path graph;
float xStart, xEnd, yStart, yEnd, yMid; // helper variables for margins and offsets

public GraphSurfaceView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.context = context;
paint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
paint.setStrokeWidth(1); // width of lines and texts
paint.setStyle(Paint.Style.STROKE); // don't fill drawn objects
paint.setColor(Color.BLACK); // line and text color
graph = new Path();
// calculate basic values
int viewWidth = getWidth();
int viewHeight = getHeight();
xStart = viewWidth * 0.02f; // where to begin drawing along the x-axis
xEnd = viewWidth - xStart; // where to stop drawing along the x-axis
yStart = viewHeight * 0.08f; // where to begin drawing along the y-axis
yEnd = viewHeight - yStart; // where to stop drawing along the y-axis
yMid = viewHeight / 2f; // middle of yStart and yEnd
}

public void drawGraph(double[] data){
this.data = data;
invalidate();
}

@Override
public void onDraw(Canvas canvas) {
// set up some helper variables
float maxAmp = (float) data[0]; // maximum amplitude of data
for (double f : data) {
if (Math.abs(f) > maxAmp)
maxAmp = (float) Math.abs(f);
}
float yScalar = (yEnd - yStart) / (2 * maxAmp); // scalar for y values
// draw diagram frame
canvas.drawLine(xStart, yStart, xEnd, yStart, paint); // draw the upper line
canvas.drawLine(xStart, yMid, xEnd, yMid, paint); // draw the middle line
canvas.drawLine(xStart, yEnd, xEnd, yEnd, paint); // draw the lower line
// calculate and draw sample values
float x, y;
graph.reset();
graph.moveTo(xStart, yMid);
for (int j = 0; j < data.length; j++) {
x = xStart + (j * (xEnd - xStart) / data.length);
y = yMid + ((float) data[j] * yScalar);
graph.lineTo(x, y);
}
canvas.drawPath(graph, paint);
// set text
canvas.drawText(-maxAmp + " g", xStart, yStart - 4, paint); // draw upper Y value
canvas.drawText(maxAmp + " g", xStart, yEnd + 12, paint); // draw lower Y value
}
}

编辑:添加了在屏幕上显示图表的代码。我希望我这边不会出现复制意大利面错误。

编辑2:所以我设法调试每个线程的消息队列(MQ)。当测量运行时,每个 MQ 都是空的。我的问题发生后,主线程的 MQ 是唯一有消息的。 The first message似乎是一条空消息并导致无响应,但我不确定。每次点击屏幕时,接下来的消息总是成对出现——“PerformClick”和“UnsetPressedState”。

最佳答案

解决了。问题是我的 drawGraph(double[] data) 实现中的 invalidate() 调用。由于我是从另一个线程调用它,所以我必须使用 postInvalidate() 来代替。

关于java - 多线程时 onClick 随机不被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59881870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com