Android分享---調用系統自帶的分享功能


以前我們總想到友盟等平台分享功能的集成,集成這玩意還得下載對應的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 ShareUtil
13 {
14 
15     private static final String EMAIL_ADDRESS = "791335000@qq.com.com";
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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM