如何以编程方式在Android中截取对话框的屏幕截图?

时间:2016-03-07 13:00:40

标签: android

我有与Web Server交互的Android应用程序。当数据从手机发送到服务器时,有一些数据工作(10-20秒),之后我将结果返回到手机。并且我在2个选项的对话框中显示该结果。一个选择是" OK"这意味着用户可以使用结果并解除对话框。另一个选择是截取该结果的屏幕截图。当我按下这个按钮时,我没有得到对话框的图片,我得到了该对话框后面的布局图片。

enter image description here

我背后的代码是

//this method is called on onPostExecute of async task

public void recieveResult (final Activity act,String result){
    new AlertDialog.Builder(act)
            .setTitle("Data - status")
            .setMessage(result)
            .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
            .setPositiveButton("Save picture", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Bitmap bitmap = takeScreenshot(act);
                    saveBitmap(bitmap,act);
                    Toast.makeText(act,"Saved",Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                }
            })
            .show();
}

public Bitmap takeScreenshot(Activity act) {
    View rootView = act.findViewById(android.R.id.content).getRootView();
    rootView.setDrawingCacheEnabled(true);
    return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap,Activity act) {
    String timeStamp = new SimpleDateFormat("MMyyyydd_HHmmss").format(new Date());
    String imageFileName = "/screenshot_"+timeStamp+"_.png";
    File storage = Environment.getExternalStoragePublicDirectory("Screens");
    if (!storage.exists())
    {
        Toast.makeText(act, "Directory made", Toast.LENGTH_LONG).show();
        storage.mkdirs();
    }
    File imagePath = new File(storage.getPath() + imageFileName);
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}

我的图片结果只是没有对话框的屏幕。如何获取对话框的图片?

3 个答案:

答案 0 :(得分:0)

尝试获取Windows's decor view

然后在实现时获取其绘图缓存位图。

答案 1 :(得分:0)

对话框具有自己的窗口(不同表单活动的窗口),可以使用dialog.getWindow()方法获取对话框的窗口。

这是屏幕截图代码:

private AlertDialog dialog;

public void showDialog(View view) {
    dialog = new AlertDialog.Builder(this)
            .setTitle("Titel")
            .setMessage("some content")
            .setPositiveButton("Screenshot", (d, which) -> {
                Bitmap bitmap = screenshot(dialog);
                // you can save the bitmap or display in an ImageView
            }).create();
    dialog.show();
}

private Bitmap screenshot(Dialog dialog) {
    Window window = dialog.getWindow();
    View decorView = window.getDecorView();
    Bitmap bitmap = Bitmap.createBitmap(decorView.getWidth(), decorView.getHeight(), Bitmap.Config.ARGB_8888);
    decorView.draw(new Canvas(bitmap));
    return bitmap;
}

答案 2 :(得分:-1)

试试这段代码

 String picId=String.valueOf(nu);
                    String myfile="meter"+picId+".jpeg";

                    BitmapDrawable bitmapDrawable = null;
                    Toast.makeText(getActivity(),"success full store image gallery",Toast.LENGTH_SHORT).show();
                    Date now = new Date();
                    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

                    try {

                        File dir_image = new  File(Environment.getExternalStorageDirectory()+//<---
                                File.separator+"SoundMeter");  //23-1-16          //<---
                        dir_image.mkdirs();

                        // 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 = surfaceView.getRootView();
                        v1.setDrawingCacheEnabled(true);
                        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());

                       /* bitmapDrawable = new BitmapDrawable(bitmap);*/
                        v1.setDrawingCacheEnabled(false);
                       // File imageFile = new File(mPath);     //file path 23-1-16
                        File imageFile = new File(dir_image,myfile);

                        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();
                    }
                    btnCaptured1.setVisibility(View.VISIBLE);
                    btnCaptured.setVisibility(View.VISIBLE);
                    //btnCaptured.setBackgroundDrawable(bitmapDrawable);

                }
            });

        }
        else
        {
            Toast.makeText(getActivity().getApplicationContext(), "No Connection", Toast.LENGTH_LONG).show();

        }