EasyPusher手机直播推送是如何实现后台直播推送的

本文由EasyDarwin开源团队成员John提供;http://blog.csdn.net/jyt0551/article/details/52276062

EasyPusher Android是使用摄像头采集视频数据,并通过MediaCodec进行H264编码,之后打包成RTSP格式并上传的。

大家知道Android 的Camera是通过回调来获取YUV数据的,要想获取到回调数据,需要给Camera一个有效的Surface对象。通常我们用SurfaceView或者TextureView来提供这个surface。那如果app跑到后台时,这个Surface就会被destory掉,这时候摄像头就不再回调数据了。那整个推送过程就会停止。

那EasyPusher如何实现在“后台”继续推送呢?实际上我们借助了悬浮窗口来创建这样一个Surface供Camera使用。其实这里并非真正的后台,因为是有一个可见的view的。为了看起来更像是“后台”,那我们可以把这个view 的尺寸设置为1*1(经测试,surfaceview设置为0*0时,其surface不会被create出来),这样用户实际上是看不到的,这样就达到了“后台”的效果。

首先我们创建一个Service,在onCreate里,我们创建一个SurfaceView,并使用WindowsManager将它添加到Windows里。这里需要注意的是,因为我们要创建悬浮框,需要设置layoutParam参数为
TYPE_SYSTEM_OVERLAY,以保证其不依附于Activity.
关键代码如下:

 // Create new SurfaceView, set its size to 1x1, move it to the top left
 // corner and set this service as a callback
    mWindowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
    mOutComeVideoView = new SurfaceView(this);


    WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(1, 1, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, PixelFormat.TRANSLUCENT);
    layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
    mWindowManager.addView(mOutComeVideoView, layoutParams);
    mOutComeVideoView.getHolder().addCallback(this);
// 在Callback里实现创建摄像头、启动预览等操作。 

EasyPusher Github:https://github.com/EasyDarwin/EasyPusher

获取更多信息

邮件:support@easydarwin.org

WEB:www.EasyDarwin.org

Copyright © EasyDarwin.org 2012-2016

EasyDarwin

posted @ 2016-08-22 14:19  Babosa  阅读(885)  评论(0编辑  收藏  举报