Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

讓你的 App 出現在系統分享選單裡:接收 ACTION_SEND 數據

編輯:關於 Android 程式設計

目標很清晰:用戶在系統相冊裡點「分享」時,我們自己的 App 能出現在候選列表並正確接收圖片。整個過程分兩步——先在 Manifest 註冊,再在 Activity 裡解析。

第一步:註冊 Intent-filter

在 AndroidManifest.xml 中為目標 Activity 聲明它能接收發送型 Intent:

<intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimetype="image/*" />
</intent-filter>

這裡的 mimetype 決定了你的 App 會出現在哪些分享場景。只寫 image/* 就只出現在圖片分享裡;若還想接文本,可以再加一條 text/plain 的 data。

第二步:在 Activity 中解析 Intent

void onCreate(Bundle savedInstanceState) {
    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            handleSendText(intent);       // 處理單條文本
        } else if (type.startsWith("image/")) {
            handleSendImage(intent);      // 處理單張圖片
        }
    } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            handleSendMultipleImages(intent);  // 處理多張圖片
        }
    } else {
        // 其他情況,例如從桌面圖標正常啟動
    }
}

void handleSendText(Intent intent) {
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (sharedText != null) {
        // 更新 UI 展示文本
    }
}

void handleSendImage(Intent intent) {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (imageUri != null) {
        // 更新 UI 展示圖片
    }
}

void handleSendMultipleImages(Intent intent) {
    ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
    if (imageUris != null) {
        // 更新 UI 展示多張圖片
    }
}

幾個容易忽略的細節

  • 區分單發與多發:ACTION_SEND 用 EXTRA_STREAM 取單個 Uri,ACTION_SEND_MULTIPLE 則用 getParcelableArrayListExtra 取列表,兩者不能混用。
  • URI 權限:從其他應用傳來的 content:// Uri 是臨時授權的。如果要把該 Uri 轉交給另一個 Activity 或保存下來,記得用 grantUriPermission 或 takePersistableUriPermission 續期,否則稍後讀取會拋 SecurityException。
  • 別忘了兜底:不少分享入口傳的是 EXTRA_TEXT 而非流,只處理圖片會導致「分享進來一片空白」。
  • 不要在 onCreate 裡做重活:解碼大圖、複製文件應交給子線程或 ViewModel,避免影響啟動速度。

延伸閱讀

官方與社區的完整示例:https://code.tutsplus.com/tutorials/android-sdk-receiving-data-from-the-send-intent--mobile-14878

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved