Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 開發實作:螢幕截圖與郵件分享功能

編輯:Android 開發實例

無論是掌上 BI 報表工具還是行動辦公應用,幾乎都會需要「把當前畫面存成圖片並寄出去」這個功能:使用者看到一份報表、一張圖表,想直接截圖轉寄給同事,比口述或再截一次圖方便得多。

本文示範如何取得指定 Activity 的畫面、裁掉狀態列、存成 PNG 檔,再透過系統 Intent 分享出去。

實作流程

整個流程可以拆成四步:

  1. 取得要截圖的 View(通常是 DecorView,即整個視窗),開啟 DrawingCache 並強制繪製。
  2. 從 DrawingCache 取出 Bitmap,再用 Bitmap.createBitmap() 依狀態列高度裁掉頂部。
  3. 確認 SD 卡/外部儲存空間可用且空間足夠,把 Bitmap 以 PNG 格式壓縮寫檔。
  4. 組裝 ACTION_SEND Intent,把檔案以 URI 形式附上,交給系統挑選要開啟的 App。

一個容易踩到的小細節

在設定 Intent 的 MIME 類型時,email.setType("image/png") 與 email.setType("application/octet-stream") 都不會影響郵件本身的發送。但兩者的行為差異很明顯:使用 image/png 時,系統的分享選單會同時列出簡訊、彩信、郵件等所有能處理圖片的應用;而 application/octet-stream 則只會列出以「檔案附件」角度處理的程式。

因此,如果你希望使用者可以把截圖直接丟進簡訊或社群軟體,就用 image/png;如果只想限定為郵件附件,才考慮 application/octet-stream。

核心工具類別

package com.johnson.Screenshot;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.widget.Toast;

public class ScreenshotTools {

    /** 判斷 SD 卡可用所需的最小空間(KB) */
    public static long minSizeSDcard = 50;

    public static String filePath = Environment.getExternalStorageDirectory()
            + "/FJBICache";
    public static String fileName = "chart.png";
    public static String detailPath = filePath + File.separator + fileName;

    /** 呼叫系統程式寄送郵件 */
    private static void sendEmail(Context context, String[] to, String subject,
                                  String body, String path) {

        Intent email = new Intent(android.content.Intent.ACTION_SEND);

        if (to != null) {
            email.putExtra(android.content.Intent.EXTRA_EMAIL, to);
        }
        if (subject != null) {
            email.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
        }
        if (body != null) {
            email.putExtra(android.content.Intent.EXTRA_TEXT, body);
        }
        if (path != null) {
            File file = new File(path);
            email.putExtra(android.content.Intent.EXTRA_STREAM, Uri.fromFile(file));
            // 用 image/png 時,系統會同時列出彩信、郵件等可處理圖片的程式
            email.setType("image/png");
        }

        context.startActivity(Intent.createChooser(email, "請選擇發送軟體"));
    }

    /** 取得指定 Activity 的截圖並存成 png 檔 */
    private static Bitmap takeScreenShot(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();

        // 取得狀態列高度
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        // 取得螢幕寬高
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay().getHeight();

        // 從狀態列下方開始裁切,去掉狀態列
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width,
                height - statusBarHeight);

        view.destroyDrawingCache();
        return b;
    }

    /** 截圖存檔 */
    private static void savePic(Bitmap b, String filePath, String fileName) {
        File f = new File(filePath);
        if (!f.exists()) {
            f.mkdir();
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath + File.separator + fileName);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 截屏並發送郵件 */
    public static void takeScreenShotToEmail(Context context, Activity a) {
        if (getAvailableSDcard(context)) {
            savePic(takeScreenShot(a), filePath, fileName);
            sendEmail(context, null, null, null, detailPath);
        }
    }

    /** 判斷 SD 卡是否可用且剩餘空間大於 minSizeSDcard */
    public static boolean getAvailableSDcard(Context context) {
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);

        if (sdCardExist) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            long sdCardSize = (availableBlocks * blockSize) / 1024;   // KB

            if (sdCardSize > minSizeSDcard) {
                return true;
            } else {
                Toast.makeText(context, "SD 卡空間不足", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "請在使用轉發功能之前插入 SD 卡", Toast.LENGTH_SHORT).show();
        }
        return false;
    }
}

呼叫端

在 Activity 裡只要一個按鈕就能觸發整個流程:

package com.johnson.Screenshot;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ScreenshotActivity extends Activity {

    Button bt;
    Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        bt = (Button) findViewById(R.id.button1);
        mContext = this;

        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ScreenshotTools.takeScreenShotToEmail(mContext, ScreenshotActivity.this);
            }
        });
    }
}

對應版面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_text" />
</LinearLayout>

移植到新專案時必須調整的地方

這份程式碼寫於早期 Android 版本,直接搬進新專案會遇到幾個問題,值得逐一處理:

  • 檔案 URI 與 FileProvider:Android 7.0(API 24)起禁止把 file:// URI 直接傳給其他應用,會拋出 FileUriExposedException。必須改用 FileProvider.getUriForFile() 產生 content:// URI,並在 manifest 中宣告 provider 與 file_paths.xml。
  • 執行期權限:寫入外部儲存空間需要 WRITE_EXTERNAL_STORAGE,Android 6.0 以上還必須在執行期動態向使用者申請。建議改用 getExternalFilesDir() 取得 App 專用目錄,即可免申請權限。
  • API 已棄用:Display.getWidth()/getHeight() 已標記為 deprecated,建議改用 DisplayMetrics 或 WindowMetrics;StatFs.getBlockSize() 亦應替換為 getBlockSizeLong()。
  • DrawingCache 的替代做法:DrawingCache 已不是推薦作法。若只是要擷取某個 View,可改用 Canvas 直接對 View 執行 draw();若要擷取整個畫面,則可走 PixelCopy API。
  • 狀態列高度建議動態計算:寫死 25px 的作法在不同解析度與不同 Android 版本(尤其全面屏、瀏海螢幕)上都不準,透過 WindowInsets 取得會可靠得多。
  • 記得回收 Bitmap:截圖用的 Bitmap 佔用記憶體可觀,寫檔完成後應呼叫 recycle(),並在 takeScreenShot() 中對中間產物 b1 一併處理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved