第三方分享第一彈----微信分享

第三方分享第一彈----微信分享

大家都知道,分享功能幾乎是所有APP都需要的基礎功能,為了讓大家免于到處去找資料,我這里簡單的做了一下總結,也算是自己學習的一個記錄。
下面我們先來看下微信的分享功能。

官方資料

首先,想要微信的分享,需要我們去微信公眾平臺創建我們的應用,這個其實很簡單啦,大家按照步驟一步一步來就可以啦,應用審核一般兩到三天就可以了,待審核通過以后就可以開始安心的敲代碼啦.

微信的分享支持文本,視頻,音頻,圖片,網頁甚至小程序,在這里我們來看下官方介紹的方法:

官方文檔傳送門

首先我們需要依賴微信的第三方庫:

  compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:1.1.6'

分享之前需要創建api對象,如下:

IWXAPI api;
// WXAPIFactory工廠,獲取IWXAPI實例
api = WXAPIFactory.createWXAPI(context, Constants.WeChat_APPID, false);
// 注冊應用
boolean flag = api.registerApp(Constants.WeChat_APPID); // 你申請應用的APPID 

1.文本分享

WXTextObject textObject = new WXTextObject();
textObject.text = "hello";//你要分享出去的文本
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = textObject;
msg.description = "hello";

SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("text");// 唯一標識一個請求
req.message = msg;
// 發送到聊天界面——WXSceneSession
// 發送到朋友圈——WXSceneTimeline
// 添加到微信收藏——WXSceneFavorite
req.scene = SendMessageToWX.Req.WXSceneSession;
api.sendReq(req);  

2.圖片分享

   Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.share_pic);

    WXImageObject imageObject = new WXImageObject(bitmap);


    WXMediaMessage msg = new WXMediaMessage();
    msg.mediaObject = imageObject;

    //設置縮略圖
    Bitmap bmp = Bitmap.createScaledBitmap(bitmap,80,80,true);
    bitmap.recycle();
    msg.thumbData = BitmapUtils.Bitmap2Bytes(bmp);

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("text");// 唯一標識一個請求
    req.message = msg;
    req.scene = SendMessageToWX.Req.WXSceneSession;

    api.sendReq(req);

3.音樂分享

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.share_pic);

    WXMusicObject musicObject = new WXMusicObject();
    musicObject.musicUrl = "音樂url";

    WXMediaMessage msg = new WXMediaMessage();
    msg.mediaObject = musicObject;
    msg.title = "音樂標題";
    msg.description = "音樂描述";

    //設置縮略圖
    Bitmap bmp = Bitmap.createScaledBitmap(bitmap,80,80,true);
    bitmap.recycle();
    msg.thumbData = BitmapUtils.Bitmap2Bytes(bmp);

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("music");// 唯一標識一個請求
    req.message = msg;
    req.scene = SendMessageToWX.Req.WXSceneSession;

    api.sendReq(req); 
    

4.視頻分享

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.share_pic);

    WXMusicObject musicObject = new WXMusicObject();
    musicObject.musicUrl = "視頻url";

    WXMediaMessage msg = new WXMediaMessage();
    msg.mediaObject = musicObject;
    msg.title = "視頻標題";
    msg.description = "視頻描述";

    //設置縮略圖
    Bitmap bmp = Bitmap.createScaledBitmap(bitmap,80,80,true);
    bitmap.recycle();
    msg.thumbData = BitmapUtils.Bitmap2Bytes(bmp);

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("video");// 唯一標識一個請求
    req.message = msg;
    req.scene = SendMessageToWX.Req.WXSceneSession;

    api.sendReq(req); 
    

5.網頁分享

 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.share_pic);

    WXMusicObject musicObject = new WXMusicObject();
    musicObject.musicUrl = "網頁url";

    WXMediaMessage msg = new WXMediaMessage();
    msg.mediaObject = musicObject;
    msg.title = "網頁標題";
    msg.description = "網頁描述";

    //設置縮略圖
    Bitmap bmp = Bitmap.createScaledBitmap(bitmap,80,80,true);
    bitmap.recycle();
    msg.thumbData = BitmapUtils.Bitmap2Bytes(bmp);

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("webpage");// 唯一標識一個請求
    req.message = msg;
    req.scene = SendMessageToWX.Req.WXSceneSession;

    api.sendReq(req);  
    

小程序的我們暫時就不做分享了,但是從上面的官方案例中我們可以看出分享的代碼高度一致,所以小編我就順便優化了一下,代碼如下,不喜勿噴:

經過優化封裝后

public class WeChatShare {
  // 第三方APP和微信通信的openApi接口
  private static IWXAPI iwxapi;
  private static Context mContext;
  private int share_to = WxShareTo.share_session;
  private int share_type = -1;
  private String url = "";
  private String title = "";
  private String description = "";
  private String shareText = "";
  private Bitmap imageBitmap = null;
  private String miniProgramId = "";
  private String miniProgramPath = "";

  public static WeChatShare regToWx(Context context) {
    mContext = context;
    // WXAPIFactory工廠,獲取IWXAPI實例
    iwxapi = WXAPIFactory.createWXAPI(context, Constants.WeChat_APPID, false);
    // 注冊應用
    boolean flag = iwxapi.registerApp(Constants.WeChat_APPID);
    Toast.makeText(context, "flag:" + flag, Toast.LENGTH_SHORT).show();
    return new WeChatShare();
  }

  public WeChatShare setWhere(@WxShareTo int shareTo) {
    share_to = shareTo;
    return this;
  }

  /**
   * 分享的類型
   *
   * @param type
   *
   * @return
   */
  public WeChatShare setType(@WxShareType int type) {
    share_type = type;
    return this;
  }

  /**
   * 分享的Url
   *
   * @param url
   *
   * @return
   */
  public WeChatShare addUrl(String url) {
    this.url = url;
    return this;
  }

  /**
   * 分享的標題
   *
   * @param title
   *
   * @return
   */
  public WeChatShare addTitle(String title) {
    this.title = title;
    return this;
  }

  /**
   * 描述
   *
   * @param description
   *
   * @return
   */
  public WeChatShare addDescription(String description) {
    this.description = description;
    return this;
  }

  /**
   * 分享的圖片url
   *
   * @param imageUrl
   *
   * @return
   */
  public WeChatShare addImage(String imageUrl) {
    if (TextUtils.isEmpty(imageUrl)) {
      throw new NullPointerException("imageUrl is empty.");
    }
    addImage(BitmapUtils.getBitmap(imageUrl));
    return this;
  }

  /**
   * 分享的圖片資源ID
   *
   * @param imageResource
   *
   * @return
   */
  public WeChatShare addImage(int imageResource) {
    addImage(BitmapFactory.decodeResource(mContext.getResources(), imageResource));
    return this;
  }

  /**
   * 分享的圖片bitmap
   *
   * @param imageBitmap
   *
   * @return
   */
  public WeChatShare addImage(Bitmap imageBitmap) {
    this.imageBitmap = imageBitmap;
    return this;
  }

  /**
   * 分享的wenbennr
   *
   * @param shareText
   *
   * @return
   */
  public WeChatShare addShareText(String shareText) {
    this.shareText = shareText;
    return this;
  }

  /**
   * 分享小程序的原始Id
   *
   * @param miniProgramId
   *
   * @return
   */
  public WeChatShare addMiniProgramId(String miniProgramId) {
    this.miniProgramId = miniProgramId;
    return this;
  }

  /**
   * 分享小程序的path
   *
   * @param miniProgramPath
   *
   * @return
   */
  public WeChatShare addMiniProgramPath(String miniProgramPath) {
    this.miniProgramPath = miniProgramPath;
    return this;
  }

  public void share() {
    WXMediaMessage msg = new WXMediaMessage();
    if (share_type < 0) {
      throw new NullPointerException("you should set share type first.");
    }
    // 標題
    if (!TextUtils.isEmpty(title)) {
      msg.title = title;
    }

    // 描述
    if (!TextUtils.isEmpty(description)) {
      msg.description = description;
    }

    String transaction = "";
    switch (share_type) {
      case WxShareType.type_text:
        // 分享文本
        transaction = "text";
        msg.description = shareText;
        WXTextObject textObject = new WXTextObject();
        textObject.text = shareText;
        msg.mediaObject = textObject;
        break;
      case WxShareType.type_image:
        // 分享圖片
        transaction = "img";
        if (null == imageBitmap) {
          throw new NullPointerException("bitmap is null.");
        }
        msg.mediaObject = new WXImageObject(imageBitmap);
        break;
      case WxShareType.type_video:
        // 分享視頻
        transaction = "video";
        WXVideoObject videoObject;
        videoObject = new WXVideoObject();
        videoObject.videoUrl = url;
        msg.mediaObject = videoObject;
        break;
      case WxShareType.type_music:
        // 分享音頻
        transaction = "music";
        WXMusicObject musicObject = new WXMusicObject();
        musicObject.musicUrl = url;
        msg.mediaObject = musicObject;
        break;
      case WxShareType.type_webPage:
        // 分享網頁
        transaction = "webpage";
        WXWebpageObject webpageObject = new WXWebpageObject();
        webpageObject.webpageUrl = url;
        msg.mediaObject = webpageObject;
        break;
      case WxShareType.type_miniProgram:
        /**
         * 注: 要求發起分享的App與小程序屬于同一微信開放平臺帳號。
         * 小程序的原始ID獲取方法:登錄小程序后臺-設置-基本設置-帳號信息
         */
        // 分享小程序
        if (TextUtils.isEmpty(miniProgramId)) {
          throw new NullPointerException("miniProgramId is empty.");
        }
        if (TextUtils.isEmpty(miniProgramPath)) {
          throw new NullPointerException("miniProgramPath is empty.");
        }
        if (TextUtils.isEmpty(url)) {
          throw new NullPointerException("the url for lower WeChat to open is empty.");
        }
        transaction = "webpage";
        WXMiniProgramObject miniProgramObject = new WXMiniProgramObject();
        miniProgramObject.webpageUrl = url;// 低版本微信將打開的url
        miniProgramObject.userName = miniProgramId; // 跳轉的小程序的原始ID
        miniProgramObject.path = miniProgramPath; // 小程序的path
        msg.mediaObject = miniProgramObject;
        break;
    }

    // 縮略圖
    if (null != imageBitmap) {
      Bitmap bmp = Bitmap.createScaledBitmap(imageBitmap, 80, 80, true);
      imageBitmap.recycle();
      msg.thumbData = BitmapUtils.Bitmap2Bytes(bmp);
    }
    sendMsg(msg, transaction);
  }

  /**
   * 調起微信分享
   *
   * @param mediaMessage
   */
  private void sendMsg(WXMediaMessage mediaMessage, String transaction) {
    if (!AppUtils.getInstance(mContext).isAppAvilible(AppUtils.WX_PKGNAME)) {
      Toast.makeText(mContext, "您還未安裝微信客戶端,請先安裝.", Toast.LENGTH_SHORT).show();
      return;
    }
    if (TextUtils.isEmpty(transaction)) {
      throw new NullPointerException("you should set share type first.");
    }
    // 構造Req
    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction(transaction);
    req.message = mediaMessage;
    req.scene = share_to;
    iwxapi.sendReq(req);
  }

  private String buildTransaction(String type) {
    return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
  }
}

分享位置的參數值:

@IntDef ({ share_session, share_timeline, share_favorite })// 枚舉數據
@Retention (RetentionPolicy.SOURCE) //告訴編譯器在生成.class文件時不保留枚舉注解數據
public @interface WxShareTo {
  // 發送到聊天界面——WXSceneSession
  int share_session = SendMessageToWX.Req.WXSceneSession;
  // 發送到朋友圈——WXSceneTimeline
  int share_favorite = SendMessageToWX.Req.WXSceneFavorite;
  // 添加到微信收藏——WXSceneFavorite
  int share_timeline = SendMessageToWX.Req.WXSceneTimeline;
}

分享類型的參數值:

@IntDef ({ type_text, type_image, type_video, type_music, type_webPage, type_miniProgram })//枚舉類型
@Retention (RetentionPolicy.SOURCE) //告訴編譯器在生成.class文件時不保留枚舉注解數據
public @interface WxShareType {

  int type_text = 0;
  int type_image = 1;
  int type_video = 2;
  int type_music = 3;
  int type_webPage = 4;
  int type_miniProgram = 5;
}

相關工具類:

AppUtils.class

public class AppUtils {
  public static AppUtils instance;
  public static Context mContext;
  public static final String QQ_PKGNAME = "com.tencent.mobileqq";
  public static final String WX_PKGNAME = "com.tencent.mm";

  public static AppUtils getInstance(Context context) {
    mContext = context;
    if (null == instance) {
      synchronized (AppUtils.class) {
        if (null == instance) {
          instance = new AppUtils();
        }
      }
    }
    return instance;
  }

  public boolean isAppAvilible(String pkgName) {
    final PackageManager packageManager = mContext.getPackageManager();// 獲取packagemanager
    List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 獲取所有已安裝程序的包信息
    if (pinfo != null) {
      for (int i = 0; i < pinfo.size(); i++) {
        String pn = pinfo.get(i).packageName;
        if (pn.equals("com.tencent.mm")) {
          return true;
        }
      }
    }

    return false;
  }
}

BitmapUtils.class

public class BitmapUtils {

  /**
   * 將圖片內容解析成字節數組
   *
   * @param inStream
   *
   * @return byte[]
   *
   * @throws Exception
   */
  public static byte[] readStream(InputStream inStream) throws Exception {
    byte[] buffer = new byte[1024];
    int len = -1;
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    while ((len = inStream.read(buffer)) != -1) {
      outStream.write(buffer, 0, len);
    }
    byte[] data = outStream.toByteArray();
    outStream.close();
    inStream.close();
    return data;
  }

  /**
   * 將字節數組轉換為ImageView可調用的Bitmap對象
   *
   * @param bytes
   * @param opts
   *
   * @return Bitmap
   */
  public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {
    if (bytes != null) {
      if (opts != null) {
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
      } else {
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
      }
    }
    return null;
  }

  /**
   * 圖片縮放
   *
   * @param bitmap 對象
   * @param w 要縮放的寬度
   * @param h 要縮放的高度
   *
   * @return newBmp 新 Bitmap對象
   */
  public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    Matrix matrix = new Matrix();
    float scaleWidth = ((float) w / width);
    float scaleHeight = ((float) h / height);
    matrix.postScale(scaleWidth, scaleHeight);
    Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    return newBmp;
  }

  /**
   * 把Bitmap轉Byte
   */
  public static byte[] Bitmap2Bytes(Bitmap bm) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
  }

  /**
   * 把字節數組保存為一個文件
   */
  public static File getFileFromBytes(byte[] b, String outputFile) {
    BufferedOutputStream stream = null;
    File file = null;
    try {
      file = new File(outputFile);
      FileOutputStream fstream = new FileOutputStream(file);
      stream = new BufferedOutputStream(fstream);
      stream.write(b);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
    }
    return file;
  }

  public static Bitmap getBitmap(String url) {
    Bitmap bm = null;
    try {
      URL iconUrl = new URL(url);
      URLConnection conn = iconUrl.openConnection();
      HttpURLConnection http = (HttpURLConnection) conn;

      int length = http.getContentLength();

      conn.connect();
      // 獲得圖像的字符流
      InputStream is = conn.getInputStream();
      BufferedInputStream bis = new BufferedInputStream(is, length);
      bm = BitmapFactory.decodeStream(bis);
      bis.close();
      is.close();// 關閉流
    } catch (Exception e) {
      e.printStackTrace();
    }
    return bm;
  }
}  

使用起來也很簡單,如果你看過gilde或者picasso的源碼,那么,一眼就能看出來該怎么使用了,在此,僅做一個文本分享的示例:

WeChatShare.regToWx(this)// 注冊APP到微信
            .setWhere(WxShareTo.share_session)// 設置分享到哪邊
            .setType(WxShareType.type_text) // 設置分享的類型
            .addShareText("你好") // 文本分享添加要分享的文本
            .share(); // 發起分享請求

當然有分享就該有回調,這里需要注意的是,微信規定了回調類的格式,首先你需要在包名文件夾下新建wxapi 文件夾,然后在創建 WXEntryActivity 類集成自Activity并實現微信的IWXAPIEventHandler接口,然后就可以在onReqonResq中得到回調內容,如下:

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
  public static final String TAG = WXEntryActivity.class.getSimpleName().trim();
  private IWXAPI api;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView currrentTextView = new TextView(this);
    setContentView(currrentTextView);
    api = WXAPIFactory.createWXAPI(this, Constants.WeChat_APPID, false);
    api.handleIntent(getIntent(), this);
  }

  @Override protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    api.handleIntent(intent, this);
  }

  @Override public void onReq(BaseReq baseReq) {
    Log.i(TAG, "onReq: ");
  }

  @Override public void onResp(BaseResp resp) {
    int errorCode = resp.errCode;
    Log.i(TAG, "onResp: " + errorCode);
    switch (errorCode) {
      case BaseResp.ErrCode.ERR_OK:
        //用戶同意
        //String code = ((SendAuth.Resp) resp).code;
        Log.i(TAG, "ERR_OK: ");
        break;
      case BaseResp.ErrCode.ERR_AUTH_DENIED:
        //用戶拒絕
        Log.i(TAG, "ERR_AUTH_DENIED: ");
        break;
      case BaseResp.ErrCode.ERR_USER_CANCEL:
        //用戶取消
        Log.i(TAG, "ERR_USER_CANCEL: ");
        break;
      default:
        break;
    }
  }
}

自此,微信分享介紹完畢,不足之處,歡迎指正。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,372評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,245評論 4 61
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一種新的協議。它實...
    香橙柚子閱讀 24,111評論 8 183
  • 原文 子曰:“不患人之不己知,患不知人也。” 譯文 孔子說:“不怕別人不了解自己,只怕自己不了解別人。” 學習心得...
    幻玥閱讀 3,304評論 1 4
  • 習慣形成:信號 反應程序 獎勵機制 信念 拖延癥是當今社會中互聯網知識復雜情況而慢慢養成的習慣之一。 拖延癥是怎么...
    塞弗特Mr王閱讀 240評論 0 0