標籤:選擇 sources log parcel pre extra sendto string 選取器
以前我們總想到友盟等平台分享功能的整合,整合這玩意還得下載對應的jar包。當然,用這些平台的分享並不是說什麼好處都沒有,至少人家的統計功能還是很實用的。不過有的時候我們是不需要多餘功能的,只需要能分享就行,那我們就可以直接用Andriod系統內建有分享功能去完成了。下面我來介紹如何?系統的分享功能:
分享文本資訊
1 Intent intent = new Intent(Intent.ACTION_SEND);2 intent.setType("text/plain");3 intent.putExtra(Intent.EXTRA_TEXT, text);4 context.startActivity(Intent.createChooser(intent, title));
分享單張圖片
1 Intent intent = new Intent(Intent.ACTION_SEND);2 intent.setType("image/png");3 intent.putExtra(Intent.EXTRA_STREAM, uri);4 context.startActivity(Intent.createChooser(intent,title));
這裡解釋一下,圖片檔案要先通過getResourcesUri()拿到圖片資源的Path,然後再轉換成URI對象放入intent.putExtra()的第二個參數中。
分享多個圖片檔案
1 Intent mulIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);2 mulIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);3 mulIntent.setType("image/jpeg");4 context.startActivity(Intent.createChooser(mulIntent, "多圖檔案分享"));
我們可以建立一個選取器,使用者多選完之後,放到Uri集合,然後就直接可以通過以上代碼進行分享了,分享效果和相同。
以上分享,已整理成工具類,代碼如下:
1 package huolongluo.sharedemo; 2 3 import android.content.Context; 4 import android.content.Intent; 5 import android.net.Uri; 6 7 import java.util.ArrayList; 8 9 /**10 * Created by 火龍裸 on 2017/11/2.11 */12 public class ShareUtil13 {14 15 private static final String EMAIL_ADDRESS = "[email protected]";16 17 public static void shareText(Context context, String text, String title)18 {19 Intent intent = new Intent(Intent.ACTION_SEND);20 intent.setType("text/plain");21 intent.putExtra(Intent.EXTRA_TEXT, text);22 context.startActivity(Intent.createChooser(intent, title));23 }24 25 public static void shareImage(Context context, Uri uri, String title)26 {27 Intent intent = new Intent(Intent.ACTION_SEND);28 intent.setType("image/png");29 intent.putExtra(Intent.EXTRA_STREAM, uri);30 context.startActivity(Intent.createChooser(intent, title));31 }32 33 public static void sendEmail(Context context, String title)34 {35 Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + EMAIL_ADDRESS));36 context.startActivity(Intent.createChooser(intent, title));37 }38 39 public static void sendMoreImage(Context context, ArrayList<Uri> imageUris, String title)40 {41 Intent mulIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);42 mulIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);43 mulIntent.setType("image/jpeg");44 context.startActivity(Intent.createChooser(mulIntent, "多圖檔案分享"));45 }46 }
Android分享---調用系統內建的分享功能