Cómo tomar una instantánea de la aplicación de pantalla no sólo en Android con código
He desarrollado la aplicación que toma la captura de pantalla. Pero sólo toma una instantánea de la aplicación. Quiero tomar una instantánea de la aplicación. He investigado las respuestas pero no encuentro respuesta todavía. Aquí está mi código.
View view = getWindow().getDecorView().getRootView(); view.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); view.setDrawingCacheEnabled(false); saveImageToAppFolder(bitmap);
SaveImagetoAppFolder es la función que guarda la imagen en la carpeta de la aplicación. Eso no es problema. ¿Hay de todos modos tomar instantánea de la pantalla?
- Pantalla de bloqueo de Android
- ¿Cómo diferenciar el diseño para 480 * 800 y 480 * 854 resoluciones de pantalla en android?
- Androide ¿Cómo estirar las filas en el gridview para llenar la pantalla?
- Android cómo dividir entre dos textview el ancho completo de pantalla exactamente cincuenta por ciento cincuenta?
- Android: ¿Cómo puede hacer PreferenceScreen personalizado?
- Apoyo a las dos orientaciones del paisaje en Honeycomb
- El selector de inicio de Android / lanzador no muestra la opción "usar de forma predeterminada para esta acción"
- Android: apagar la pantalla cuando está cerca de la cara
- ¿Reduce Android la velocidad de descarga cuando se apaga la pantalla?
- Tamaños de imagen de Android
- Android Desactivar la pantalla
- ¿Cómo puedo tomar una captura de pantalla de un video, en android
- Tamaños extraíbles de los androides cambia en la pantalla al leer la imagen del archivo
Para tomar una captura de pantalla de la pantalla del dispositivo, Sólo si tiene una llamada root el binario screencap como:
Process sh = Runtime.getRuntime().exec("su", null,null); OutputStream os = sh.getOutputStream(); os.write(("/system/bin/screencap -p " + Environment.getExternalStorageDirectory()+ "/img.png").getBytes("ASCII")); os.flush(); os.close(); sh.waitFor()
Y para cargar ese archivo en un mapa de bits, utilice
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(path, options); } public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; }
No sé su código en saveImageToAppFolder es lo que pero usted puede intentar esto:
Nota: necesitas configurar el fondo de tu aplicación / actividad como transparente (100%).
//your code below is extractly View view = getWindow().getDecorView().getRootView(); view.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); view.setDrawingCacheEnabled(false); //try my code for save image file to storage File imgFile = new File(imgPath); FileOutputStream os = new FileOutputStream(imageFile); int imgQuality = 100; bitmap.compress(Bitmap.CompressFormat.JPEG, imgQuality , os); os.flush(); os.close();
Código para establecer un fondo transparente:
// primero: crea el tema xml abajo para transparente
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="Theme.Transparent" parent="android:Theme"> <item name="android:windowIsTranslucent">true</item> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowContentOverlay">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsFloating">true</item> <item name="android:backgroundDimEnabled">false</item> </style> </resources>
Después de establecer de esta manera:
<activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent"> </activity>
Nota: puede red más detalles de aquí url: ¿Cómo puedo crear una actividad transparente en Android?
Aquí cómo puede capturar la pantalla y guardarla en su almacenamiento
Dar permisos para crear archivos en almacenamiento externo
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Y este es el código para la actividad.
private void takeScreenshot() { Date now = new Date(); android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now); try { // image naming and path to include sd card appending name you choose for file String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg"; // create bitmap screen capture View v1 = getWindow().getDecorView().getRootView(); v1.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache()); v1.setDrawingCacheEnabled(false); File imageFile = new File(mPath); FileOutputStream outputStream = new FileOutputStream(imageFile); int quality = 100; bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream); outputStream.flush(); outputStream.close(); openScreenshot(imageFile); } catch (Throwable e) { // Several error may come out with file handling or OOM e.printStackTrace(); }
}
Así es como puede capturar la pantalla.