当前位置 : 主页 > 手机开发 > android >

Android自带API实现分享功能

来源:互联网 收集:自由互联 发布时间:2021-08-03
前言 在做项目的过程中需要实现文字和图片的分享,有两种方式: 1. 使用android sdk中自带的Intent.ACTION_SEND实现分享。 2. 使用shareSDK、友盟等第三方的服务。 鉴于使用的方便,此次只介

前言

在做项目的过程中需要实现文字和图片的分享,有两种方式:
1. 使用android sdk中自带的Intent.ACTION_SEND实现分享。
2. 使用shareSDK、友盟等第三方的服务。
鉴于使用的方便,此次只介绍使用Android sdk中自带的方式来实现分享的功能。

分享文字

/** 
   * 分享文字内容 
   * 
   * @param dlgTitle 
   *      分享对话框标题 
   * @param subject 
   *      主题 
   * @param content 
   *      分享内容(文字) 
   */ 
private void shareText(String dlgTitle, String subject, String content) { 
    if (content == null || "".equals(content)) { 
      return; 
    } 
    Intent intent = new Intent(Intent.ACTION_SEND); 
    intent.setType("text/plain"); 
    if (subject != null && !"".equals(subject)) { 
      intent.putExtra(Intent.EXTRA_SUBJECT, subject); 
    } 

    intent.putExtra(Intent.EXTRA_TEXT, content); 

    // 设置弹出框标题 
    if (dlgTitle != null && !"".equals(dlgTitle)) { // 自定义标题 
      startActivity(Intent.createChooser(intent, dlgTitle)); 
    } else { // 系统默认标题 
      startActivity(intent); 
    } 
  } 

分享单张图片

/** 
   * 分享图片和文字内容 
   * 
   * @param dlgTitle 
   *      分享对话框标题 
   * @param subject 
   *      主题 
   * @param content 
   *      分享内容(文字) 
   * @param uri 
   *      图片资源URI 
   */ 
  private void shareImg(String dlgTitle, String subject, String content, 
      Uri uri) { 
    if (uri == null) { 
      return; 
    } 
    Intent intent = new Intent(Intent.ACTION_SEND); 
    intent.setType("image/*"); 
    intent.putExtra(Intent.EXTRA_STREAM, uri); 
    if (subject != null && !"".equals(subject)) { 
      intent.putExtra(Intent.EXTRA_SUBJECT, subject); 
    } 
    if (content != null && !"".equals(content)) { 
      intent.putExtra(Intent.EXTRA_TEXT, content); 
    } 

    // 设置弹出框标题 
    if (dlgTitle != null && !"".equals(dlgTitle)) { // 自定义标题 
      startActivity(Intent.createChooser(intent, dlgTitle)); 
    } else { // 系统默认标题 
      startActivity(intent); 
    } 
  } 

分享多张图片

//分享多张图片 
  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, "分享到")); 
  } 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

网友评论