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

Android 調用系統自帶分享功能(文字+圖片一步到位)

編輯:關於 Android 程式設計

想讓 App 借助系統的分享面板,把文字和圖片一起分享出去?其實只要一個方法就能搞定,直接看代碼:

/**
 * 分享功能
 *
 * @param context     上下文
 * @param activityTitle Activity 的名字
 * @param msgTitle    消息標題
 * @param msgText     消息內容
 * @param imgPath     圖片路徑,不分享圖片則傳 null
 */
public void shareMsg(String activityTitle, String msgTitle, String msgText, String imgPath) {
    Intent intent = new Intent(Intent.ACTION_SEND);
    if (imgPath == null || imgPath.equals("")) {
        intent.setType("text/plain"); // 純文本
    } else {
        File f = new File(imgPath);
        if (f != null && f.exists() && f.isFile()) {
            intent.setType("image/jpg");
            Uri u = Uri.fromFile(f);
            intent.putExtra(Intent.EXTRA_STREAM, u);
        }
    }
    intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
    intent.putExtra(Intent.EXTRA_TEXT, msgText);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(Intent.createChooser(intent, activityTitle));
}

原理很直白:構造一個 ACTION_SEND 的 Intent,根據是否傳入圖片路徑決定 setType 是 text/plain 還是 image/jpg,再把標題、內容通過 EXTRA_SUBJECT 與 EXTRA_TEXT 塞進去,最後用 createChooser 彈出系統分享面板即可。簡單幾行,就能複用整個系統的分享能力,著實方便。

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