public class MainActivity extends Activity {
private static final String SCREENSHOT_FILE_NAME_TEMPLATE = "Screenshot%s.jpg";
private static final String SCREENSHOT_FILE_PATH_TEMPLATE = "%s/%s/%s";
private static final String SCREENSHOTS_DIR_NAME = "aaaaaaaaa";
private static final String TAG = "MainActivity";
private TextView tv;
private ImageView im;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
im = (ImageView) findViewById(R.id.im);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
activityScreensho(MainActivity.this);
}
});
}
private Bitmap activityScreensho(Activity activity) {
// view
View view = activity.getWindow().getDecorView();
// 当前窗口保存信息
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
// 状态栏高度
Rect rect = new Rect();
view.getWindowVisibleDisplayFrame(rect);
int statH = rect.top;
WindowManager windowManager = activity.getWindowManager();
// 屏幕高宽
DisplayMetrics dMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(dMetrics);
int width = dMetrics.widthPixels;
// view绘制区域
Rect outRect2 = new Rect();
activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getDrawingRect(outRect2);
int viewHeight = outRect2.height(); // view绘制界面的高度
// 去掉状态栏
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, statH, width, viewHeight);
// 销毁缓存信息
view.destroyDrawingCache();
view.setDrawingCacheEnabled(false);
im.setImageBitmap(bitmap);
saveSD(bitmap);
return bitmap;
}
private String saveSD(Bitmap bitmap) {
// 判断sd卡是否存在
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// 文件名
long systemTime = System.currentTimeMillis();
String imageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(systemTime));
String mFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
// 文件全名
String mstrRootPath = Environment.getExternalStorageDirectory().toString();
File dir = new File(mstrRootPath + File.separator + SCREENSHOTS_DIR_NAME);
// 判断文件是否存在,不存在则创建
if (!dir.exists()) {
dir.mkdirs();
}
String mFilePath = String.format(SCREENSHOT_FILE_PATH_TEMPLATE, mstrRootPath, SCREENSHOTS_DIR_NAME,
mFileName);
Log.i(TAG, "file path:" + mFilePath);
File file = new File(mFilePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i(TAG, "file path:" + file.getAbsolutePath());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
// 第一参数是图片格式,第二参数是图片质量,第三参数是输出流
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return mFilePath;
}
return null;
}
}