簡體   English   中英

截取屏幕截圖 - 后台服務

[英]Take a screenshot - Background Service

我正在嘗試使用后台服務截取屏幕截圖。 這項服務就像一個Facebook聊天室,但我希望它在我點擊時截取屏幕截圖。

預覽圖片

我已經開發了一些代碼,但它不起作用。 我試過的最后一次是:

private void takeScreenshot() {
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStorageDirectory().toString() + "/capture/" + now + ".jpg";

        // create bitmap screen capture
        Bitmap bitmap;
        View v1 = chatHead.getRootView();
        v1.setDrawingCacheEnabled(true);
        bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        OutputStream fout = null;
        File imageFile = new File(mPath);

        try {
            fout = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
            fout.flush();
            fout.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

但是截圖到我的按鈕而不是屏幕。

我知道問題在這里:

View v1 = chatHead.getRootView();

但我不知道如何解決它。 誰能幫我?

我實際上使用的是Android Studio 2.2.2和Android 4.0或更高版本。

要獲取包含不屬於您的應用的視圖的屏幕截圖,您需要使用MediaProjectionManager

請參閱如何在Android應用程序中使用狀態欄內容拍攝屏幕截圖?

對於Lollipop及以上版本,您可以使用Google的MediaProjection API來截取屏幕截圖,但您需要征得用戶的許可。

您可以使用MediaProjection Here找到示例屏幕捕獲代碼

對於少於Lollipop的設備,您需要root權限才能獲得它。

使用Android的MediaProjection API中提供的MediaProjectionManager#createScreenCaptureIntent 您現在正在做的是獲取chatHead的根視圖的信息,而不是設備整個屏幕上顯示的信息,包括頂部的狀態欄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM