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

Android 調用系統分享:文字、單圖與多圖三種場景

編輯:關於 Android 程式設計

分享功能不必自己實現,Android 內建的 ACTION_SEND 就能把內容拋給微信、郵件、藍牙等所有已安裝的目標應用。核心只有三件事:設置 action、塞入數據、指定 MIME 類型,最後用 Intent.createChooser 彈出選擇列表。

public class ShareActivity extends Activity {

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

    /** 分享純文字 */
    public void shareText(View view) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "This is my Share text.");
        shareIntent.setType("text/plain");
        // 每次都顯示分享列表
        startActivity(Intent.createChooser(shareIntent, "分享到"));
    }

    /** 分享單張圖片 */
    public void shareSingleImage(View view) {
        String imagePath = Environment.getExternalStorageDirectory()
                + File.separator + "test.jpg";
        Uri imageUri = Uri.fromFile(new File(imagePath));
        Log.d("share", "uri:" + imageUri);   // file:///storage/emulated/0/test.jpg

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("image/*");
        startActivity(Intent.createChooser(shareIntent, "分享到"));
    }

    /** 分享多張圖片 */
    public void shareMultipleImage(View view) {
        ArrayList<Uri> uriList = new ArrayList<>();
        String path = Environment.getExternalStorageDirectory() + File.separator;
        uriList.add(Uri.fromFile(new File(path + "australia_1.jpg")));
        uriList.add(Uri.fromFile(new File(path + "australia_2.jpg")));
        uriList.add(Uri.fromFile(new File(path + "australia_3.jpg")));

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList);
        shareIntent.setType("image/*");
        startActivity(Intent.createChooser(shareIntent, "分享到"));
    }
}

三個入口的關鍵差異:文字用 EXTRA_TEXT + text/plain;單圖用 EXTRA_STREAM + image/*;多圖改用 ACTION_SEND_MULTIPLE,並以 putParcelableArrayListExtra 傳遞 Uri 列表。

運行效果:

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