我想获得两个屏幕位图。问题是,TextView
或TextClock
包含来自第一次调用的值getDrawingCache()
。在第二次TextView
调用.TextClock
Bitmap
getDrawingCache()
在 Nexus 5 上工作(第二个位图包含正确的时间TextClock
)。
在许多其他设备上不起作用。例如:华为荣耀 4C。
minSdkVersion 21
targetSdkVersion 25
compileSdkVersion 25
TextClock
自动改变值。即使我调用setText()
方法也无法正常工作TextView
。
问题出在哪里?
测试:
使用:创建简单布局TextClock
并在 UI 线程中运行此代码:
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;
}