摘要:Android - Screen Capture
我要做一個,按按鈕後,能夠將現有的螢幕截取下來,
網路已有文章解決這個問題
https://androidresearch.wordpress.com/2013/01/06/taking-a-screenshot-of-current-activity-in-android/
實際實作後,覺得缺少一個部份,除了截取螢幕下來以外,為了讓我們能夠在Gallery能看得見,
所以還需要傳送檔案位置給Gallery,讓他知道,以便我們能夠Gallery能查看結果。
以下是實作的程式碼。
public void initScreenCapture() {
Button mBtnScreenCapture;
mBtnScreenCapture = (Button)this.findViewById(R.id.btn_screen_capture);
mBtnScreenCapture.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
}
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
String fileName = sdf.format(new Date());
File imagePath = new File(getAblumDir() + "/screenshot_"+fileName+".png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
sendBroadcaseAddPhotoToGallery(this,imagePath.getAbsolutePath());
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
public static File getAblumDir() {
File albumDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "screenCapturemDemo");
// Create the storage directory if it does not exist.
if (! albumDir.exists()){
if (!albumDir.mkdirs()) {
// Log.e(TAG, "PiActivity: App album directory failed to create !!");
}
}
return albumDir;
}
/**
* Add photo to gallery
* @param path
*/
public void sendBroadcaseAddPhotoToGallery(Context ctx,String path) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(new File(path));
mediaScanIntent.setData(contentUri);
ctx.sendBroadcast(mediaScanIntent);
}