package com.liyoro.phonescreenshot;
import java.io.ByteArrayOutputStream;
import java.io.IOException;import android.os.Bundle;
import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.view.Display; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView;/**
* 手机截屏 * @author liyoro * * */ public class MainActivity extends Activity { private ImageView mImageView = null; private Button mButton = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);mButton = (Button)findViewById(R.id.button);
mImageView = (ImageView)findViewById(R.id.p_w_picpathview); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) {Bitmap mBitmap = Bytes2Bimap(getCurScreenPic(MainActivity.this));
mImageView.setImageBitmap(mBitmap); } }); }@Override
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; }public static byte[] getCurScreenPic(Activity activity) {
// 1.构建Bitmap WindowManager windowManager = activity.getWindowManager(); Display display = windowManager.getDefaultDisplay(); int w = display.getWidth(); int h = display.getHeight();Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
// 2.获取屏幕
View decorview = activity.getWindow().getDecorView(); decorview.setDrawingCacheEnabled(true); Bmp = decorview.getDrawingCache();ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bmp.compress(Bitmap.CompressFormat.PNG, 90, baos);
byte[] b = baos.toByteArray();
try {
baos.flush(); baos.close(); } catch (IOException e) { e.printStackTrace(); } return b; }private Bitmap Bytes2Bimap(byte[] b) {
if (b.length != 0) { return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } } }