全部產品
Search
文件中心

Mobile Platform as a Service:Android 小程式發送自訂訊息至自訂 View

更新時間:Jul 13, 2024

說明 Android 小程式發送自訂訊息至自訂 View 功能僅在 mPaaS 10.1.68.29 及以上版本中支援。當前使用的基準版本低於 10.1.68.29 時,可參考 mPaaS 升級指南 升級基準版本至 10.1.68.29。

建立自訂 View context

this.context = my.createMpaasCustomComponentContext('mpaas-map');

'mpaas-map' 為小程式標籤中 id 對應的 value,這裡請填入您的 id。

通過 context 向用戶端發送訊息

this.context.postMessage({
      actionType: 'setColor',
      data: {
        "color": "#FF00FF00"
      }
    });

其中 actionType 為用戶端接收到的訊息事件名稱,data 為擴充參數。

用戶端接收訊息並處理原生 View

public class MyTestEmbedView extends MPBaseEmbedView {
    ···
    @Override
    public void onReceivedMessage(String actionType, JSONObject data, H5BridgeContext bridgeContext) {
        LoggerFactory.getTraceLogger().debug(TAG, "onReceivedMessage, actionType: " + actionType + ", data: " + data.toString());
        if("setColor".equals(actionType)){
            mRealView.setColor(Color.parseColor(data.getString("color")));
        }
    }
    ···
}

onReceivedMessage 方法中第一個參數為小程式傳入的 actionType,第二個參數為傳入的擴充參數,第三個參數為 bridge(可忽略)。