Androidでプログラム的にスクリーンショットを撮るにはどうすればいいですか?質問する

Androidでプログラム的にスクリーンショットを撮るにはどうすればいいですか?質問する

プログラムではなくコードから、携帯電話の画面の選択した領域のスクリーンショットを撮るにはどうすればよいですか?

ベストアンサー1

以下は、スクリーンショットを SD カードに保存し、後から必要に応じて使用できるようにするコードです。

まず、ファイルを保存するための適切な権限を追加する必要があります。

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

これはコードです(アクティビティで実行されています):

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();
    }
}

最近生成された画像を開く方法は次のとおりです。

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);
}

これをフラグメント ビューで使用する場合は、次を使用します。

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

の代わりに

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

takeScreenshot()関数について

注記

このソリューションは、ダイアログにサーフェス ビューが含まれている場合には機能しません。詳細については、次の質問の回答を確認してください。

Android で Surface View のスクリーンショットを撮ると黒い画面が表示される

おすすめ記事