Jak programowo zrobić zrzut ekranu na Androida?

Jak zrobić zrzut ekranu wybranego obszaru telefonu-ekran nie przez żaden program, ale z kodu?

Author: Cœur, 2010-04-18

24 answers

Oto kod, który pozwolił na zapisanie mojego zrzutu ekranu na karcie SD i użycie go później, niezależnie od twoich potrzeb: {]}

Najpierw musisz dodać odpowiednie uprawnienia, aby zapisać plik:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

A to jest kod (uruchamiany w aktywności):

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 DOM
        e.printStackTrace();
    }
}

I tak możesz otworzyć ostatnio wygenerowany obraz:

private void openScreenshot(File imageFile) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(imageFile);
    intent.setDataAndType(uri, "image/*");
    startActivity(intent);
}

Jeśli chcesz użyć tego w widoku fragment, użyj:

View v1 = getActivity().getWindow().getDecorView().getRootView();

Zamiast

View v1 = getWindow().getDecorView().getRootView();

On takeScreenshot () function

Uwaga :

To rozwiązanie nie działa, jeśli okno dialogowe zawiera widok powierzchni. Aby uzyskać szczegółowe informacje, Sprawdź odpowiedź na następujące pytanie:

Android Take Screenshot z widoku powierzchni pokazuje czarny ekran

 468
Author: taraloca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-03 13:10:14

Wywołaj tę metodę, przechodząc do zewnętrznej grupy widoków, z której chcesz zrobić zrzut ekranu:

public Bitmap screenShot(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
            view.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}
 142
Author: JustinMorris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-19 17:08:12

Uwaga: działa tylko dla zrootowanego telefonu

Programowo można uruchomić adb shell /system/bin/screencap -p /sdcard/img.png Jak poniżej

Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();    

Następnie przeczytaj img.png jako Bitmap i użyj jako swoje życzenie.

 42
Author: Viswanath Lekshmanan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-13 01:39:16

Brak uprawnień roota lub nie jest wymagane Duże kodowanie dla tej metody.


W powłoce adb za pomocą poniższego polecenia można wykonać zrzut ekranu.

input keyevent 120

To polecenie nie wymaga żadnych uprawnień roota, więc to samo można wykonać z kodu java aplikacji android również.

Process process;
process = Runtime.getRuntime().exec("input keyevent 120");

Więcej o kodzie keyevent w Androidzie zobacz http://developer.android.com/reference/android/view/KeyEvent.html

Tutaj użyliśmy. KEYCODE_SYSRQ jego wartość to 120 i służy do żądania systemowego / klucza Print Screen.


Jak powiedział CJBS, obraz wyjściowy zostanie zapisany w / sdcard / Pictures / Screenshots

 26
Author: Jeegar Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-04 13:00:35

ODPOWIEDŹ Mualig jest bardzo dobra, ale miałem ten sam problem, który opisuje Ewoks, nie rozumiem tła. Więc czasami jest wystarczająco dobry, a czasami dostaję czarny tekst na czarnym tle (w zależności od tematu).

To rozwiązanie jest w dużej mierze oparte na kodzie Mualig i kodzie, który znalazłem w Robotium. Odrzucam użycie cache ' u rysowania, wywołując bezpośrednio metodę draw. Zanim to zrobię, postaram się narysować tło z bieżącej aktywności, aby najpierw je narysować.
// Some constants
final static String SCREENSHOTS_LOCATIONS = Environment.getExternalStorageDirectory().toString() + "/screenshots/";

// Get device dimmensions
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);

// Get root view
View view = mCurrentUrlMask.getRootView();

// Create the bitmap to use to draw the screenshot
final Bitmap bitmap = Bitmap.createBitmap(size.x, size.y, Bitmap.Config.ARGB_4444);
final Canvas canvas = new Canvas(bitmap);

// Get current theme to know which background to use
final Activity activity = getCurrentActivity();
final Theme theme = activity.getTheme();
final TypedArray ta = theme
    .obtainStyledAttributes(new int[] { android.R.attr.windowBackground });
final int res = ta.getResourceId(0, 0);
final Drawable background = activity.getResources().getDrawable(res);

// Draw background
background.draw(canvas);

// Draw views
view.draw(canvas);

// Save the screenshot to the file system
FileOutputStream fos = null;
try {
    final File sddir = new File(SCREENSHOTS_LOCATIONS);
    if (!sddir.exists()) {
        sddir.mkdirs();
    }
    fos = new FileOutputStream(SCREENSHOTS_LOCATIONS
            + System.currentTimeMillis() + ".jpg");
    if (fos != null) {
        if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
            Log.d(LOGTAG, "Compress/Write failed");
        }
        fos.flush();
        fos.close();
    }

} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
 18
Author: xamar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-25 11:37:33
private void captureScreen() {
    View v = getWindow().getDecorView().getRootView();
    v.setDrawingCacheEnabled(true);
    Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false);
    try {
        FileOutputStream fos = new FileOutputStream(new File(Environment
                .getExternalStorageDirectory().toString(), "SCREEN"
                + System.currentTimeMillis() + ".png"));
        bmp.compress(CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Dodaj pozwolenie w manifeście

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Do obsługiMarshmallow lub starszych wersji, proszę dodać poniższy kod w metodzie activity onCreate

ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},00);
 18
Author: Crazy Coder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-05 12:02:44

Jako odniesienie, jednym ze sposobów przechwytywania ekranu (a nie tylko aktywności aplikacji) jest przechwycenie bufora ramki (device /dev/graphics/fb0). Aby to zrobić, musisz mieć uprawnienia roota lub Twoja aplikacja musi być aplikacją z Signature permissions ("uprawnienie, które System przyznaje tylko wtedy, gdy wnioskująca aplikacja jest podpisana z tym samym certyfikatem, co aplikacja, która zadeklarowała uprawnienie") - co jest bardzo mało prawdopodobne, chyba że skompilowałeś własne ROM.

Każde przechwytywanie bufora ramki, z kilku testowanych urządzeń, zawierało dokładnie jeden zrzut ekranu. Ludzie zgłaszali, że zawiera więcej, myślę, że zależy to od rozmiaru ramki/wyświetlacza.

Próbowałem odczytać bufor ramki w sposób ciągły, ale wydaje się, że zwraca on stałą ilość odczytanych bajtów. W moim przypadku jest to (3 410 432) bajtów, co wystarczy, aby zapisać ramkę wyświetlacza 854*480 rgba (3 279 360 bajtów). Tak, ramka, w binarnym, wyprowadzona z fb0 jest RGBA w moim urządzeniu. Będzie to najprawdopodobniej zależeć od urządzenia do urządzenia. To będzie dla Ciebie ważne, aby to odkodować=)

W moim urządzeniu /dev/graphics/fb0 uprawnienia są tak, że tylko root i użytkownicy z grupy graphics mogą odczytywać fb0.

Grafika jest ograniczoną grupą, więc prawdopodobnie uzyskasz dostęp do fb0 tylko z zakorzenionym telefonem za pomocą polecenia su.

Aplikacje na Androida mają user id (uid) = app_##i group id (guid) = app_## .

Adb shell mA uid = shell i guid = shell , który ma znacznie więcej uprawnień niż aplikacja. Możesz sprawdzić te uprawnienia w /system/permissions / platform.xml

Oznacza to, że będzie można odczytać fb0 w powłoce adb bez roota, ale nie będzie można odczytać go w aplikacji bez roota.

Również, dając uprawnienia READ_FRAME_BUFFER i / lub ACCESS_SURFACE_FLINGER na AndroidManifest.xml nie zrobi nic dla zwykłej aplikacji, ponieważ te działa tylko dla aplikacji " signature ".

Zobacz też wątek zamknięty Po Więcej Szczegółów.

 17
Author: Rui Marques,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:48

Moje rozwiązanie to:

public static Bitmap loadBitmapFromView(Context context, View v) {
    DisplayMetrics dm = context.getResources().getDisplayMetrics(); 
    v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
            v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(returnedBitmap);
    v.draw(c);

    return returnedBitmap;
}

I

public void takeScreen() {
    Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
    String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
    File imageFile = new File(mPath);
    OutputStream fout = null;
    try {
        fout = new FileOutputStream(imageFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
        fout.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        fout.close();
    }
}

Obrazy są zapisywane w folderze pamięci zewnętrznej.

 16
Author: validcat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-14 13:11:10

Możesz wypróbować następującą bibliotekę: http://code.google.com/p/android-screenshot-library/ Android Screenshot Library (ASL) umożliwia programowo przechwytywanie zrzutów ekranu z urządzeń z systemem Android bez konieczności posiadania uprawnień dostępu roota. Zamiast tego, ASL wykorzystuje natywną usługę działającą w tle, uruchamianą za pomocą Android Debug Bridge (ADB) raz na rozruch urządzenia.

 11
Author: Kuba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-07 13:53:11

Na podstawie odpowiedzi @JustinMorris powyżej i @ NiravDangi tutaj https://stackoverflow.com/a/8504958/2232148 musimy wziąć tło i pierwszy plan widoku i złożyć je w następujący sposób:

public static Bitmap takeScreenshot(View view, Bitmap.Config quality) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), quality);
    Canvas canvas = new Canvas(bitmap);

    Drawable backgroundDrawable = view.getBackground();
    if (backgroundDrawable != null) {
        backgroundDrawable.draw(canvas);
    } else {
        canvas.drawColor(Color.WHITE);
    }
    view.draw(canvas);

    return bitmap;
}

Parametr jakości przyjmuje stałą bitmapy.Config, zazwyczaj Bitmap.Config.RGB_565 lub Bitmap.Config.ARGB_8888.

 11
Author: Oliver Hausler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:32
public class ScreenShotActivity extends Activity{

private RelativeLayout relativeLayout;
private Bitmap myBitmap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    relativeLayout = (RelativeLayout)findViewById(R.id.relative1);
    relativeLayout.post(new Runnable() {
        public void run() {

            //take screenshot
            myBitmap = captureScreen(relativeLayout);

            Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();

            try {
                if(myBitmap!=null){
                    //save image to SD card
                    saveImage(myBitmap);
                }
                Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

}

public static Bitmap captureScreen(View v) {

    Bitmap screenshot = null;
    try {

        if(v!=null) {

            screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(screenshot);
            v.draw(canvas);
        }

    }catch (Exception e){
        Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
    }

    return screenshot;
}

public static void saveImage(Bitmap bitmap) throws IOException{

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
    File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
    fo.close();
}

}

ADD PERMISSION

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 8
Author: Vaishali Sutariya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-21 12:01:28

Możesz spróbować zrobić coś takiego,

Uzyskanie pamięci podręcznej bitmapy z układu lub widoku, wykonując coś takiego Najpierw musisz setDrawingCacheEnabled do układu (linearlayout lub relativelayout, lub widoku)

Then

Bitmap bm = layout.getDrawingCache()

Potem robisz co chcesz z bitmapą. Albo zamieniając go w plik obrazu, albo wysyłając uri bitmapy w inne miejsce.

 7
Author: Kevin Tan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-06 06:01:15

Short way is

FrameLayout layDraw = (FrameLayout) findViewById(R.id.layDraw); /*Your root view to be part of screenshot*/
layDraw.buildDrawingCache();
Bitmap bmp = layDraw.getDrawingCache();
 7
Author: Chintan Khetiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-12 07:42:24

Dla tych, którzy chcą przechwycić GLSurfaceView, metoda getDrawingCache lub drawing to canvas nie będzie działać.

Musisz przeczytać zawartość bufora ramki OpenGL po renderowaniu ramki. Tu jest dobra odpowiedź

 6
Author: rockeye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:45

Stworzyłem prostą bibliotekę, która wykonuje zrzut ekranu z View i albo daje obiekt bitmapowy, albo zapisuje go bezpośrednio do dowolnej ścieżki

Https://github.com/abdallahalaraby/Blink

 6
Author: Abdallah Alaraby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-25 22:01:00

Większość odpowiedzi na to pytanie używa metody rysowania Canvas lub metody drawing cache. Jednak View.setDrawingCache() metoda jest przestarzała w API 28. Obecnie zalecanym API do robienia zrzutów ekranu jest PixelCopy klasa dostępna z API 24 (ale metody akceptujące parametr Window są dostępne z API 26 == Android 8.0 Oreo). Oto przykładowy kod Kotlina do pobrania Bitmap:

@RequiresApi(Build.VERSION_CODES.O)
fun saveScreenshot(view: View) {
    val window = (view.context as Activity).window
    if (window != null) {
        val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
        val locationOfViewInWindow = IntArray(2)
        view.getLocationInWindow(locationOfViewInWindow)
        try {
            PixelCopy.request(window, Rect(locationOfViewInWindow[0], locationOfViewInWindow[1], locationOfViewInWindow[0] + view.width, locationOfViewInWindow[1] + view.height), bitmap, { copyResult ->
                if (copyResult == PixelCopy.SUCCESS) {
                    saveBitmap(bitmap)
                }
                // possible to handle other result codes ...
            }, Handler())
        } catch (e: IllegalArgumentException) {
            // PixelCopy may throw IllegalArgumentException, make sure to handle it
        }
    }
}
 5
Author: Miloš Černilovský,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-16 11:53:04

Jeśli chcesz zrobić zrzut ekranu z fragment, wykonaj następujące czynności:

  1. Override onCreateView():

             @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                // Inflate the layout for this fragment
                View view = inflater.inflate(R.layout.fragment_one, container, false);
                mView = view;
            }
    
  2. Logika robienia zrzutu ekranu:

     button.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         View view =  mView.findViewById(R.id.scrollView1);
          shareScreenShotM(view, (NestedScrollView) view); 
     }
    
  3. Metoda shareScreenShotM)():

    public void shareScreenShotM(View view, NestedScrollView scrollView){
    
         bm = takeScreenShot(view,scrollView);  //method to take screenshot
        File file = savePic(bm);  // method to save screenshot in phone.
        }
    
  4. Metoda takeScreenShot ():

             public Bitmap takeScreenShot(View u, NestedScrollView z){
    
                u.setDrawingCacheEnabled(true);
                int totalHeight = z.getChildAt(0).getHeight();
                int totalWidth = z.getChildAt(0).getWidth();
    
                Log.d("yoheight",""+ totalHeight);
                Log.d("yowidth",""+ totalWidth);
                u.layout(0, 0, totalWidth, totalHeight);
                u.buildDrawingCache();
                Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
                u.setDrawingCacheEnabled(false);
                u.destroyDrawingCache();
                 return b;
            }
    
  5. Metoda savePic ():

     public static File savePic(Bitmap bm){
    
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
             File sdCardDirectory =  new File(Environment.getExternalStorageDirectory() + "/Foldername");
    
           if (!sdCardDirectory.exists()) {
                sdCardDirectory.mkdirs();
          }
           //  File file = new File(dir, fileName);
          try {
             file = new File(sdCardDirectory, Calendar.getInstance()
                .getTimeInMillis() + ".jpg");
            file.createNewFile();
            new FileOutputStream(file).write(bytes.toByteArray());
            Log.d("Fabsolute", "File Saved::--->" + file.getAbsolutePath());
             Log.d("Sabsolute", "File Saved::--->" + sdCardDirectory.getAbsolutePath());
         } catch (IOException e) {
              e.printStackTrace();
          }
         return file;
       }
    

Do aktywności możesz po prostu użyć View v1 = getWindow().getDecorView().getRootView(); zamiast mView

 4
Author: Parsania Hardik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-30 06:25:38

Przedłużam odpowiedź taraloca. Musisz dodać następujące linie, aby to działało. zmieniłem nazwę obrazu na statyczną. Upewnij się, że używasz zmiennej timestamp taraloca incase potrzebujesz dynamicznej nazwy obrazu.

    // Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

private void verifyStoragePermissions() {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
    }else{
        takeScreenshot();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        if (requestCode == REQUEST_EXTERNAL_STORAGE) {
            takeScreenshot();
        }
    }
}
I w AndroidManifest.plik xml musi zawierać następujące wpisy:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 4
Author: TechBee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-30 15:39:23

Dla Pełnego Przewijania Strony Zrzut Ekranu

Jeśli chcesz zrobić zrzut ekranu z pełnym widokiem (który zawiera widok przewijania lub tak), sprawdź w tej bibliotece

Https://github.com/peter1492/LongScreenshot

Wystarczy zaimportować Gradel i utworzyć obiekt BigScreenshot

BigScreenshot longScreenshot = new BigScreenshot(this, x, y);

Odpowiedź zwrotna zostanie odebrana z bitmapą zrzutów ekranu wykonaną podczas automatycznego przewijania Grupa widoku ekranu i na końcu zmontowane razem.

@Override public void getScreenshot(Bitmap bitmap) {}

Które można zapisać w galerii lub ewentualnie użyć ich po

 3
Author: Peter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-20 05:04:24

Tylko dla aplikacji systemowych!

Process process;
process = Runtime.getRuntime().exec("screencap -p " + outputPath);
process.waitFor();

Uwaga: aplikacje systemowe nie muszą uruchamiać "su", aby wykonać to polecenie.

 2
Author: GilCol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-04 15:13:35

Widok parametru jest głównym obiektem układu.

public static Bitmap screenShot(View view) {
                    Bitmap bitmap = null;
                    if (view.getWidth() > 0 && view.getHeight() > 0) {
                        bitmap = Bitmap.createBitmap(view.getWidth(),
                                view.getHeight(), Bitmap.Config.ARGB_8888);
                        Canvas canvas = new Canvas(bitmap);
                        view.draw(canvas);
                    }
                    return bitmap;
                }
 2
Author: Anil Singhania,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-29 07:36:38

Zrób zrzut ekranu widoku w systemie android.

public static Bitmap getViewBitmap(View v) {
    v.clearFocus();
    v.setPressed(false);

    boolean willNotCache = v.willNotCacheDrawing();
    v.setWillNotCacheDrawing(false);

    int color = v.getDrawingCacheBackgroundColor();
    v.setDrawingCacheBackgroundColor(0);

    if (color != 0) {
        v.destroyDrawingCache();
    }
    v.buildDrawingCache();
    Bitmap cacheBitmap = v.getDrawingCache();
    if (cacheBitmap == null) {
        return null;
    }

    Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

    v.destroyDrawingCache();
    v.setWillNotCacheDrawing(willNotCache);
    v.setDrawingCacheBackgroundColor(color);

    return bitmap;
}
 1
Author: Mohit Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-06 08:15:42

Z Androida 11 (poziom API 30) możesz zrobić zrzut ekranu za pomocą usługi dostępności:

TakeScreenshot - wykonuje zrzut ekranu określonego wyświetlacza i zwraca go za pośrednictwem usługi AccessibilityService.ScreenshotResult.

 1
Author: zvi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-08-03 06:35:59

Jeśli chcesz uchwycić widok lub układ, taki jak RelativeLayout lub LinearLayout itp. wystarczy użyć kodu:

LinearLayout llMain = (LinearLayout) findViewById(R.id.linearlayoutMain);
Bitmap bm = loadBitmapFromView(llMain);

Teraz możesz zapisać tę bitmapę w pamięci urządzenia przez:

FileOutputStream outStream = null;
File f=new File(Environment.getExternalStorageDirectory()+"/Screen Shots/");
f.mkdir();
String extStorageDirectory = f.toString();
File file = new File(extStorageDirectory, "my new screen shot");
pathOfImage = file.getAbsolutePath();
try {
    outStream = new FileOutputStream(file);
    bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
    Toast.makeText(getApplicationContext(), "Saved at "+f.getAbsolutePath(), Toast.LENGTH_LONG).show();
    addImageGallery(file);
    //mail.setEnabled(true);
    flag=true;
} catch (FileNotFoundException e) {e.printStackTrace();}
try {
    outStream.flush();
    outStream.close();
} catch (IOException e) {e.printStackTrace();}
 -2
Author: Akshay Paliwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-05 11:10:48