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

Android 程式呼叫系統分享功能的實作範例

編輯:關於 Android 程式設計

本文將說明如何在 Android 程式中呼叫系統的分享功能,涵蓋分享文字、單張圖片與多張圖片三種情境,分享給大家參考。

 /**
 * 調用系統的分享功能
 * Created by admin on 15-4-13.
 */
 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
 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, "分享到"));
 }
 } 

從程式碼可以看出,系統分享的核心在於建構一個 Intent:分享文字時使用 ACTION_SEND 搭配 EXTRA_TEXT 與 text/plain 類型;分享單張圖片時搭配 EXTRA_STREAM 與 image/* 類型;而分享多張圖片則改用 ACTION_SEND_MULTIPLE,並以 putParcelableArrayListExtra 傳入多個 Uri 清單。最後透過 Intent.createChooser 彈出系統分享選單,讓使用者自行選擇要分享到的目標應用。

頁面效果如下:

值得一提的是,在較新版本的 Android 中,由於採用 FileProvider 來共享檔案 URI,直接以 Uri.fromFile 傳遞檔案可能會引發 FileUriExposedException,實作時建議改用 FileProvider.getUriForFile 並授予讀取權限,以確保分享順利進行。

希望本文所述能對大家的 Android 程式設計有所幫助。

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