【发布时间】:2015-07-23 06:27:53
【问题描述】:
我要写一个服务在后台做截图,所以我应该使用服务来做。在这些代码中,我无法创建位图,因为我无法获取宽度和高度
@Override
public void onCreate() {
super.onCreate();
try {
mView = new LinearLayout(this);
mView.setBackgroundColor(0);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
0 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
PixelFormat.TRANSLUCENT);
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mView, params);
//all return 0
int w = mView.getWidth();
int h = mView.getHeight();
w = mView.getMeasuredWidth();
h = mView.getMeasuredHeight();
mView.measure(View.MeasureSpec.makeMeasureSpec(
View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
mView.layout(0, 0, mView.getMeasuredWidth(),
mView.getMeasuredHeight());
mView.setDrawingCacheEnabled(true);
mView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(mView.getMeasuredWidth(),
mView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
int height = bitmap.getHeight();
canvas.drawBitmap(bitmap, 0, height, paint);
mView.draw(canvas);
if (bitmap != null) {
try {
String filePath = Environment.getExternalStorageDirectory()
.toString();
OutputStream out = null;
File file = new File(filePath, "/mViewScreenShot.png");
Log.v("0",file.getPath());
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 50, out);
out.flush();
out.close();
bitmap.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
}
catch(Exception e)
{
stopSelf();
}
stopSelf();
}
我尝试了getWidth和getMeasuredWidth,它们也返回0
int w = mView.getWidth();
int h = mView.getHeight();
w = mView.getMeasuredWidth();
h = mView.getMeasuredHeight();
而且我在getMeasuredWidth和getMeasuredHeight之前也试过这个,还是不行。
mView.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED)
【问题讨论】:
-
查看link
标签: android android-layout android-service android-view android-windowmanager