日本熟妇hd丰满老熟妇,中文字幕一区二区三区在线不卡 ,亚洲成片在线观看,免费女同在线一区二区

功能配置

更新時(shí)間:

支持區(qū)分體驗(yàn)版/非體驗(yàn)版

  1. 開啟功能。

    Mriver.setConfig("mr_experience_required", "YES");
  2. 打開小程序體驗(yàn)/測(cè)試版本。

    MriverResource.deleteApp(appId); // 刪除本地版本
    
    Bundle bundle = new Bundle();
    bundle.putString(RVStartParams.LONG_NB_UPDATE, "synctry");  // 強(qiáng)制更新版本,可以組合使用
    bundle.putInt(RVStartParams.LONG_NB_EXPERIENCE_REQUIRED, 1); // 1表示體驗(yàn)版本, 不傳參數(shù)表示正式版本
    Mriver.startApp(this, appId, bundle);

支持小程序頁(yè)面返回詢問對(duì)話框

  1. 開啟返回?cái)r截開關(guān)。

    Mriver.setConfig("enable_back_perform", "YES");
  2. 升級(jí) Appx 版本。

    // build.gradle中添加
    api ('com.mpaas.mriver:mriverappxplus-build:2.7.18.20230130001@aar') {
          force=true
    }
  3. 小程序開發(fā)時(shí)調(diào)用相關(guān) API。

    // 開啟
    my.enableAlertBeforeUnload({
          message: '確認(rèn)離開此頁(yè)面?',
    });
    
    // 關(guān)閉
    my.disableAlertBeforeUnload()

真機(jī)調(diào)試/預(yù)覽

MriverDebug.setWssHost("真實(shí)wss地址");
MriverDebug.debugAppByScan(activity);

自定義標(biāo)題欄

Mriver.setProxy(TitleViewFactoryProxy.class, new TitleViewFactoryProxy() {
                @Override
                public ITitleView createTitle(Context context, App app) {
                    return new CustomTitleView(context);
                }
            });

public class CustomTitleView implements ITitleView, View.OnClickListener {
    
    public static final String TAG = MRConstants.INTEGRATION_TAG + ":MRTitleView";
    protected TextView tvTitle;
    protected ImageView ivImageTitle;
    protected ImageView btBack;
    protected TextView btBackToHome;
    protected RelativeLayout rlTitle;
    protected View statusBarAdjustView;
    
    protected List<ImageButton> btIconList = new ArrayList<>();
    
    
    // 整個(gè)TitleBar的container view
    protected TitleBarFrameLayout contentView;
    
    // 右上角OptionMenu的個(gè)數(shù)(默認(rèn)1個(gè))
    protected int visibleOptionNum;
    protected Page mPage;
    
    // 底部分割線
    protected View mDivider;
    protected Context mContext;
    
    protected TitleViewIconSpec mTitleViewIconSpec;
    
    protected TitleViewStyleSpec mDarkStyleSpec;
    
    protected TitleViewStyleSpec mLightStyleSpec;
    
    //    protected  ProgressBar mNavLoadingBar;
    protected ITitleEventDispatcher mTitleEventDispatcher;
    
    public CustomTitleView(Context context) {
        mContext = context;
        ViewGroup parent = null;
        if (context instanceof Activity && ((Activity) context).getWindow() != null) {
            parent = ((Activity) mContext).findViewById(android.R.id.content);
        }
        
        mTitleViewIconSpec = TitleViewSpecProvider.g().getIconSpec();
        mDarkStyleSpec = TitleViewSpecProvider.g().getDarkSpec();
        mLightStyleSpec = TitleViewSpecProvider.g().getLightSpec();
        
        contentView = (TitleBarFrameLayout) LayoutInflater.from(context).inflate(R.layout.mriver_title_bar_demo, parent, false);
        tvTitle = contentView.findViewById(R.id.h5_tv_title);
        ivImageTitle = contentView.findViewById(R.id.h5_tv_title_img);
        statusBarAdjustView = contentView.findViewById(R.id.h5_status_bar_adjust_view);
        ivImageTitle.setVisibility(View.GONE);
        tvTitle.setOnClickListener(this);
        ivImageTitle.setOnClickListener(this);
        
        btBack = contentView.findViewById(R.id.h5_tv_nav_back);
        btBackToHome = contentView.findViewById(R.id.h5_tv_nav_back_to_home);
        
        
        mDivider = contentView.findViewById(R.id.h5_h_divider_intitle);
        
        rlTitle = contentView.findViewById(R.id.h5_rl_title);
        visibleOptionNum = 1;
        
        // ad view
        //        adViewLayout.setTag(H5Utils.TRANSPARENT_AD_VIEW_TAG);
        
        btBack.setOnClickListener(this);
        btBackToHome.setOnClickListener(this);
        
        applyViewStyleAndIcon();
        
    }
    
    protected void applyViewStyleAndIcon() {
        boolean useBackSpec = false;
        boolean useHomeSpec = false;
        if (mTitleViewIconSpec != null) {
            TitleViewIconSpec.IconSpecEntry btHomeSpec = mTitleViewIconSpec.getHomeButton();
            if (btHomeSpec != null) {
                btBackToHome.setTypeface(btHomeSpec.getKey());
                btBackToHome.setText(btHomeSpec.getValue());
                useHomeSpec = true;
            }
            
        }
        
        if (!useHomeSpec) {
            Typeface iconFont = Typeface.createFromAsset(mContext.getAssets(), "mrv_iconfont.ttf");
            btBackToHome.setTypeface(iconFont);
        }
        
        btBackToHome.setTextColor(StateListUtils.getStateColor(mLightStyleSpec.getHomeButtonColor()));
    }
    
    
    protected void setButtonIcon(Bitmap btIcon, int index) {
        if (isOutOfBound(index, btIconList.size())) {
            return;
        }
        btIconList.get(index).setImageBitmap(btIcon);
    }
    
    @Override
    public void setTitle(String title) {
        if (title != null && enableSetTitle(title)) {
            tvTitle.setText(title);
            tvTitle.setVisibility(View.VISIBLE);
            ivImageTitle.setVisibility(View.GONE);
        }
    }
    
    protected boolean enableSetTitle(String title) {
        return !title.startsWith("http://") && !title.startsWith("https://");
    }
    
    // view visible control
    protected boolean isOutOfBound(int num, int length) {
        return length == 0 || length < num;
    }
    
    @Override
    public void showBackButton(boolean show) {
        btBack.setVisibility(show ? View.VISIBLE : View.GONE);
        if (show && btBackToHome != null) {
            btBackToHome.setVisibility(View.GONE);
        }
        addLeftMarginOnTitle();
    }
    
    @Override
    public void showOptionMenu(boolean b) {
        
    }
    
    public void showHomeButton(boolean show) {
        btBackToHome.setVisibility(show ? View.VISIBLE : View.GONE);
        if (show) {
            btBack.setVisibility(View.GONE);
        }
        addLeftMarginOnTitle();
    }
    
    @Override
    public void setTitleEventDispatcher(ITitleEventDispatcher dispatcher) {
        mTitleEventDispatcher = dispatcher;
    }
    
    @Override
    public void addCapsuleButtonGroup(View view) {
        if (view == null) {
            return;
        }
    }
    
    protected void addLeftMarginOnTitle() {
        boolean needAdd = btBack.getVisibility() != View.VISIBLE &&
            btBackToHome.getVisibility() != View.VISIBLE;
        RelativeLayout.LayoutParams rlTitleLayoutParams =
            (RelativeLayout.LayoutParams) rlTitle.getLayoutParams();
        rlTitleLayoutParams.setMargins(!needAdd ? 0 : DimensionUtil.dip2px(mContext, 16), 0, 0, 0);
        
    }
    
    @Override
    public void showTitleLoading(boolean show) {
    }
    
    @Override
    public View getContentView() {
        return contentView;
    }
    
    @Override
    public void onClick(View view) {
        RVLogger.d(TAG, "onClick " + view);
        if (mPage == null) {
            return;
        }
        if (view.equals(btBack)) {
            if (mTitleEventDispatcher != null) {
                mTitleEventDispatcher.onBackPressed();
            }
        } else if (view.equals(tvTitle) || view.equals(ivImageTitle)) {
            if (mTitleEventDispatcher != null) {
                mTitleEventDispatcher.onTitleClick();
            }
        } else if (view.equals(btBackToHome)) {
            if (mTitleEventDispatcher != null) {
                mTitleEventDispatcher.onHomeClick();
            }
        }
    }
    
    @Override
    public void setPage(Page page) {
        mPage = page;
        tvTitle.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                mPage.getApp().restartFromServer(null);
                return false;
            }
        });
    }
    
    
    public View getDivider() {
        return mDivider;
    }
    
    protected void switchToLightTheme() {
        tvTitle.setTextColor(mLightStyleSpec.getTitleTextColor());
        
        btBackToHome.setTextColor(StateListUtils.getStateColor(mLightStyleSpec.getHomeButtonColor()));
        
    }
    
    protected void switchToDarkTheme() {
        tvTitle.setTextColor(mDarkStyleSpec.getTitleTextColor());
        
        btBackToHome.setTextColor(StateListUtils.getStateColor(mDarkStyleSpec.getHomeButtonColor()));
        
        
    }
    
    public void onRelease() {
        btIconList.clear();
    }
    
    
    /***
    * 打開沉浸式狀態(tài)欄支持
    */
    @Override
    public void setStatusBarColor(int color) {
        if (StatusBarUtils.isSupport()) {
            int statusBarHeight = StatusBarUtils.getStatusBarHeight(mContext);
            
            if (statusBarHeight == 0) { //保護(hù),萬一有rom沒辦法拿到狀態(tài)欄高度的話,則在這里不生效。
                return;
            }
            LinearLayout.LayoutParams layoutParams =
                (LinearLayout.LayoutParams) statusBarAdjustView.getLayoutParams();
            layoutParams.height = statusBarHeight;
            statusBarAdjustView.setLayoutParams(layoutParams);
            statusBarAdjustView.setVisibility(View.VISIBLE);
            
            try {
                StatusBarUtils.setTransparentColor((Activity) mContext, color);
            } catch (Exception e) {
                RVLogger.e(TAG, e);
            }
        }
    }
    
    @Override
    public void setBackgroundColor(int color) {
        contentView.getContentBgView().setColor(color);
    }
    
    @Override
    public void setAlpha(int alpha, boolean titleTextAlphaEnabled) {
        contentView.getContentBgView().setAlpha(alpha);
        if (titleTextAlphaEnabled) {
            tvTitle.setAlpha(alpha);
        }
    }
    
    @Override
    public void setOptionMenu(Bitmap bitmap) {
        visibleOptionNum = 2;
        setButtonIcon(bitmap, 1);
    }
    
    @Override
    public void setTitleImage(Bitmap image, String contentDesc) {
        if (!TextUtils.isEmpty(contentDesc)) {
            ivImageTitle.setContentDescription(contentDesc);
        }
        if (image != null) {
            RVLogger.d(TAG, "imgTitle width " + image.getWidth() + ", imgTitle height " + image
                       .getHeight());
            ivImageTitle.setImageBitmap(image);
            ivImageTitle.setVisibility(View.VISIBLE);
            tvTitle.setVisibility(View.GONE);
            RVLogger.d(TAG, "ivImageTitle width " + ivImageTitle
                       .getWidth() + ", ivImageTitle height " + ivImageTitle.getHeight());
        }
    }
    
    @Override
    public void setTitlePenetrate(boolean enable) {
        contentView.setPreventTouchEvent(!enable);
    }
    
    @Override
    public void applyTheme(TitleBarTheme theme) {
        if (theme == TitleBarTheme.DARK) {
            switchToDarkTheme();
        } else if (theme == TitleBarTheme.LIGHT) {
            switchToLightTheme();
        }
    }
}

自定義小程序加載動(dòng)畫

Mriver.setProxy(SplashViewFactoryProxy.class, new SplashViewFactoryProxy() {

                @Override
                public ISplashView createSplashView(Context context) {
                    return new CustomLoadingView(context);
                }
            });

public class CustomLoadingView extends FrameLayout implements ISplashView {

    private static final String TAG = "CustomLoadingView";

    private static final int defaultAlphaColor = 855638016;//Color.argb(51, 0, 0, 0);//默認(rèn)透明色
    private static final long TIME_DELAY_FOR_SHOW_PERCENTAGE = 2000;//展示百分的延遲時(shí)間2s

    public final static String MSG_UPDATE_APPEARANCE = "UPDATE_APPEARANCE";
    public final static String DATA_UPDATE_APPEARANCE_BG_COLOR = "UPDATE_APPEARANCE_BG_COLOR"; //頁(yè)面背景色 #RGB
    public final static String DATA_UPDATE_APPEARANCE_LOADING_ICON = "UPDATE_APPEARANCE_LOADING_ICON"; //loading圖標(biāo) Drawable
    public final static String DATA_UPDATE_APPEARANCE_LOADING_TEXT = "UPDATE_APPEARANCE_LOADING_TEXT"; //loading文案
    public final static String DATA_UPDATE_APPEARANCE_LOADING_TEXT_COLOR = "UPDATE_APPEARANCE_LOADING_TEXT_COLOR"; //loading文案顏色 #RGB
    public final static String DATA_UPDATE_APPEARANCE_LOADING_BOTTOM_TIP = "UPDATE_APPEARANCE_LOADING_BOTTOM_TIP"; //底部提示文案

    public final static String ANIMATION_STOP_LOADING_PREPARE = "ANIMATION_STOP_LOADING_PREPARE";

    private Context mContext;

    protected ImageView mLoadingIcon;
    protected TextView mLoadingTitle;
    protected TextView mLoadingPercentTip;
    protected TextView mBottomTip;
    protected TextView mBackButton;

    private Paint mDotPaint;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private boolean mPlayingStartAnim;
    private int mDarkDotX;
    private int mDarkDotY;
    private int mDarkGap;
    private int mDotSize;
    private int mLightDotIndex = 0;
    private int mPercentValue;
    private long mStartLoadingTime = 0;

    private OnCancelListener onCancelListener;
    private Activity hostActivity;

    public interface OnCancelListener {
        void onCancel();
    }

    public CustomLoadingView(Context context) {
        this(context, null);
    }

    public CustomLoadingView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomLoadingView(final Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;

        hostActivity = (Activity) context;

        initView();

        mBackButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                cancel();
                if (context instanceof Activity) {
                    RVLogger.d(TAG, "user want close app when splash loading");
                    ((Activity) context).finish();
                }
            }
        });
    }

    public final void cancel() {
        if (this.onCancelListener != null) {
            this.onCancelListener.onCancel();
        }

    }

    public void initView() {
        mLoadingIcon = new ImageView(mContext);
        mLoadingIcon.setScaleType(ImageView.ScaleType.FIT_XY);
        mLoadingIcon.setImageResource(R.drawable.ic_launcher_foreground);
        mLoadingTitle = new TextView(mContext);
        mLoadingTitle.setGravity(Gravity.CENTER);
        mLoadingTitle.setTextColor(Color.BLACK);
        mLoadingTitle.setSingleLine();
        mLoadingTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        mLoadingTitle.setEllipsize(TextUtils.TruncateAt.END);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLoadingTitle.setLayoutParams(lp);
        addView(mLoadingIcon);
        addView(mLoadingTitle);

        mBackButton = new TextView(mContext);
        mBackButton.setGravity(Gravity.CENTER);
        addView(mBackButton);

        // 加載百分比
        mPercentValue = 0;
        mLoadingPercentTip = new TextView(mContext);
        mLoadingPercentTip.setGravity(Gravity.CENTER);
        mLoadingPercentTip.setSingleLine();
        mLoadingPercentTip.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
        mLoadingPercentTip.setEllipsize(TextUtils.TruncateAt.END);
        lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLoadingPercentTip.setLayoutParams(lp);
        mLoadingPercentTip.setText("");
        addView(mLoadingPercentTip);

        mBottomTip = new TextView(mContext);
        mBottomTip.setTextSize(12);
        mBottomTip.setGravity(Gravity.CENTER);
        lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mBottomTip.setLayoutParams(lp);
        addView(mBottomTip);

        mDotSize = 30;
        mDotPaint = new Paint();
        mDotPaint.setStyle(Paint.Style.FILL);
        mDarkGap = 10;

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int size = 150;
        mLoadingIcon.measure(makeMeasureSpec(size), makeMeasureSpec(size));

        int height = 200;
        int width = 500;
        mLoadingTitle.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), makeMeasureSpec(height));

        height = 200;
        width = 500;
        mLoadingPercentTip.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), makeMeasureSpec(height));

        width = 200;
        height = 100;
        mBottomTip.measure(makeMeasureSpec(width), MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));

        width = 200;
        height = 200;
        mBackButton.measure(makeMeasureSpec(width), makeMeasureSpec(height));

        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        int offsetX = 0;
        int offsetY = 0;

        mBackButton.layout(offsetX, offsetY, mBackButton.getMeasuredWidth(), mBackButton.getMeasuredHeight() + offsetY);

        offsetX = (getMeasuredWidth() - mLoadingIcon.getMeasuredWidth()) / 2;
        mLoadingIcon.layout(offsetX, offsetY, offsetX + mLoadingIcon.getMeasuredWidth(),
                offsetY + mLoadingIcon.getMeasuredHeight());

        offsetX = (getMeasuredWidth() - mLoadingTitle.getMeasuredWidth()) / 2;
        offsetY = offsetY + mLoadingIcon.getMeasuredHeight();
        mLoadingTitle.layout(offsetX, offsetY, offsetX + mLoadingTitle.getMeasuredWidth(),
                offsetY + mLoadingTitle.getMeasuredHeight());

        mDarkDotX = getMeasuredWidth() / 2 - mDotSize - mDarkGap;
        mDarkDotY = offsetY + mLoadingTitle.getMeasuredHeight();

        offsetX = (getMeasuredWidth() - mLoadingPercentTip.getMeasuredWidth()) / 2;
        offsetY = offsetY + mLoadingPercentTip.getMeasuredHeight();
        mLoadingPercentTip.layout(offsetX, offsetY, offsetX + mLoadingPercentTip.getMeasuredWidth(),
                offsetY + mLoadingPercentTip.getMeasuredHeight());

        offsetX = (getMeasuredWidth() - mBottomTip.getMeasuredWidth()) / 2;
        offsetY = getMeasuredHeight() - mBottomTip.getMeasuredHeight();
        mBottomTip.layout(offsetX, offsetY, offsetX + mBottomTip.getMeasuredWidth(), offsetY + mBottomTip.getMeasuredHeight());
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (mPlayingStartAnim) {
            mDotPaint.setColor(Color.BLACK);
            mDarkDotX = getMeasuredWidth() / 2 - mDotSize - mDarkGap;
            for (int i = 0; i < 3; i++) {
                mDotPaint.setColor(mLightDotIndex == i ? Color.WHITE : Color.BLACK);
                canvas.drawCircle(mDarkDotX, mDarkDotY, mDotSize / 2, mDotPaint);
                mDarkDotX = mDarkDotX + mDarkGap + mDotSize;
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        super.onTouchEvent(ev);
        return true;
    }

    public void startLoadingAnimation() {
        if (mPlayingStartAnim) return;
        mPlayingStartAnim = true;

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    mLightDotIndex++;
                    if (mLightDotIndex > 2) {
                        mLightDotIndex = 0;
                    }
                    ExecutorUtils.runOnMain(new Runnable() {
                        @Override
                        public void run() {
                            invalidate();
                            // 更新百分比的值
                            if (isCanShowPercentage()) {
                                if (mPercentValue == 0) {
                                    mPercentValue = 52;
                                } else if (mPercentValue < 99) {
                                    mPercentValue++;
                                }
                                mLoadingPercentTip.setText(String.format("%d%%", mPercentValue));
                            }

                        }
                    });
                }
            };
        }

        if (mTimer == null) {
            try {
                mTimer = new Timer();
                mTimer.schedule(mTimerTask, 0, 200);
            } catch (Throwable throwable) {
                RVLogger.e(TAG, "printMonitor error", throwable);
            }
        }

        RVLogger.d(TAG, "SplashLoadingView... startLoading Animation");
    }

    public void stopLoadingAnimation() {
        mPlayingStartAnim = false;

        if (mTimer != null) {
            mTimer.cancel();
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
        }
        invalidate();

        RVLogger.d(TAG, "SplashLoadingView... stopLoading Animation");
    }

    private int getDimen(int id) {
        return mContext.getResources().getDimensionPixelSize(id);
    }

    private int makeMeasureSpec(int size) {
        return MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
    }

    public void onStart() {
        updateStatusBar();
        startLoadingAnimation();
    }

    public void onStop() {
        stopLoadingAnimation();
        mLoadingPercentTip.setVisibility(GONE);
        RVLogger.d(TAG, "SplashLoadingView... stop");
    }

    @Override
    public void onFail() {
        onStop();
        Map<String, Object> msgData = new HashMap<>();
        msgData.put(CustomLoadingView.DATA_UPDATE_APPEARANCE_LOADING_BOTTOM_TIP, "");
        sendMessage(CustomLoadingView.MSG_UPDATE_APPEARANCE, msgData);
    }

    public void onHandleMessage(String msg, Map<String, Object> data) {
        if (MSG_UPDATE_APPEARANCE.equals(msg)) {

            String bgColor = (String) data.get(DATA_UPDATE_APPEARANCE_BG_COLOR);
            if (!TextUtils.isEmpty(bgColor)) {
                setBackgroundColor(Color.parseColor(bgColor));
            }

            Drawable loadingIcon = (Drawable) data.get(DATA_UPDATE_APPEARANCE_LOADING_ICON);
            if (loadingIcon != null) {
                mLoadingIcon.setImageDrawable(loadingIcon);
            }

            String text = (String) data.get(DATA_UPDATE_APPEARANCE_LOADING_TEXT);
            if (text != null) {
                mLoadingTitle.setText(text);
            }

            String textColor = (String) data.get(DATA_UPDATE_APPEARANCE_LOADING_TEXT_COLOR);
            if (!TextUtils.isEmpty(textColor)) {
                mLoadingTitle.setTextColor(Color.parseColor(textColor));
            }

            String bottomTip = (String) data.get(DATA_UPDATE_APPEARANCE_LOADING_BOTTOM_TIP);
            if (bottomTip != null) {
                mBottomTip.setText(bottomTip);
            }
        }
    }

    public void performAnimation(final String animationType, final Animator.AnimatorListener animationListener) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            doPerformAnimation(animationType, animationListener);
        } else {
            post(new Runnable() {
                @Override
                public void run() {
                    doPerformAnimation(animationType, animationListener);
                }
            });
        }
    }

    private void doPerformAnimation(final String animationType, final Animator.AnimatorListener animationListener) {

        if (getParent() == null) {
            RVLogger.e(TAG, "loading view has not added to parent container");
            return;
        }

        if (ANIMATION_STOP_LOADING_PREPARE.equals(animationType)) {
            mPlayingStartAnim = false;

            int offsetTargetY = 0;
            float titleTargetX = 0f;
            if (isBackButtonVisible()) {
                titleTargetX = mBackButton.getX() + mBackButton.getMeasuredWidth();
            } else {
                titleTargetX = getTitleLeftMargin();
            }
            float titleTargetY = (200 - mLoadingTitle.getMeasuredHeight()) / 2;

            AnimatorSet prepareStopLoadingAnimator = new AnimatorSet();
            prepareStopLoadingAnimator.setDuration(400);
            if (animationListener != null) {
                prepareStopLoadingAnimator.addListener(animationListener);
            }
            prepareStopLoadingAnimator.play(ObjectAnimator.ofFloat(mLoadingIcon, "y", mLoadingIcon.getY(), offsetTargetY))
                    .with(ObjectAnimator.ofFloat(mLoadingIcon, "scaleX", mLoadingIcon.getScaleX(), 0))
                    .with(ObjectAnimator.ofFloat(mLoadingIcon, "scaleY", mLoadingIcon.getScaleY(), 0))
                    .with(ObjectAnimator.ofFloat(mLoadingTitle, "x", mLoadingTitle.getX(), titleTargetX))
                    .with(ObjectAnimator.ofFloat(mLoadingTitle, "y", mLoadingTitle.getY(), titleTargetY));

            prepareStopLoadingAnimator.start();
        } else {
            performAnimation(animationType, animationListener);
        }
    }

    @Override
    public void updateLoadingInfo(EntryInfo entryInfo) {
        Map<String, Object> msgData = new HashMap<>();
        msgData.put(CustomLoadingView.DATA_UPDATE_APPEARANCE_LOADING_TEXT, entryInfo.title);

        sendMessage(CustomLoadingView.MSG_UPDATE_APPEARANCE, msgData);

        H5ImageUtil.loadImage(entryInfo.iconUrl, null, new H5ImageListener() {
            @Override
            public void onImage(Bitmap bitmap) {
                RVLogger.d(TAG, "onBitmapLoaded!");
                Map<String, Object> msgData = new HashMap<>();
                int dimen = 100;
                Bitmap displayBitmap = ImageUtil.scaleBitmap(bitmap, dimen, dimen);
                msgData.put(CustomLoadingView.DATA_UPDATE_APPEARANCE_LOADING_ICON, new BitmapDrawable(displayBitmap));
                sendMessage(CustomLoadingView.MSG_UPDATE_APPEARANCE, msgData);
            }
        });
    }

    @Override
    public View getView() {
        return this;
    }

    @Override
    public void onExit() {
        performAnimation(CustomLoadingView.ANIMATION_STOP_LOADING_PREPARE, new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                RVLogger.d(TAG, "onAnimationStart");
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                RVLogger.d(TAG, "onAnimationEnd");
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                RVLogger.d(TAG, "onAnimationCancel");
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }


    private void updateStatusBar() {
        if (hostActivity != null && hostActivity.getClass().getName().equals("com.alipay.mobile.core.loading.impl.LoadingPage")) {
            StatusBarUtils.setTransparentColor(hostActivity, defaultAlphaColor);
        }
    }

    protected boolean isBackButtonVisible() {
        return true;
    }

    protected float getTitleLeftMargin() {
        return 0f;
    }

    private boolean isCanShowPercentage() {
        if (mStartLoadingTime == 0) {
            mStartLoadingTime = System.currentTimeMillis();
        }
        long time = System.currentTimeMillis();
        return ((time - mStartLoadingTime) > TIME_DELAY_FOR_SHOW_PERCENTAGE);
    }

    public final void sendMessage(final String msg, final Map<String, Object> data) {
        this.post(new Runnable() {
            public void run() {
                try {
                    CustomLoadingView.this.onHandleMessage(msg, data);
                } catch (Throwable e) {
                    RVLogger.e(TAG, e);
                }

            }
        });
    }
}

支持調(diào)試面板功能

// Mriver 初始化完成時(shí)調(diào)用,默認(rèn)只有預(yù)覽和真機(jī)調(diào)試小程序才顯示
MriverEngine.enableDebugConsole();

// 強(qiáng)制所有小程序顯示調(diào)試面板
Mriver.setConfig("mriver_show_debug_menu_all", "YES");

自定義更多菜單欄

Mriver.setProxy(MRTinyMenuProxy.class, new MRTinyMenuProxy() {
                @Override
                public ITinyMenuPopupWindow createTinyMenuPopupWindow(Context context, TinyMenuViewModel tinyMenuViewModel) {
                    return new DemoTinyMenuPopupWindow(context, tinyMenuViewModel);
                }
            });

// DemoTinyMenuPopupWindow 實(shí)現(xiàn)參考內(nèi)部的 TinyMenuModalWindow

監(jiān)聽攔截返回

Mriver.setConfig("enable_back_perform", "YES");
List<String> tt = new ArrayList<String>();
tt.add(BackInterceptPoint.class.getName());// 接口 類名
Mriver.registerPoint(DemoBackInterceptPointProviderImp.class.getName(), tt);


public class DemoBackInterceptPointProviderImp implements BackInterceptPoint {

    @Override
    public boolean intercepted(final Render render, int i, CommonBackPerform.BackHandler backHandler, GoBackCallback goBackCallback) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(render.getActivity(), "返回鍵" ,Toast.LENGTH_LONG).show();
            }
        });
        return false; // true表示攔截
    }

    @Override
    public void onInitialized() {
        Log.i("BackPoint", "BackInterceptPoint--onInitialized--:");
    }

    @Override
    public void onFinalized() {
        Log.i("BackPoint", "BackInterceptPoint--onFinalized--:");
    }
}

監(jiān)聽攔截關(guān)閉

Mriver.setProxy(AppCloseInterceptProxy.class, new AppCloseInterceptProxy() {
 @Override
 public boolean intercept(Context context, Page page) {
 showToast("關(guān)閉鍵");
 return false; // true表示攔截
 }
});

自定義 appx loading 動(dòng)畫(僅支持 GIF)

在小程序 mini.project.json 文件中添加 "nonLoadingIndicator": false 。

代碼示例如下:

Mriver.registerPoint(MriverResourceInterceptor.class.getName(),
                    Arrays.asList("com.alibaba.ariver.resource.api.extension.ResourceInterceptPoint"));
            Mriver.setConfig("mriver_custom_appxloading", CUSTOM_LOADING_RESOURCE);
						// loading的大小:占屏幕寬度的比例,20表示loading控件大小為屏幕寬度的20%
            Mriver.setConfig("mriver_custom_appxloading_size", "20");
            ResourcePackage resourcePackage = new GlobalResourcePackage("00000001") {
                @Override
                protected boolean needWaitSetupWhenGet() {
                    return false;
                }

                @Override
                public boolean needWaitForSetup() {
                    return false;
                }

                @Override
                protected boolean canHotUpdate(String hotVersion) {
                    return false;
                }

                @Override
                public Resource get(ResourceQuery query) {
                  	// 可以攔截所有資源
                    if (TextUtils.equals(CUSTOM_LOADING_RESOURCE, query.pureUrl)) {
                        return getPresetImageResource(UIStyleActivity.this, query);
                    }
                    return null;
                }
            };
GlobalPackagePool.getInstance().add(resourcePackage);

private Resource getPresetImageResource(Context application, ResourceQuery query) {

    Resource sResource = null;
    if (sResource == null) {

        InputStream inputStream = null;
        AssetManager am = application.getAssets();
        try {
            inputStream = am.open("preset/custom_loading.gif");
            int length = inputStream.available();
            byte[] buffer = new byte[length];
            inputStream.read(buffer);
            sResource = new OfflineResource(query.pureUrl, buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        }
    }
    return sResource;
}

資源管理

// 主動(dòng)刪除本地小程序
MriverResource.deleteApp("xxxx");

// 獲取所有小程序信息列表
Map<String, List<AppModel>> allApp = MriverResource.getAllApp();

// 主動(dòng)更新所有
MriverResource.updateAll(new UpdateAppCallback() {
                @Override
                public void onSuccess(List<AppModel> list) {

                    showToast("userid能拉到的所有信息小程序更新成功");
                }

                @Override
                public void onError(UpdateAppException e) {
                    showToast(e.getMessage());
                }
            });

// 主動(dòng)更新特定小程序
Map<String, String> updateApp = new HashMap<>();
            updateApp.put("xxx", "");
            MriverResource.updateApp(updateApp, new UpdateAppCallback() {
                @Override
                public void onSuccess(List<AppModel> list) {
                    showToast("appid=2021042520210425的小程序更新成功");
                }

                @Override
                public void onError(UpdateAppException e) {
                    showToast(e.getMessage());
                }
            });

// 主動(dòng)下載小程序
MriverResource.downloadAppPackage("xxx", new PackageDownloadCallback() {
                @Override
                public void onPrepare(String s) {
                    //做一些輔助的工作如可以打個(gè)日志
                }

                @Override
                public void onProgress(String s, int i) {
                    //進(jìn)度
                    showToast("i=" + i);
                }

                @Override
                public void onCancel(String s) {
                    //用戶不用關(guān)心。取消是內(nèi)部網(wǎng)絡(luò)庫(kù)的取消api
                }

                @Override
                public void onFinish(String s) {
                    showToast(s);
                }

                @Override
                public void onFailed(String s, int i, String s1) {
                    showToast("onFailed--" + s);
                }
            });

預(yù)置小程序

  • 將小程序 .amr 包和小程序信息放到 assets/mriver/legacy 目錄即可。

    重要

    文件名規(guī)則為:appId.amr,不要帶版本號(hào)。

    image.png

    小程序信息放到 nebula_preset.json 里,參考如下:

    {
    	"config":{
    		"updateReqRate":16400,
    		"limitReqRate":13600,
    		"appPoolLimit":3,
    		"versionRefreshRate":86400
    	},
    	"data":[
    		{
    			"app_desc":"預(yù)置小程序",
    			"app_id":"2022080915350001",
    			"auto_install":1,
    			"extend_info":{
    				"launchParams":{
    					"enableTabBar":"YES",
    					"enableKeepAlive":"NO",
    					"enableDSL":"YES",
    					"nboffline":"sync",
    					"enableWK":"YES",
    					"page":"page/tabBar/component/index",
    					"tinyPubRes":"YES",
    					"enableJSC":"YES"
    				},
    				"usePresetPopmenu":"YES"
    			},
    			"fallback_base_url":"https://xxx/2022080915350001/1.0.1.0_all/nebula/fallback/",
    			"global_pack_url":"",
    			"installType":1,
    			"main_url":"/index.html#page/tabBar/component/index",
    			"name":"預(yù)置小程序",
    			"online":1,
    			"package_url":"https://xxx/2022080915350001/1.0.1.0_all/nebula/2022080915350001_1.0.1.0.amr",
    			"patch":"",
    			"sub_url":"",
    			"version":"1.0.1.0",
    			"vhost":"https://2022080915350001.h5app.com"
    		}
    	],
    	"resultCode":100,
    	"resultMsg":"操作成功",
    	"state":"success"
    }
  • 如需提前安裝,參考如下代碼。

    private void checkPresetInstalled() {
            Map<String, AppModel> appModelMap = RVProxy.get(RVResourcePresetProxy.class).getPresetAppInfos();
            Map<String, RVResourcePresetProxy.PresetPackage> packageMap = RVProxy.get(RVResourcePresetProxy.class).getPresetPackage();
            Set<String> stringSet = packageMap.keySet();
            for (String key: stringSet) {
                RVResourcePresetProxy.PresetPackage presetPackage = packageMap.get(key);
                AppModel presetModel = appModelMap.get(key);
                if (presetModel != null && presetPackage != null && presetPackage.getInputStream() != null) {
                    AppModel appModel = MriverResource.getAppModel(presetModel.getAppId());
                    boolean available = ((RVResourceManager)RVProxy.get(RVResourceManager.class)).isAvailable(appModel);
                    if (!available) {
                        if (TextUtils.equals(appModel.getAppVersion(), presetModel.getAppVersion())) {
                            InternalUtils.installApp(presetModel, presetPackage.getInputStream());
                        } else {
                            // 決定是否提前安裝線上版本
                        }
                    }
    
                }
            }
        }

資源加載攔截

ResourcePackage resourcePackage = new GlobalResourcePackage("00000001") {
                @Override
                protected boolean needWaitSetupWhenGet() {
                    return false;
                }

                @Override
                public boolean needWaitForSetup() {
                    return false;
                }

                @Override
                protected boolean canHotUpdate(String hotVersion) {
                    return false;
                }

                @Override
                public Resource get(ResourceQuery query) {
                  	// 可以攔截所有資源
                    if (TextUtils.equals("指定資源路徑", query.pureUrl)) {
                        return getLocalResource(UIStyleActivity.this, query);
                    }
                    return null;
                }
            };
GlobalPackagePool.getInstance().add(resourcePackage);

簽名校驗(yàn)

// 開啟簽名
MriverResource.enableVerify(MriverResource.VERIFY_TYPE_YES,"公鑰");

// 關(guān)閉簽名
MriverResource.disableVerify( );

開啟?;?/b>

Mriver.setConfig("enable_keep_alive", "YES");
Mriver.setConfig("mriver_keep_alive_time", "120000"); // ?;顣r(shí)間2分鐘
Mriver.setConfig("mriver_keepalive_max", "3"); // 最大?;顐€(gè)數(shù)3

Android 小程序保活基于 Activity Task Stack 實(shí)現(xiàn),如果小程序存在跳轉(zhuǎn)原生頁(yè)面(例如登錄)或者其他 App 頁(yè)面(例如三方支付、分享等)時(shí),需要注意:

  • 如果和小程序頁(yè)面在同個(gè)一個(gè)棧里不會(huì)存在風(fēng)險(xiǎn)。

  • 如果這些頁(yè)面是單獨(dú)的 activity stack,可能會(huì)影響返回棧順序,需要回歸相關(guān)邏輯。

默認(rèn)情況下,保活喚醒時(shí)如果指定了頁(yè)面,并且指定的頁(yè)面并不是小程序當(dāng)前頁(yè),喚醒時(shí)會(huì)刷新成指定頁(yè)面。

可以通過設(shè)置 refererBiz 參數(shù)忽略刷新,直接喚起當(dāng)前頁(yè):

 Bundle intent  = new Bundle();
intent.putString("page", "page/component/view/view");
intent.putString("refererBiz", "home");
Mriver.startApp(appId, intent);
說明
  • 如果 refererBiz 值固定為 home,保活喚醒時(shí)會(huì)忽略指定的頁(yè)面。如果沒有已?;畹男〕绦?,則會(huì)打開指定頁(yè)面。

  • 如果 refererBiz 值為其他(業(yè)務(wù)自定義即可),?;顔拘褧r(shí)會(huì)和上一次打開的 referer 值對(duì)比,如果一致會(huì)忽略指定的頁(yè)面。 如果沒有已保活的小程序,則會(huì)打開指定頁(yè)面。

啟動(dòng)指定版本小程序

MriverResource.deleteApp("2022080918000001"); // 刪除本地小程序

Bundle bundle = new Bundle();
bundle.putString(RVStartParams.LONG_NB_TARGET_VERSION, "指定版本號(hào)");
Mriver.startApp(TargetVersionActivity.this, "2022080918000001", bundle);

自定義 JSAPI

// 自定義tinyToNative的jsapi
MriverEngine.registerBridge(CustomApiBridgeExtension.class);


public class CustomApiBridgeExtension extends SimpleBridgeExtension {

    private static final String TAG = "CustomApiBridgeExtension";

    @ActionFilter
    public void tinyToNative(@BindingId String id,
                             @BindingNode(App.class) App app,
                             @BindingNode(Page.class) Page page,
                             @BindingApiContext ApiContext apiContext,
                             @BindingExecutor(ExecutorType.UI) Executor executor,
                             @BindingRequest JSONObject params,
                             @BindingParam("param1") String param1,
                             @BindingParam("param2") String param2,
                             @BindingCallback BridgeCallback callback) {
        RVLogger.d(TAG, "id: "+id+
                "\napp: "+app.toString()+
                "\npage: "+page.toString()+
                "\napiContext: "+apiContext.toString()+
                "\nexecutor: "+executor.toString());
        RVLogger.d(TAG, JSONUtils.toString(params));
        JSONObject result = BridgeResponse.SUCCESS.get();
        //result.put("message", "客戶端接收到參數(shù):" + param1 + ", " + param2 + "\n返回 Demo 當(dāng)前包名:" + apiContext.getActivity().getPackageName());
        // 將結(jié)果返回給小程序
        Stack stack = MriverApp.getAppStack();
        Enumeration enumerationLists = stack.elements();

        JSONArray jsonArray = new JSONArray();
        while (enumerationLists.hasMoreElements()) {
            JSONObject jsonObject = new JSONObject();
            MRApp o = (MRApp) enumerationLists.nextElement();
            jsonObject.put("AppId", o.getAppId());
            jsonObject.put("AppVersion", o.getAppVersion());
            jsonArray.add(jsonObject);
        }
        String tinyappStr = jsonArray.toJSONString();
        // result.put("message", "客戶端接收到參數(shù):" + param1 + ", " + param2 + "\n返回 Demo 當(dāng)前包名:" + apiContext.getActivity().getPackageName());
        result.put("message", tinyappStr);
        callback.sendJSONResponse(result);
    }

}

開啟分享功能

Mriver.setConfig("mr_showShareMenuItem", "YES");

// 實(shí)現(xiàn)ShareApiBridgeExtension
public class ShareApiBridgeExtension extends SimpleBridgeExtension {
    private static final String TAG = "CustomApiBridgeExtension";

    @ActionFilter
    public void shareTinyAppMsg(@BindingId String id,
                                @BindingNode(App.class) App app,
                                @BindingNode(Page.class) Page page,
                                @BindingApiContext ApiContext apiContext,
                                @BindingExecutor(ExecutorType.UI) Executor executor,
                                @BindingRequest JSONObject params,
                                final @BindingCallback BridgeCallback callback) {
        Log.i("ShareApiBridge", "share: " + (params == null ? "null" : params.toJSONString()));


        String title = params.getString("title");


        String desc = params.getString("desc");


        String myprop = params.getString("myprop");


        String path = params.getString("page");


        String appId = app.getAppId();




        // 此處可調(diào)用分享組件,實(shí)現(xiàn)后續(xù)功能


        String message = "應(yīng)用ID: " + appId + "\n"


            + "title: " + title + "\n"


            + "desc: " + desc + "\n"


            + "myprop: " + myprop + "\n"


            + "path: " + path + "\n";




        AUNoticeDialog dialog = new AUNoticeDialog(apiContext.getActivity(),


            "分享結(jié)果", message, "分享成功", "分享失敗");


        dialog.setPositiveListener(new AUNoticeDialog.OnClickPositiveListener() {


            @Override


            public void onClick() {


                JSONObject result = BridgeResponse.SUCCESS.get();


                result.put("success", true);


                callback.sendJSONResponse(result);


            }


        });


        dialog.setNegativeListener(new AUNoticeDialog.OnClickNegativeListener() {


            @Override


            public void onClick() {

                callback.sendBridgeResponse(BridgeResponse.newError(11, "分享失敗"));


            }


        });


        dialog.show();
    }
}

權(quán)限彈窗

// 自定義權(quán)限管控提醒的彈窗
Mriver.setProxy(LocalPermissionDialogProxy.class, new LocalPermissionDialogProxy() {
                    @Override
                    public LocalPermissionDialog create(Context context) {
                        return new DemoLocalPermissionDialog(context);
                    }

                    @Override
                    public boolean interceptPermission(String appId, String page, String action, String scope, List<String> permissions) {
                        showToast("jsapi: " + action + " 小程序:"+appId+" 頁(yè)面:"+page);
                        return false;
                    }

                });
// 彈窗示例
public class DemoLocalPermissionDialog implements LocalPermissionMultiDialog {
    private Dialog mDialog;
    private final Context mContext;
    private PermissionPermitListener mPermissionPermitListener;

    public DemoLocalPermissionDialog(Context context) {
        this.mContext = context;
    }

	public void setExtData(String[] permissions, AppModel appModel, Page page, String action, String scope) {
  	 // 支持根據(jù)這些參數(shù)自定義能力,包括多級(jí)彈窗、自定義文案樣式等
     // permissions: 當(dāng)前action需要的所有權(quán)限列表
     // appModel: 當(dāng)前action的appModel,能取到小程序定義的相關(guān)文案
     // action: 對(duì)應(yīng)jsapi的action
     // scope: 對(duì)應(yīng)jsapi的scope
	}

    public void setDialogContent(String content, String title, String icon) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.mContext);
        builder.setTitle("權(quán)限彈窗");
        builder.setMessage(content);
        builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface pDialogInterface, int pI) {
                if (DemoLocalPermissionDialog.this.mPermissionPermitListener != null) {
                    DemoLocalPermissionDialog.this.mPermissionPermitListener.onSuccess();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface pDialogInterface, int pI) {
                if (DemoLocalPermissionDialog.this.mPermissionPermitListener != null) {
                    DemoLocalPermissionDialog.this.mPermissionPermitListener.onFailed(-1, "", true);
                }
            }
        });
        this.mDialog = builder.create();
        this.mDialog.show();
    }

    public void setPermissionPermitListener(PermissionPermitListener permissionPermitListener) {
        this.mPermissionPermitListener = permissionPermitListener;
    }

    public void show() {
        if (this.mDialog != null && this.mContext instanceof Activity && !((Activity)this.mContext).isFinishing()) {
            this.mDialog.show();
        }

    }

說明

增加 setExtData 支持權(quán)限彈窗更多能力。

自定義 View

  1. 升級(jí) appx 到 2.7.18 版本。

    api ('com.mpaas.mriver:mriverappxplus-build:2.7.18.20220825001@aar') {
        force=true
    }
  2. 調(diào)用相關(guān) API。

    RVProxy.set(RVEmbedProxy.class, new RVEmbedProxy() {
    
                    @Override
                    public Class<?> getEmbedViewClass(String type) {
                        if ("custom_barrage".equalsIgnoreCase(type)) {
                            // type需要和小程序端的type一一對(duì)應(yīng),根據(jù)type返回對(duì)應(yīng)的自定義View
                            return EmbedCustomView.class;
                        }
                        return null;
                    }
                });
  3. 實(shí)現(xiàn)自定義 View。

    package com.mpaas.demo.tinyapp.engine;
    
    import android.content.Context;
    import android.text.TextUtils;
    import android.util.Log;
    import android.view.View;
    import android.widget.FrameLayout;
    
    import com.alibaba.ariver.app.api.Page;
    import com.alibaba.ariver.engine.api.bridge.extension.BridgeCallback;
    import com.alibaba.ariver.engine.api.bridge.extension.BridgeResponse;
    import com.alibaba.ariver.engine.api.embedview.IEmbedView;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.alipay.mobile.beehive.video.h5.live.MRLivePlayerHelper;
    import com.mpaas.mriver.integration.embed.IMREmbedView;
    
    import java.util.Map;
    
    public class EmbedCustomView implements IMREmbedView {
        private Context mContext;
        private Page mPage;
        private CustomBarrageView mCustomBarrageView; // 彈幕view示例
    
        @Override
        public void onCreate(Context context, Page page, IEmbedView iEmbedView) {
            mContext = context;
            mPage = page;
        }
    
        @Override
        public View getView(int width, int height, final String viewId, String type, Map<String, String> params) {
            Log.i("EmneCustomV", "getView: " + mCustomBarrageView + " " + viewId + " " + type + " " + params);
            if (mCustomBarrageView == null) {
                mCustomBarrageView = new CustomBarrageView(mContext);
            }
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
            mCustomBarrageView.setLayoutParams(layoutParams);
            return mCustomBarrageView;
        }
    
        // 收到小程序端發(fā)送的數(shù)據(jù)
        @Override
        public void onReceivedMessage(String actionType, JSONObject data, BridgeCallback bridgeCallback) {
            Log.i("EmneCustomV", "onReceivedMessage: " +  actionType);
            if ("mpaasCustomEvent".equalsIgnoreCase(actionType)) {
                String innerAction = data.getString("actionType");
                if (TextUtils.equals(innerAction, "bindLivePlayer")) {
                    JSONObject dataJSON = data.getJSONObject("data");
    
                    // 設(shè)置彈幕數(shù)據(jù)
                    JSONArray barrages = dataJSON.getJSONArray("barrages");
                    mCustomBarrageView.setData(barrages);
    
                    // 綁定liveplayer
                    String bindId = dataJSON.getString("id");
                    if (!TextUtils.isEmpty(bindId)) {
                        MRLivePlayerHelper.bind(bindId, mCustomBarrageView);
                    }
                }
    
            }
        }
    
        protected void notifySuccess(final BridgeCallback bridgeContext) {
            if (bridgeContext != null) {
                bridgeContext.sendBridgeResponse(BridgeResponse.SUCCESS);
            }
        }
    
        
        @Override
        public void onReceivedRender(JSONObject params, BridgeCallback bridgeCallback) {
            Log.i("EmneCustomV", "onReceivedRender: " +  params);
            notifySuccess(bridgeCallback);
        }
    
        @Override
        public void onWebViewResume() {
    
        }
    
        @Override
        public void onWebViewPause() {
    
        }
    
        @Override
        public void onAttachedToWebView() {
    
        }
    
        @Override
        public void onDetachedToWebView() {
    
        }
    
        @Override
        public void onDestroy() {
    
        }
    
        @Override
        public void onRequestPermissionResult(int i, String[] strings, int[] ints) {
    
        }
    
        @Override
        public void onEmbedViewVisibilityChanged(int i) {
    
        }
    
        @Override
        public void initElementId(String s) {
    
        }
    
    }
    

小程序端實(shí)現(xiàn)

//page.axml
<mpaas-component
          id="mpaas-barrage"
          type="custom_barrage"                    // type類型,需要和native對(duì)應(yīng)起來
          style="{{ width: 400, height: 200 }}"    // 只能配置寬高
          onMpaasCustomEvent="onMpaasCustomEvent"  // 收到native事件
/>

//page.js

barrageContext = my.createMpaasComponentContext('mpaas-barrage');
// 發(fā)送數(shù)據(jù)給native
barrageContext.mpaasCustomEvent({
        actionType: 'bindLivePlayer',
        data: {
          "id": "liveplayer",
          "barrages": ["有意思", "沙發(fā)", "彈幕1", "彈幕2", "彈幕3"]
        }
      });
  }, 100)

頁(yè)面生命周期監(jiān)聽

  1. 初始化時(shí)調(diào)用如下代碼。

    List<String> miniAppPoint = new ArrayList<>();
    miniAppPoint.add(PageResumePoint.class.getName());
    miniAppPoint.add(PagePausePoint.class.getName());
    miniAppPoint.add(PageEnterPoint.class.getName());
    miniAppPoint.add(AppExitPoint.class.getName());
    Mriver.registerPoint(PageLifeCycleExtension.class.getName(), miniAppPoint);
  2. 實(shí)現(xiàn) PageLifeCycleExtension.java

    public class PageLifeCycleExtension implements PageResumePoint, PageEnterPoint, PagePausePoint, AppExitPoint {
    
        private static final String TAG = "PageLifeCycleExtension";
    
        @Override
        public void onPageResume(Page page) {
        }
    
        @Override
        public void onInitialized() {
    
        }
    
        @Override
        public void onFinalized() {
    
        }
    
        @Override
        public void onPageEnter(Page page) {
    
        }
    
        @Override
        public void onPagePause(final Page page) {
        }
    
        @Override
        public void onAppExit(App app) {
            
        }
    }

APM 監(jiān)聽

重要

如果頁(yè)面空白區(qū)域較大,不會(huì)回調(diào) MiniPage_Load_T2。

  1. 初始化時(shí)設(shè)置如下內(nèi)容。

    RVProxy.set(PrepareNotifyProxy.class, new PrepareNotifyProxy() {
    
                            @Override
                            public void notify(String s, PrepareStatus prepareStatus) {
    
                            }
    
                            @Override
                            public void apmEvent(final String s, final String s1, final String s2, final String s3, final String s4) {
                              // 非UI線程  
                              Log.i("MiniStartTime", "apmE: " + s + " " + s4);
                              if ("MiniAppStart".equalsIgnoreCase(s) || "MiniPage_Load_T2".equalsIgnoreCase(s)) {
                                  boolean isT2 = "MiniPage_Load_T2".equalsIgnoreCase(s);
                                  String apmData = s4;
                                  if (!TextUtils.isEmpty(apmData)) {
                                      parseTime(isT2, apmData);
                                  }
                              }
                          });
                    }
    
    
    
    
    private void parseTime(boolean isT2, String s4) {
            String[] kvArrs = s4.split("\\^");
            long miniStart = 0; // 小程序點(diǎn)擊的時(shí)間
            long miniPrepared = 0; // 小程序準(zhǔn)備階段完成的時(shí)間,首次會(huì)包含下載
            long miniAppStarted = 0; // 小程序核心階段完成的時(shí)間
            long miniT2 = 0; // 小程序T2渲染完成的時(shí)間
            boolean needIgnore = false;  // true表示內(nèi)部二級(jí)頁(yè)面跳轉(zhuǎn)時(shí)二級(jí)頁(yè)面渲染回調(diào),首屏需要忽略
    
            for (String kvItem : kvArrs) {
                String[] kv = kvItem.split("=");
                if (kv.length == 2) {
                    String key = kv[0];
                    String value = kv[1];
                    if ("mini_st_ts0".equalsIgnoreCase(key)) {
                        // 小程序點(diǎn)擊的時(shí)間
                        miniStart = Long.parseLong(value);
                    } else if ("mini_st_ts7".equalsIgnoreCase(key)) {
                        // 小程序準(zhǔn)備階段完成的時(shí)間
                        miniPrepared = Long.parseLong(value);
                    } else if ("mini_st_end_ts".equalsIgnoreCase(key)) {
                        // 小程序核心階段完成的時(shí)間
                        miniAppStarted = Long.parseLong(value);
                    } else if ("mini_t2_ts".equalsIgnoreCase(key)) {
                        // 小程序T2渲染完成的時(shí)間
                        miniT2 = Long.parseLong(value);
                    } else if (isT2 && "isFirstPage".equalsIgnoreCase(key)) {
                        if ("false".equalsIgnoreCase(value)) {
                            needIgnore = true;
                        }
                    }
                }
            }
    
            if (!needIgnore && miniStart > 0 && miniPrepared > 0 && miniAppStarted > 0 && miniT2 > 0) {
                final String toastStr = "準(zhǔn)備耗時(shí)=" + (miniPrepared - miniStart) + " 核心耗時(shí)=" + (miniAppStarted - miniPrepared) + " 業(yè)務(wù)耗時(shí)=" + (miniT2 - miniAppStarted) + " 總耗時(shí)=" + (miniT2 - miniStart);
                Log.i("MiniStartTime", toastStr);
                mUIHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MRiverApp.sApp, toastStr, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
  2. 啟動(dòng)小程序時(shí)增加時(shí)間戳參數(shù)。

    Bundle intent  = new Bundle();
    intent.putString("miniapp_start_ts", Long.toString(System.currentTimeMillis()));
    Mriver.startApp(FastStartActivity.this, “appId”, intent);

支持 Google 地圖

  1. 打開開關(guān)切換到 Google 地圖。

    Mriver.setConfig("ta_map_type", "1");
  2. 添加 Google 地圖依賴并配置 Google 地圖的 key。