I'm trying to capture multiple screenshots at regular interval using Timer
.
But; the images added to the ArrayList
are all last images. So I'm getting similar images throughout the list.
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
System.out.println("executing timer "+index);
View rootView = findViewById(R.id.relative_inside);
rootView.setDrawingCacheEnabled(true);
rootView.buildDrawingCache();
Bitmap drawingCache = rootView.getDrawingCache();
list.add(drawingCache);
System.out.println("image added to list "+index);
index++;
}
});
}
};
I'm calling timer with the below code :-
timer.schedule(timerTask, 0, 80);
but, while extracting the images from List, I'm getting similar images. Could anyone point out my mistake?
It's because getDrawingCache()
returns the same instance of Bitmap
, just with updated pixel data. Therefore, all list items already added are getting updated whenever cache bitmap change.
You would have to create new instance of Bitmap every time you read cache and then add to the list.
For example:
Bitmap drawingCache = Bitmap.createBitmap(rootView.getDrawingCache());
list.add(drawingCache);
Please note that bitmaps consume a lot of memory and it's very easy to get OutOfMemoryError
.
Additionally, you could move this part:
View rootView = findViewById(R.id.relative_inside);
rootView.setDrawingCacheEnabled(true);
rootView.buildDrawingCache();
to TimerTask creation phase e.g. inside constructor. Then you can refer to your view by instance variable. Going through view hierarchy is time consuming.