I would like to get two bitmaps of screen. Problem is, TextView
or TextClock
contains values from first call of getDrawingCache()
. Values for TextView
or TextClock
are not refreshed in new Bitmap
after second call of getDrawingCache()
.
Work on Nexus 5 (second bitmap contains correct time from TextClock
).
On many other devices not work. E.g.: Huawei Honor 4C.
minSdkVersion 21
targetSdkVersion 25
compileSdkVersion 25
TextClock
automatically changes value. Not working even though i call setText()
method on TextView
.
Where is problem?
Test:
Create simple layout with: TextClock
and run this code in UI Thread:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("TAG", Thread.currentThread().getName());
try {
Bitmap bitmapScreen = getBitmapOfScreen();
//File f = new File("/storage/sdcard1", "tmp.jpg"); //Huawei
File f = new File("/storage/emulated/0", "tmp.jpg"); //Nexus 5
FileOutputStream fis = new FileOutputStream(f);
bitmapScreen.compress(Bitmap.CompressFormat.JPEG, 100, fis);
fis.flush();
fis.close();
bitmapScreen.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 5000);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("TAG", Thread.currentThread().getName());
try {
Bitmap bitmapScreen = getBitmapOfScreen();
//File f = new File("/storage/sdcard1", "tmp2.jpg"); //Huawei
File f = new File("/storage/emulated/0", "tmp2.jpg"); //Nexus 5
FileOutputStream fis = new FileOutputStream(f);
bitmapScreen.compress(Bitmap.CompressFormat.JPEG, 100, fis);
fis.flush();
fis.close();
bitmapScreen.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 10000);
/** Must be called in UI thread.*/
public Bitmap getBitmapOfScreen() throws Exception {
final View v1 = getWindow().getDecorView().getRootView();
v1.destroyDrawingCache();
v1.setDrawingCacheEnabled(true);
v1.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
bitmap.setHasAlpha(true); //important for PNG
v1.setDrawingCacheEnabled(false);
return bitmap;
}
Solved.
Missing called
invalidate()
on view. For now, when i callinvalidate()
onTextClock
beforegetBitmapOfScreen()
call, value is correct in bitmap.