1. 程式人生 > >Android APP拉起小程式、分享小程式、小程式開啟APP

Android APP拉起小程式、分享小程式、小程式開啟APP


APP拉起小程式

	private void launchMiniProgram(String path) {
        String appId = "你的appid"; // 填應用AppId
        IWXAPI api = WXAPIFactory.createWXAPI(PinDanActivity.this, appId);

        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = "原始id"; // 填小程式原始id
        req.path = path;                  //拉起小程式頁面的可帶參路徑,不填預設拉起小程式首頁
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;// 可選開啟 開發版,體驗版和正式版
        api.sendReq(req);
    }
  • req.userName 引數是小程式原始id,不是小程式的appid,不然會提示跳轉失敗。
  • req.path 引數是小程式裡面的頁面路徑,及json檔案裡面的路徑,比如:/pages/index/index?id=1
  • req.miniprogramType 小程式的版本

回撥WXEntryActivity

	@Override
    public void onResp(BaseResp baseResp) {
        // baseresp.getType 1:第三方授權, 2:分享
        LogUtil.i("baseresp.getType = " + baseResp.getType());
        switch (baseResp.getType()) {
            case 1:
              
                break;
            case 2:
              
                break;
            case ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM:
                WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) baseResp;
                //獲取引數
                String extraData = launchMiniProResp.extMsg; //對應小程式元件 <button open-type="launchApp"> 中的 app-parameter 屬性
                break;
        }
      }

APP分享小程式

    private void shareMiniProgram(String url) {
        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = url; // 相容低版本的網頁連結
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPROGRAM_TYPE_PREVIEW;// 正式版:0,測試版:1,體驗版:2
        miniProgramObj.userName = "原始id";     // 小程式原始id
        miniProgramObj.path = "/pages/home/home";        //小程式頁面路徑

        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        msg.title ="分享的標題"; // 小程式訊息title
        msg.description = "分享的描述";   // 小程式訊息desc
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pindan);
        msg.thumbData = bmpToByteArray(bitmap, true);   // 小程式訊息封面圖片,小於128k

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前支援會話
        api.sendReq(req);
    }

小程式開啟APP

<button open-type="launchApp" app-parameter="wechat" binderror="launchAppError">開啟APP</button>
  • open-type=“launchApp” 開放能力
  • app-parameter=“wechat” 傳參
  • binderror=“launchAppError” 失敗回撥
Page({
  launchAppError (e) {
    console.log(e.detail.errMsg)
  }
})