I've got following piece of code:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
TextureView textureView = (TextureView) findViewById(R.id.texture);
if (textureView != null) {
try {
Log.i("MainActivity", "Read start");
String str = readQr(textureView.getBitmap());
if (str != null)
Log.i("MainActivity", str);
else Log.i("MainActivity", "No QR Code found.");
} catch (NotFoundException ex) {
Log.i("MainActivity", "No QR Code found.");
} catch (ChecksumException | FormatException e) {
e.printStackTrace();
}
}
}
}, 0, 250);
It should check for a QR code in the TextureView
four times a second. The calculation takes a bit less than one second. The problem is, that the timer opens only one thread, which blocks itself => The task gets run only around one time a second.
According to this comment scheduleAtFixedRate
should do the trick... But it does not, it behaves exactly like schedule
in my situation.
What would be the best option to achieve what I want?
EDIT: I replaced the Timer by a ScheduledExecutorService
, as suggested in the comments, but it still results in the exactly same behaviour.
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); // I know it's too much, I just tried using 10 Threads because 4 did still not work.
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
final TextureView textureView = (TextureView) findViewById(R.id.texture);
if (textureView != null) {
try {
Log.i("MainActivity", "Read start");
String str = readQr(textureView.getBitmap());
if (str != null)
Log.i("MainActivity", str);
else Log.i("MainActivity", "No QR Code found.");
Log.i("MainActivity", "Read end");
} catch (NotFoundException ex) {
Log.i("MainActivity", "No QR Code found.");
Log.i("MainActivity", "Read end");
} catch (ChecksumException | FormatException e) {
e.printStackTrace();
Log.i("MainActivity", "Read end");
}
}
}
}, 0, 250, TimeUnit.MILLISECONDS);