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

把自己的應用加入系統分享選單

編輯:關於 Android 程式設計

想讓使用者在相冊或瀏覽器中按下「分享」時,你的 App 也能出現在清單裡,只需要在 Manifest 中為某個 Activity 加上適合的 intent-filter。

基本寫法

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

三個元素各有作用:action 宣告「我能處理 ACTION_SEND」;data 用 MIME 類型限定「只收圖片」;category DEFAULT 則是讓這個 Activity 能出現在間接意圖(implicit intent)的候選清單中——少了它,系統的分享對話框不會列出你的 App。

支援多種型別

若同時要收文字與圖片,可以寫多組 <data>:

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

在 Activity 中接收

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
            handleSharedText(sharedText);
        } else if (type.startsWith("image/")) {
            Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
            if (imageUri != null) {
                handleSharedImage(imageUri);
            }
        }
    }
}

文字用 EXTRA_TEXT,圖片則用 EXTRA_STREAM 取得 Uri。讀取圖片時記得要在 Manifest 中加上 android:grantUriPermissions 相關設定,或使用 ContentResolver.openInputStream() 直接讀——分享而來的 Uri 是臨時授權,不能長期保存。

其他常見的分享相關 action

  • ACTION_SEND:分享一筆內容,最常用。
  • ACTION_SENDTO / ACTION_SEND_MULTIPLE:分享多筆內容(多張圖片)。
  • ACTION_VIEW:開啟指定內容,例如 <data android:scheme="http" android:host="example.com" /> 可攔下該網域的連結。
  • ACTION_MAIN + category.LAUNCHER:應用列表中的啟動圖示。

反向操作:從你的 App 分享出去

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "分享的內容");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "分享到"));

兩個實務提醒

1. 為分享入口自訂圖示與標籤。在 Activity 上設定 android:label 與 android:icon,分享選單中顯示的就是這組值,而不是 App 的預設圖示。多個分享入口時務必區分清楚,否則使用者會看到好幾個一模一樣的選項。

2. 留意 Android 12 之後的設計指引。分享選單的外觀由系統掌控,App 無法自訂樣式;若需要更豐富的分享體驗(例如直接分享給某個聯絡人),應改用 Intent.createChooser() 搭配 ChooserTargetService,或使用 AndroidX 的 ShareCompat 簡化程式碼。另外,新版系統對 intent-filter 中過於寬泛的設定審查更嚴格,宣告 image/* 這類範圍是恰當的,但盡量不要寫成 */*。

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