萤石云视频播放开发

集成:

dependencies { compile 'com.hikvision.ezviz:ezviz-sdk:4.5.1' }

添加权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_LOGS"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>

配置 build.gradle:

defaultConfig {
       ...
        targetSdkVersion 22//小于23
       ...
        ndk {
            abiFilters "armeabi-v7a"//只支持32位
        }
    }
     sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }

注意:

目前提供所有so均为32位,只能在armeabi-v7a引用。

当时碰到一个其他的sdk支持62位的,只能加上ndk { abiFilters "armeabi"},最后跟其他的sdk厂家要了一个32位的so文件,在app—>src->main下创建了一个armeabi-v7a文件夹,如下图:

 

targetSdkVersion设置为23及以上,在android6.0系统的手机上会出现没有权限崩溃的情况,因为android6.0牵扯到Dangerous Permissions问题,如果需要使用高版本,需要自己处理Dangerous Permissions。

 

AndroidManifest.xml:

<activity
        android:name="com.videogo.main.EzvizWebViewActivity"
        android:screenOrientation="portrait"
        android:configChanges="orientation|keyboardHidden"
    </activity>

<!-- receive 登录时使用,如果用web断登录则不需要,登录流程web端已经写好,只需拿到AccessToken设置一下就好,调用setAccessToken()方法。--> <receiver android:name="you_BroadcastReceiver" android:exported="false" > <intent-filter> <action android:name="com.videogo.action.OAUTH_SUCCESS_ACTION" /> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver>

Application初始化:

/**
 *  APP_KEY请替换成自己申请的
 */
EZOpenSDK.initLib(this, APP_KEY, "");

 

1.初始化EZPlayer调用EZOpenSDK的createPlayer,详见api; 
2.预览播放成功后可以进行以下操作:录像、拍照、画面翻转、对讲、云台控制、声音开关、视频画面缩放、拖动进度播放,详见api的EZPlayer,其中设备控制该接口的如云台控制和镜头显示功能、对讲,属于限制级接口,要优选通过判断设备的能力集来调用,设备能力集请查看EZDeviceInfo对象的属性值来判断具体方法; 
3.关于对讲功能,如果预览播放有声音输出,则在开启对讲前需要关闭预览播放的声音closeSound,关闭对讲后开启预览播放的声音openSound,详见demo; 
4.EZOpenSDK中的setVideoLevel设置视频清晰度(videoLevel),此调节可以在视频播放前设置也可以在视频播放成功后设置,视频播放成功后设置了清晰度需要先停止播放stopRealPlay然后重新开启播放startRealPlay才能生效; 
5.开始播放之后在消息回调中会收到a、成功消息:EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS,b、失败消息:EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL,失败回调时查看errorCode,如果为400035(需要输入验证码)和400036(验证码错误),则需要开发者自己处理让用户重新输入验证密码,并调用setPlayVerifyCode设置密码,然后重新启动播放。

 

 

播放视频类的代码:

package com.everyoo.smarthome.ui;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andbase.library.http.AbHttpUtil;
import com.andbase.library.http.listener.AbStringHttpResponseListener;
import com.andbase.library.http.model.AbRequestParams;
import com.everyoo.smarthome.R;
import com.everyoo.smarthome.ui.scan.main.CaptureActivity;
import com.everyoo.smarthome.util.DataManager;
import com.everyoo.smarthome.util.EZUtils;
import com.everyoo.smarthome.util.HttpConfig;
import com.everyoo.smarthome.util.SharePreferenceUtil;
import com.everyoo.smarthome.util.ToastUtil;
import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.exception.ErrorCode;
import com.videogo.exception.InnerException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.realplay.RealPlayStatus;
import com.videogo.util.ConnectionDetector;
import com.videogo.util.LogUtil;
import com.videogo.util.MediaScanner;
import com.videogo.util.SDCardUtil;
import com.videogo.util.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static android.app.Activity.RESULT_OK;
import static com.everyoo.smarthome.HomeApplication.getOpenSDK;
import static com.videogo.openapi.EZConstants.EZRealPlayConstants.MSG_SET_VEDIOMODE_FAIL;
import static com.videogo.realplay.RealPlayMsg.MSG_SET_VEDIOMODE_SUCCESS;

/**
 * Created by tom on 2017/11/15.
 */

public class HomeTopCameraFragment extends Fragment implements SurfaceHolder.Callback, View.OnClickListener, Handler.Callback {

    private static final String TAG = "HomeTopCameraFragment";

    public static final int MSG_PLAY_UI_UPDATE = 200;
    public static final int CAMERA_LIST = 2020;

    private String deviceSerial;

    private SurfaceView mRealPlaySv;
    private SurfaceHolder mRealPlaySh;
    private Button mRealPlayBtn;
    private Button mRealPlaySoundBtn;
    private Button mRealPlayQualityBtn;
    private Button mRealPlayPreviouslyBtn;
    private Button mRealPlayTalkBtn;
    private Button mRealPlayVideoBtn;
    private Button add_device;
    private LinearLayout ll_no_camera;
    private PopupWindow mQualityPopupWindow = null;
    private EZConstants.EZVideoLevel mCurrentQulityMode = EZConstants.EZVideoLevel.VIDEO_LEVEL_HD;
    /**
     * 标识是否正在播放
     */
    private int mStatus = RealPlayStatus.STATUS_INIT;

    /**
     * 演示点预览控制对象
     */
    private EZPlayer mEZPlayer;

    private List<EZDeviceInfo> mCameraList;
    private EZDeviceInfo mDeviceInfo = null;
    private EZCameraInfo mCameraInfo = null;
    private Handler mHandler = new Handler(this);
    private int mSoundType = 0;
    private boolean mIsOnTalk =false;
    private boolean mIsRecording = false;
    private TextView tv_device_name,device_list,mRealPlayRecordTv;
    private ImageView iv_play;

    /**
     * 定时器
     */
    private Timer mUpdateTimer = null;
    /**
     * 定时器执行的任务
     */
    private TimerTask mUpdateTimerTask = null;

    private String mRecordTime = null;
    /**
     * 录像时间
     */
    private int mRecordSecond = 0;

    private SharePreferenceUtil sharePreferenceUtil;
    private String deviceName;
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //播放成功的回调
            case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                startUpdateTimer();
                break;
            case  MSG_SET_VEDIOMODE_SUCCESS:
                closeQualityPopupWindow();
                setVideoLevel();
                if (mStatus == RealPlayStatus.STATUS_START) {
                    // 停止播放
                    stopRealPlay();
                    //下面语句防止stopRealPlay线程还没释放surface, startRealPlay线程已经开始使用surface
                    //因此需要等待500ms
                    SystemClock.sleep(500);
                    // 开始播放
                    startRealPlay();
                }
                break;
            case EZConstants.EZRealPlayConstants.MSG_SET_VEDIOMODE_FAIL:
                closeQualityPopupWindow();
                setVideoLevel();
                ToastUtil.showToast(getActivity(),"切换视频质量失败");
                break;
            case MSG_PLAY_UI_UPDATE:
                if (mIsRecording) {
                    updateRecordTime();
                }
                break;

        }
        return false;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 保持屏幕常亮
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view;

        view = inflater.inflate(R.layout.ez_realplay_page, container, false);

        mRealPlaySv = (SurfaceView) view.findViewById(R.id.realplay_sv);
        mRealPlaySh = mRealPlaySv.getHolder();
        mRealPlaySh.addCallback(this);

        mRealPlayBtn = (Button) view.findViewById(R.id.realplay_play_btn);
        mRealPlayBtn.setOnClickListener(this);
        mRealPlaySoundBtn = (Button) view.findViewById(R.id.realplay_sound_btn);
        mRealPlaySoundBtn.setOnClickListener(this);
        mRealPlayQualityBtn = (Button) view.findViewById(R.id.realplay_quality_btn);
        mRealPlayQualityBtn.setOnClickListener(this);
        mRealPlayPreviouslyBtn = (Button) view.findViewById(R.id.realplay_previously_btn);
        mRealPlayPreviouslyBtn.setOnClickListener(this);
        mRealPlayTalkBtn = (Button) view.findViewById(R.id.realplay_talk_btn);
        mRealPlayTalkBtn.setOnClickListener(this);
        mRealPlayVideoBtn = (Button) view.findViewById(R.id.realplay_video_btn);
        mRealPlayVideoBtn.setOnClickListener(this);

        mRealPlayRecordTv = (TextView) view.findViewById(R.id.tv_video_time);

        tv_device_name = (TextView) view.findViewById(R.id.tv_device_name);
        iv_play = (ImageView) view.findViewById(R.id.iv_play);

        ll_no_camera = (LinearLayout) view.findViewById(R.id.ll_no_camera);
        add_device = (Button) view.findViewById(R.id.add_device);
        add_device.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivity(intent);
            }
        });

        device_list = (TextView) view.findViewById(R.id.device_list);
        device_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CameraListActivity.class);
                startActivityForResult(intent,CAMERA_LIST);
            }
        });

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        initData();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopRealPlay();
    }

    private void initData() {
       getAccessToken();

    }

    private void getAccessToken() {
        sharePreferenceUtil = new SharePreferenceUtil(getActivity());
        AbRequestParams params = new AbRequestParams();
        params.put("userid", sharePreferenceUtil.getUserId());
        params.put("accesstoken", sharePreferenceUtil.getAccessToken());
        AbHttpUtil.getInstance(getActivity()).post(HttpConfig.get_token, params, new AbStringHttpResponseListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {

            }

            @Override
            public void onSuccess(int statusCode, String content) {
                JSONObject object;
                try {
                    object = new JSONObject(content);
                    if (object.optString("result").equals("2003")) {
                        JSONObject info = object.optJSONObject("info");
                        String accessToken = info.optString("accessToken");
                        String expireTime = info.optString("expireTime");
                        sharePreferenceUtil = new SharePreferenceUtil(getActivity());
                        sharePreferenceUtil.putString("CameraAccessToken",accessToken);
                        sharePreferenceUtil.putString("CameraExpireTime",expireTime);
                        getOpenSDK().setAccessToken(accessToken);
                        getDeviceList();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getDeviceList() {
        sharePreferenceUtil = new SharePreferenceUtil(getActivity());
        AbRequestParams params = new AbRequestParams();
        params.put("userid", sharePreferenceUtil.getUserId());
        params.put("accesstoken", sharePreferenceUtil.getAccessToken());
        AbHttpUtil.getInstance(getActivity()).post(HttpConfig.getCamera_list, params, new AbStringHttpResponseListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {

            }

            @Override
            public void onSuccess(int statusCode, String content) {
                JSONObject object;
                try {
                    object = new JSONObject(content);
                    if (object.optString("result").equals("2003")) {
                        JSONArray info = object.optJSONArray("info");
                        if (info!=null && info.length()>0) {
                            JSONObject object1 = info.optJSONObject(0);
                            deviceSerial = object1.optString("deviceSerial");
                            deviceName = object1.getString("deviceName");
                            if (deviceSerial != null) {
                                new GetCamersInfoListTask().execute();
                                ll_no_camera.setVisibility(View.GONE);
                            }
                        }else {
                            ll_no_camera.setVisibility(View.VISIBLE);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_LIST){
            if (resultCode == RESULT_OK){
                deviceSerial = data.getStringExtra("deviceSerial");
                Log.d(TAG, "onActivityResult: "+deviceSerial);
                new GetCamersInfoListTask().execute();
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (mEZPlayer != null) {
            mEZPlayer.setSurfaceHold(holder);
        }
        mRealPlaySh = holder;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mEZPlayer != null) {
            mEZPlayer.setSurfaceHold(null);
        }
        mRealPlaySh = null;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.realplay_play_btn:
                if (mStatus != RealPlayStatus.STATUS_STOP) {
                    stopRealPlay();
                } else {
                    startRealPlay();
                }
                break;
            case R.id.realplay_previously_btn:
                onCapturePicBtnClick();
                break;
            case R.id.realplay_video_btn:
                onRecordBtnClick();
                break;
            case R.id.realplay_talk_btn:
                if(mIsOnTalk){
                    stopVoiceTalk();
                }else {
                    startVoiceTalk();
                }
                break;

            case R.id.realplay_quality_btn:
                openQualityPopupWindow(mRealPlayQualityBtn);
                break;

            case R.id.realplay_sound_btn:
                setRealPlaySound();
                break;
            default:
                break;
        }
    }

    /**
     * 开始播放
     *
     * @see
     * @since V2.0
     */
    private void startRealPlay() {
        // 增加手机客户端操作信息记录
        LogUtil.debugLog(TAG, "startRealPlay");

        if (mStatus == RealPlayStatus.STATUS_START || mStatus == RealPlayStatus.STATUS_PLAY) {
            return;
        }

        // 检查网络是否可用
        if (!ConnectionDetector.isNetworkAvailable(getActivity())) {
            // 提示没有连接网络
            ToastUtil.showToast(getActivity(), "没有连接网络");
            return;
        }

        mStatus = RealPlayStatus.STATUS_START;

        if (mCameraInfo != null) {
            if (mEZPlayer == null) {
                mEZPlayer = getOpenSDK().createPlayer(mCameraInfo.getDeviceSerial(), mCameraInfo.getCameraNo());
            }

            if (mEZPlayer == null)
                return;
            if (mDeviceInfo == null) {
                return;
            }
            if (mDeviceInfo.getIsEncrypt() == 1) {
                mEZPlayer.setPlayVerifyCode(DataManager.getInstance().getDeviceSerialVerifyCode(mCameraInfo.getDeviceSerial()));
            }
            mEZPlayer.setHandler(mHandler);
            mEZPlayer.setSurfaceHold(mRealPlaySh);
            mEZPlayer.startRealPlay();
            mRealPlayBtn.setBackgroundResource(R.mipmap.camera_pause);
            iv_play.setVisibility(View.GONE);
        }
    }
    /**
     * 停止播放
     *
     * @see
     * @since V1.0
     */
    private void stopRealPlay() {
        LogUtil.debugLog(TAG, "stopRealPlay");
        mStatus = RealPlayStatus.STATUS_STOP;

        if (mEZPlayer != null) {
            mEZPlayer.stopRealPlay();
            mRealPlayBtn.setBackgroundResource(R.mipmap.camera_play);
        }
        iv_play.setVisibility(View.VISIBLE);
    }

    /**
     * 调节声音
     */
    private void setRealPlaySound() {
        if (mEZPlayer != null) {
            if (mSoundType == 0) {
                mEZPlayer.closeSound();
                mSoundType = 1;
                mRealPlaySoundBtn.setBackgroundResource(R.mipmap.camera_novoice);
            } else {
                mEZPlayer.openSound();
                mSoundType = 0;
                mRealPlaySoundBtn.setBackgroundResource(R.mipmap.camera_voice);
            }
        }
    }

    /**
     * 设备对讲
     *
     * @see
     * @since V2.0
     */
    private void startVoiceTalk() {
        LogUtil.debugLog(TAG, "startVoiceTalk");
        if (mEZPlayer == null) {
            LogUtil.debugLog(TAG, "EZPlaer is null");
            return;
        }
        if (mCameraInfo == null) {
            return;
        }
        mIsOnTalk = true;

        if (mEZPlayer != null) {
            mEZPlayer.closeSound();
        }
        mEZPlayer.startVoiceTalk();
        mRealPlayTalkBtn.setBackgroundResource(R.mipmap.camera_talking);
    }

    /**
     * 停止对讲
     *
     * @see
     * @since V2.0
     */
    private void stopVoiceTalk() {
        if (mCameraInfo == null || mEZPlayer == null) {
            return;
        }
        LogUtil.debugLog(TAG, "stopVoiceTalk");

        mEZPlayer.stopVoiceTalk();
        mRealPlayTalkBtn.setBackgroundResource(R.mipmap.camera_talk);

    }

    /**
     * 开始录像
     *
     * @see
     * @since V1.0
     */
    private void onRecordBtnClick() {
        if (mIsRecording) {
            stopRealPlayRecord();
            return;
        }

        if (!SDCardUtil.isSDCardUseable()) {
            // 提示SD卡不可用
            Utils.showToast(getActivity(), "SD卡不可用");
            return;
        }

        if (SDCardUtil.getSDCardRemainSize() < SDCardUtil.PIC_MIN_MEM_SPACE) {
            // 提示内存不足
            Utils.showToast(getActivity(), "内存不足");
            return;
        }

        if (mEZPlayer != null) {

            //mAudioPlayUtil.playAudioFile(AudioPlayUtil.RECORD_SOUND);
            mIsRecording =true;

            //时间作为文件命名
            java.util.Date date = new java.util.Date();
            String strRecordFile = Environment.getExternalStorageDirectory().getPath() + "/EZOpenSDK/Records/" + String.format("%tY", date)
                    + String.format("%tm", date) + String.format("%td", date) + "/"
                    + String.format("%tH", date) + String.format("%tM", date) + String.format("%tS", date) + String.format("%tL", date) + ".mp4";

            mRealPlayVideoBtn.setBackgroundResource(R.mipmap.camera_videoing);
            if (mEZPlayer.startLocalRecordWithFile(strRecordFile))
            {
                ToastUtil.showToast(getActivity(),"录像成功");
            } else {
                ToastUtil.showToast(getActivity(),"录像失败");
            }
        }
    }

    /**
     * 停止录像
     *
     * @see
     * @since V1.0
     */
    private void stopRealPlayRecord() {
        if (mEZPlayer == null || !mIsRecording) {
            return;
        }

        //mAudioPlayUtil.playAudioFile(AudioPlayUtil.RECORD_SOUND);
        mEZPlayer.stopLocalRecord();
        mRealPlayVideoBtn.setBackgroundResource(R.mipmap.camera_video);
        mIsRecording = false;
        mRealPlayRecordTv.setVisibility(View.GONE);
    }
    /**
     * 启动定时器
     *
     * @see
     * @since V1.0
     */
    private void startUpdateTimer() {
        stopUpdateTimer();
        // 开始录像计时
        mUpdateTimer = new Timer();
        mUpdateTimerTask = new TimerTask() {
            @Override
            public void run() {

                // 更新录像时间
                if (mEZPlayer != null && mIsRecording) {
                    // 更新录像时间
                    Calendar OSDTime = mEZPlayer.getOSDTime();
                    if (OSDTime != null) {
                        String playtime = Utils.OSD2Time(OSDTime);
                        if (!TextUtils.equals(playtime, mRecordTime)) {
                            mRecordSecond++;
                            //mRecordTime = playtime;
                        }
                    }
                }
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(MSG_PLAY_UI_UPDATE);
                }
            }
        };
        // 延时1000ms后执行,1000ms执行一次
        mUpdateTimer.schedule(mUpdateTimerTask, 0, 1000);
    }
    /**
     * 停止定时器
     *
     * @see
     * @since V1.0
     */
    private void stopUpdateTimer() {
        mHandler.removeMessages(MSG_PLAY_UI_UPDATE);
        // 停止录像计时
        if (mUpdateTimer != null) {
            mUpdateTimer.cancel();
            mUpdateTimer = null;
        }

        if (mUpdateTimerTask != null) {
            mUpdateTimerTask.cancel();
            mUpdateTimerTask = null;
        }
    }
    /**
     * 更新录像时间
     *
     * @see
     * @since V1.0
     */
    private void updateRecordTime() {

        if (mIsRecording) {
            mRealPlayRecordTv.setVisibility(View.VISIBLE);
        } else {
            mRealPlayRecordTv.setVisibility(View.GONE);
        }
        // 计算分秒
        int leftSecond = mRecordSecond % 3600;
        int minitue = leftSecond / 60;
        int second = leftSecond % 60;

        // 显示录像时间
        String recordTime = String.format("%02d:%02d", minitue, second);
        mRealPlayRecordTv.setText(recordTime);
    }

    /**
     * 抓拍按钮响应函数
     *
     * @since V1.0
     */
    private void onCapturePicBtnClick() {

        if (!SDCardUtil.isSDCardUseable()) {
            // 提示SD卡不可用
            Utils.showToast(getActivity(), "SD卡不可用");
            return;
        }

        if (SDCardUtil.getSDCardRemainSize() < SDCardUtil.PIC_MIN_MEM_SPACE) {
            // 提示内存不足
            Utils.showToast(getActivity(), "内存不足");
            return;
        }

        if (mEZPlayer != null) {

            Thread thr = new Thread() {
                @Override
                public void run() {
                    Bitmap bmp = mEZPlayer.capturePicture();
                    if (bmp != null) {
                        try {

                            // 用时间命名
                            java.util.Date date = new java.util.Date();
                            final String path = Environment.getExternalStorageDirectory().getPath() + "/EZOpenSDK/CapturePicture/" + String.format("%tY", date)
                                    + String.format("%tm", date) + String.format("%td", date) + "/"
                                    + String.format("%tH", date) + String.format("%tM", date) + String.format("%tS", date) + String.format("%tL", date) +".jpg";

                            if (TextUtils.isEmpty(path)) {
                                bmp.recycle();
                                bmp = null;
                                return;
                            }
                            EZUtils.saveCapturePictrue(path, bmp);

                            MediaScanner mMediaScanner = new MediaScanner(getActivity());
                            mMediaScanner.scanFile(path, "jpg");
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.showToast(getActivity(),"保存到相册");
                                }
                            });
                        } catch (InnerException e) {
                            e.printStackTrace();
                        } finally {
                            if (bmp != null) {
                                bmp.recycle();
                                bmp = null;
                                return;
                            }
                        }
                    }
                    super.run();
                }
            };
            thr.start();
        }
    }

    /**
     * 视频质量,2-高清,1-标清,0-流畅
     * @param anchor
     */
    private void openQualityPopupWindow(View anchor) {
        if (mEZPlayer == null) {
            return;
        }
        closeQualityPopupWindow();
        LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ViewGroup layoutView = (ViewGroup) layoutInflater.inflate(R.layout.realplay_quality_items, null, true);

        Button qualityHdBtn = (Button) layoutView.findViewById(R.id.quality_hd_btn);
        qualityHdBtn.setOnClickListener(mOnPopWndClickListener);
        Button qualityBalancedBtn = (Button) layoutView.findViewById(R.id.quality_balanced_btn);
        qualityBalancedBtn.setOnClickListener(mOnPopWndClickListener);
        Button qualityFlunetBtn = (Button) layoutView.findViewById(R.id.quality_flunet_btn);
        qualityFlunetBtn.setOnClickListener(mOnPopWndClickListener);

        // 视频质量,2-高清,1-标清,0-流畅
        if (mCameraInfo.getVideoLevel() == EZConstants.EZVideoLevel.VIDEO_LEVEL_FLUNET) {
            qualityFlunetBtn.setEnabled(false);
        } else if (mCameraInfo.getVideoLevel() == EZConstants.EZVideoLevel.VIDEO_LEVEL_BALANCED) {
            qualityBalancedBtn.setEnabled(false);
        } else if (mCameraInfo.getVideoLevel() == EZConstants.EZVideoLevel.VIDEO_LEVEL_HD) {
            qualityHdBtn.setEnabled(false);
        }

        int height = 105;

        qualityFlunetBtn.setVisibility(View.VISIBLE);
        qualityBalancedBtn.setVisibility(View.VISIBLE);
        qualityHdBtn.setVisibility(View.VISIBLE);

        height = Utils.dip2px(getActivity(), height);
        mQualityPopupWindow = new PopupWindow(layoutView, RelativeLayout.LayoutParams.WRAP_CONTENT, height, true);
        mQualityPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mQualityPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                LogUtil.infoLog(TAG, "KEYCODE_BACK DOWN");
                mQualityPopupWindow = null;
                closeQualityPopupWindow();
            }
        });
        try {
            mQualityPopupWindow.showAsDropDown(anchor, - Utils.dip2px(getActivity(), 5),
                    -(height + anchor.getHeight() + Utils.dip2px(getActivity(), 8)));
        } catch (Exception e) {
            e.printStackTrace();
            closeQualityPopupWindow();
        }
    }

    private void closeQualityPopupWindow() {
        if (mQualityPopupWindow != null) {
            dismissPopWindow(mQualityPopupWindow);
            mQualityPopupWindow = null;
        }
    }
    private void dismissPopWindow(PopupWindow popupWindow) {
        if (popupWindow != null && !getActivity().isFinishing()) {
            try {
                popupWindow.dismiss();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

    private View.OnClickListener mOnPopWndClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.quality_hd_btn:
                    setQualityMode(EZConstants.EZVideoLevel.VIDEO_LEVEL_HD);
                    break;
                case R.id.quality_balanced_btn:
                    setQualityMode(EZConstants.EZVideoLevel.VIDEO_LEVEL_BALANCED);
                    break;
                case R.id.quality_flunet_btn:
                    setQualityMode(EZConstants.EZVideoLevel.VIDEO_LEVEL_FLUNET);
                    break;
                default:
                    break;
            }
        }
    };
    /**
     * 码流配置 清晰度 2-高清,1-标清,0-流畅
     *
     * @see
     * @since V2.0
     */
    private void setQualityMode(final EZConstants.EZVideoLevel mode) {
        // 检查网络是否可用
        if (!ConnectionDetector.isNetworkAvailable(getActivity())) {
            // 提示没有连接网络
            Utils.showToast(getActivity(), "没有连接网络");
            return;
        }

        if (mEZPlayer != null) {

            Thread thr = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.d("ssssssss", "run:"+mCameraInfo.getDeviceSerial()+"......"+mCameraInfo.getCameraNo());
                        String deviceSerial = mCameraInfo.getDeviceSerial();
                        int cameraNo = mCameraInfo.getCameraNo();
                        getOpenSDK().setVideoLevel(deviceSerial, cameraNo, mode.getVideoLevel());
                        mCurrentQulityMode = mode;
                        Message msg = Message.obtain();
                        msg.what = MSG_SET_VEDIOMODE_SUCCESS;
                        mHandler.sendMessage(msg);
                        LogUtil.i(TAG, "setQualityMode success");
                    } catch (BaseException e) {
                        mCurrentQulityMode = EZConstants.EZVideoLevel.VIDEO_LEVEL_FLUNET;
                        e.printStackTrace();
                        Message msg = Message.obtain();
                        msg.what = MSG_SET_VEDIOMODE_FAIL;
                        mHandler.sendMessage(msg);
                        LogUtil.i(TAG, "setQualityMode fail");
                    }

                }
            }) {
            };
            thr.start();
        }
    }
    private void setVideoLevel() {
        if (mCameraInfo == null || mEZPlayer == null || mDeviceInfo == null) {
            return;
        }

        if (mDeviceInfo.getStatus() == 1) {
            mRealPlayQualityBtn.setEnabled(true);
        } else {
            mRealPlayQualityBtn.setEnabled(false);
        }

        /************** 本地数据保存 需要更新之前获取到的设备列表信息,开发者自己设置 *********************/
        mCameraInfo.setVideoLevel(mCurrentQulityMode.getVideoLevel());

        // 视频质量,2-高清,1-标清,0-流畅
        if (mCurrentQulityMode.getVideoLevel() == EZConstants.EZVideoLevel.VIDEO_LEVEL_FLUNET.getVideoLevel()) {
            mRealPlayQualityBtn.setText(R.string.quality_flunet);
        } else if (mCurrentQulityMode.getVideoLevel() == EZConstants.EZVideoLevel.VIDEO_LEVEL_BALANCED.getVideoLevel()) {
            mRealPlayQualityBtn.setText(R.string.quality_balanced);
        } else if (mCurrentQulityMode.getVideoLevel() == EZConstants.EZVideoLevel.VIDEO_LEVEL_HD.getVideoLevel()) {
            mRealPlayQualityBtn.setText(R.string.quality_hd);
        }
    }
    /**
     * 获取事件消息任务
     */
    private class GetCamersInfoListTask extends AsyncTask<Void, Void, EZDeviceInfo> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected EZDeviceInfo doInBackground(Void... params) {
            if (getActivity().isFinishing()) {
                return null;
            }
            if (!ConnectionDetector.isNetworkAvailable(getActivity())) {
                return null;
            }

            try {
                EZDeviceInfo result = null;

                result = getOpenSDK().getDeviceInfo(deviceSerial);

                return result;

            } catch (BaseException e) {
                ErrorInfo errorInfo = (ErrorInfo) e.getObject();
                LogUtil.debugLog(TAG, errorInfo.toString());

                return null;
            }
        }

        @Override
        protected void onPostExecute(EZDeviceInfo result) {
            super.onPostExecute(result);
            if (getActivity().isFinishing()) {
                return;
            }

            if (result != null) {
                ll_no_camera.setVisibility(View.GONE);
                mDeviceInfo = result;
                mCameraInfo = EZUtils.getCameraInfoFromDevice(mDeviceInfo, 0);
                if (tv_device_name!=null && deviceName !=null){
                    tv_device_name.setText(deviceName);
                }
                startRealPlay();
            }else {
                ll_no_camera.setVisibility(View.VISIBLE);
            }
        }
    }
}

  

posted @ 2017-12-06 09:33  IT_lss  阅读(3289)  评论(0编辑  收藏  举报