Android弹幕实现:基于B站弹幕开源系统(3)-文本弹幕的完善和细节调整

版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/68485505


Android弹幕实现:基于B站弹幕开源系统(3)

本文在附录1,2的基础上再次对异步获取弹幕并显示弹幕完善逻辑和代码,集中在上层Java代码部分:

package zhangphil.danmaku;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDisplayer;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.ui.widget.DanmakuView;

public class MainActivity extends Activity {

    private DanmakuView mDanmakuView;
    private DanmakuContext mContext;
    private AcFunDanmakuParser mParser;

    private final int MAX_DANMAKU_LINES = 8; //弹幕在屏幕显示的最大行数

    private ScheduledThreadPoolExecutor mScheduledThreadPoolExecutor = null;
    private ConcurrentLinkedQueue<DanmakuMsg> mQueue = null; //所有的弹幕数据存取队列,在这里做线程的弹幕取和存
    private ArrayList<DanmakuMsg> danmakuLists = null;//每次请求最新的弹幕数据后缓存list

    private final int WHAT_GET_LIST_DATA = 0xffa01;
    private final int WHAT_DISPLAY_SINGLE_DANMAKU = 0xffa02;

    private final int BASE_TIME = 400;
    private final int BASE_TIME_ADD = 100;

    //标志文本弹幕的序列号
    //区别不同弹幕
    private static int danmakuTextMsgId = 0;

    private final int[] colors = {Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN, Color.CYAN, Color.DKGRAY};

    private Handler mDanmakuHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case WHAT_GET_LIST_DATA:
                    mDanmakuHandler.removeMessages(WHAT_GET_LIST_DATA);

                    if (danmakuLists != null && !danmakuLists.isEmpty()) {
                        mQueue.addAll(danmakuLists);
                        danmakuLists.clear();

                        if (!mQueue.isEmpty())
                            mDanmakuHandler.sendEmptyMessage(WHAT_DISPLAY_SINGLE_DANMAKU);
                    }

                    break;

                case WHAT_DISPLAY_SINGLE_DANMAKU:
                    mDanmakuHandler.removeMessages(WHAT_DISPLAY_SINGLE_DANMAKU);
                    displayDanmaku();
                    break;
            }
        }
    };

    /**
     * 弹幕数据封装的类(bean)
     */
    private class DanmakuMsg {
        public String msg;
    }

    private void displayDanmaku() {
        boolean p = mDanmakuView.isPaused();
        //如果当前的弹幕由于Android生命周期的原因进入暂停状态,那么不应该不停的消耗弹幕数据
        //要知道,在这里发出一个handler消息,那么将会消费(删掉)ConcurrentLinkedQueue头部的数据
        if (!mQueue.isEmpty() && !p) {
            DanmakuMsg dm = mQueue.poll();
            if (!TextUtils.isEmpty(dm.msg)) {
                addDanmaku(dm.msg, true);
            }

            mDanmakuHandler.sendEmptyMessageDelayed(WHAT_DISPLAY_SINGLE_DANMAKU, (long) (Math.random() * BASE_TIME) + BASE_TIME_ADD);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        danmakuLists = new ArrayList<>();
        mQueue = new ConcurrentLinkedQueue<>();
        mDanmakuView = (DanmakuView) findViewById(R.id.danmakuView);

        initDanmaku();

        mScheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
        GetDanmakuMessageTask mTask = new GetDanmakuMessageTask();
        //延迟0秒执行,每隔若干秒周期执行一次任务
        mScheduledThreadPoolExecutor.scheduleAtFixedRate(mTask, 0, 5, TimeUnit.SECONDS);

        Button show = (Button) findViewById(R.id.show);
        Button hide = (Button) findViewById(R.id.hide);
        Button sendText = (Button) findViewById(R.id.sendText);
        Button pause = (Button) findViewById(R.id.pause);
        Button resume = (Button) findViewById(R.id.resume);
        Button clear = (Button) findViewById(R.id.clear);

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDanmakuView.show();
            }
        });

        hide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDanmakuView.hide();
            }
        });

        sendText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //每点击一次按钮发送一条弹幕
                sendTextMessage();
            }
        });

        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDanmakuView.pause();
            }
        });

        resume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDanmakuView.resume();
            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearDanmaku();
            }
        });
    }

    /**
     * 假设该线程任务模拟的就是从网络中取弹幕数据的耗时操作
     * 假设这些弹幕数据序列是有序的。
     */
    private class GetDanmakuMessageTask implements Runnable {
        @Override
        public void run() {
            danmakuLists.clear();

            int count = (int) (Math.random() * 50);
            for (int i = 0; i < count; i++) {
                DanmakuMsg message = new DanmakuMsg();
                message.msg = "弹幕:" + danmakuTextMsgId;
                danmakuLists.add(message);

                danmakuTextMsgId++;
            }

            if (!danmakuLists.isEmpty()) {
                Message msg = mDanmakuHandler.obtainMessage();
                msg.what = WHAT_GET_LIST_DATA;
                mDanmakuHandler.sendMessage(msg);
            }
        }
    }

    /**
     * 驱动弹幕显示机制重新运作起来
     */
    private void resumeDanmaku() {
        if (!mQueue.isEmpty())
            mDanmakuHandler.sendEmptyMessageDelayed(WHAT_DISPLAY_SINGLE_DANMAKU, (int) (Math.random() * BASE_TIME) + BASE_TIME_ADD);
    }

    private void clearDanmaku() {
        if (danmakuLists != null && !danmakuLists.isEmpty()) {
            danmakuLists.clear();
        }

        if (mQueue != null && !mQueue.isEmpty())
            mQueue.clear();

        mDanmakuView.clearDanmakusOnScreen();
        mDanmakuView.clear();
    }

    private void initDanmaku() {
        mContext = DanmakuContext.create();

        // 设置最大显示行数
        HashMap<Integer, Integer> maxLinesPair = new HashMap<>();
        maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL, MAX_DANMAKU_LINES); // 滚动弹幕最大显示5行

        // 设置是否禁止重叠
        HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<>();
        overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_RL, true);
        overlappingEnablePair.put(BaseDanmaku.TYPE_FIX_TOP, true);

        //普通文本弹幕也描边设置样式
        //如果是图文混合编排编排,最后不要描边
        mContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN, 10) //描边的厚度
                .setDuplicateMergingEnabled(false)
                .setScrollSpeedFactor(1.2f) //弹幕的速度。注意!此值越小,速度越快!值越大,速度越慢。// by phil
                .setScaleTextSize(1.2f)  //缩放的值
//        .setCacheStuffer(new BackgroundCacheStuffer())  // 绘制背景使用BackgroundCacheStuffer
                .setMaximumLines(maxLinesPair)
                .preventOverlapping(overlappingEnablePair);

        mParser = new AcFunDanmakuParser();
        mDanmakuView.prepare(mParser, mContext);

        //mDanmakuView.showFPS(true);
        mDanmakuView.enableDanmakuDrawingCache(true);

        if (mDanmakuView != null) {
            mDanmakuView.setCallback(new master.flame.danmaku.controller.DrawHandler.Callback() {
                @Override
                public void updateTimer(DanmakuTimer timer) {
                }

                @Override
                public void drawingFinished() {

                }

                @Override
                public void danmakuShown(BaseDanmaku danmaku) {
                    //Log.d("弹幕文本", "danmakuShown text=" + danmaku.text);
                }

                @Override
                public void prepared() {
                    mDanmakuView.start();
                }
            });
        }
    }

    private void sendTextMessage() {
        addDanmaku("zhangphil@csdn: " + System.currentTimeMillis(), true);
    }

    private void addDanmaku(CharSequence cs, boolean islive) {
        BaseDanmaku danmaku = mContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        if (danmaku == null || mDanmakuView == null) {
            return;
        }

        danmaku.text = cs;
        danmaku.padding = 5;
        danmaku.priority = 0;  // 可能会被各种过滤器过滤并隐藏显示
        danmaku.isLive = islive;
        danmaku.setTime(mDanmakuView.getCurrentTime() + 1200);
        danmaku.textSize = 20f * (mParser.getDisplayer().getDensity() - 0.6f); //文本弹幕字体大小
        danmaku.textColor = getRandomColor(); //文本的颜色
        danmaku.textShadowColor = getRandomColor(); //文本弹幕描边的颜色
        //danmaku.underlineColor = Color.DKGRAY; //文本弹幕下划线的颜色
        danmaku.borderColor = getRandomColor(); //边框的颜色

        mDanmakuView.addDanmaku(danmaku);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mDanmakuView != null && mDanmakuView.isPrepared()) {
            mDanmakuView.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDanmakuView != null && mDanmakuView.isPrepared() && mDanmakuView.isPaused()) {
            mDanmakuView.resume();

            //重新启动handler消息机制,触发弹幕显示
            //如果没有这一个方法,那么显示弹幕的机制将失灵(失去驱动)
            //这个方法就是重新激发弹幕显示的handler机制。
            resumeDanmaku();
        }
    }

    private void closeGetDanmakuMessage() {
        if (mScheduledThreadPoolExecutor != null)
            mScheduledThreadPoolExecutor.shutdown();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDanmakuView != null) {
            // dont forget release!
            mDanmakuView.release();
            mDanmakuView = null;
        }

        closeGetDanmakuMessage();
    }

    /**
     * 从一系列颜色中随机选择一种颜色
     *
     * @return
     */
    private int getRandomColor() {
        int i = ((int) (Math.random() * 10)) % colors.length;
        return colors[i];
    }
}


代码运行结果如图:


附录:
1,《Android弹幕实现:基于B站弹幕开源系统(1)》链接:http://blog.csdn.net/zhangphil/article/details/68067100
2,《Android弹幕实现:基于B站弹幕开源系统(2)》链接:http://blog.csdn.net/zhangphil/article/details/68114226
3,《Java ConcurrentLinkedQueue队列线程安全操作》链接:http://blog.csdn.net/zhangphil/article/details/65936066

没有更多推荐了,返回首页