android.view.SurfaceView

Here are the examples of the java api android.view.SurfaceView taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

429 Examples 7

19 Source : CaptureActivity.java
with Apache License 2.0
from yushiwo

/**
 * 初始化照相机和surfaceView,使zxing不断尝试从摄像头获取照片并解码
 * 本方法在Activity的onResume中,以及在扫描功能被关闭后需要再次开启时调用
 */
private void initZXingCamera() {
    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hreplacedurface) {
        initCamera(surfaceHolder);
    } else {
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    decodeFormats = null;
    characterSet = null;
    playBeep = true;
    AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
        playBeep = false;
    }
    vibrate = true;
}

19 Source : CaptureActivity.java
with Apache License 2.0
from yushiwo

/**
 * 重新启动扫描
 */
public void restartCamera() {
    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    initCamera(surfaceHolder);
    if (handler != null) {
        handler.restartPreviewAndDecode();
    }
}

19 Source : CodeScannerView.java
with MIT License
from yuriy-budiyev

/**
 * A view to display code scanner preview
 *
 * @see CodeScanner
 */
public final clreplaced CodeScannerView extends ViewGroup {

    private static final boolean DEFAULT_AUTO_FOCUS_BUTTON_VISIBLE = true;

    private static final boolean DEFAULT_FLASH_BUTTON_VISIBLE = true;

    private static final int DEFAULT_AUTO_FOCUS_BUTTON_VISIBILITY = VISIBLE;

    private static final int DEFAULT_FLASH_BUTTON_VISIBILITY = VISIBLE;

    private static final int DEFAULT_MASK_COLOR = 0x77000000;

    private static final int DEFAULT_FRAME_COLOR = Color.WHITE;

    private static final int DEFAULT_AUTO_FOCUS_BUTTON_COLOR = Color.WHITE;

    private static final int DEFAULT_FLASH_BUTTON_COLOR = Color.WHITE;

    private static final float DEFAULT_FRAME_THICKNESS_DP = 2f;

    private static final float DEFAULT_FRAME_ASPECT_RATIO_WIDTH = 1f;

    private static final float DEFAULT_FRAME_ASPECT_RATIO_HEIGHT = 1f;

    private static final float DEFAULT_FRAME_CORNER_SIZE_DP = 50f;

    private static final float DEFAULT_FRAME_CORNERS_RADIUS_DP = 0f;

    private static final float DEFAULT_FRAME_SIZE = 0.75f;

    private static final float BUTTON_SIZE_DP = 56f;

    private static final float FOCUS_AREA_SIZE_DP = 20f;

    private SurfaceView mPreviewView;

    private ViewFinderView mViewFinderView;

    private ImageView mAutoFocusButton;

    private ImageView mFlashButton;

    private Point mPreviewSize;

    private SizeListener mSizeListener;

    private CodeScanner mCodeScanner;

    private int mButtonSize;

    private int mAutoFocusButtonColor;

    private int mFlashButtonColor;

    private int mFocusAreaSize;

    /**
     * A view to display code scanner preview
     *
     * @see CodeScanner
     */
    public CodeScannerView(@NonNull final Context context) {
        super(context);
        initialize(context, null, 0, 0);
    }

    /**
     * A view to display code scanner preview
     *
     * @see CodeScanner
     */
    public CodeScannerView(@NonNull final Context context, @Nullable final AttributeSet attrs) {
        super(context, attrs);
        initialize(context, attrs, 0, 0);
    }

    /**
     * A view to display code scanner preview
     *
     * @see CodeScanner
     */
    public CodeScannerView(@NonNull final Context context, @Nullable final AttributeSet attrs, @AttrRes final int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context, attrs, defStyleAttr, 0);
    }

    /**
     * A view to display code scanner preview
     *
     * @see CodeScanner
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    public CodeScannerView(final Context context, final AttributeSet attrs, @AttrRes final int defStyleAttr, @StyleRes final int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initialize(context, attrs, defStyleAttr, defStyleRes);
    }

    private void initialize(@NonNull final Context context, @Nullable final AttributeSet attrs, @AttrRes final int defStyleAttr, @StyleRes final int defStyleRes) {
        mPreviewView = new SurfaceView(context);
        mPreviewView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        mViewFinderView = new ViewFinderView(context);
        mViewFinderView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        final float density = context.getResources().getDisplayMetrics().density;
        mButtonSize = Math.round(density * BUTTON_SIZE_DP);
        mFocusAreaSize = Math.round(density * FOCUS_AREA_SIZE_DP);
        mAutoFocusButton = new ImageView(context);
        mAutoFocusButton.setLayoutParams(new LayoutParams(mButtonSize, mButtonSize));
        mAutoFocusButton.setScaleType(ImageView.ScaleType.CENTER);
        mAutoFocusButton.setImageResource(R.drawable.ic_code_scanner_auto_focus_on);
        mAutoFocusButton.setOnClickListener(new AutoFocusClickListener());
        mFlashButton = new ImageView(context);
        mFlashButton.setLayoutParams(new LayoutParams(mButtonSize, mButtonSize));
        mFlashButton.setScaleType(ImageView.ScaleType.CENTER);
        mFlashButton.setImageResource(R.drawable.ic_code_scanner_flash_on);
        mFlashButton.setOnClickListener(new FlashClickListener());
        if (attrs == null) {
            mViewFinderView.setFrameAspectRatio(DEFAULT_FRAME_ASPECT_RATIO_WIDTH, DEFAULT_FRAME_ASPECT_RATIO_HEIGHT);
            mViewFinderView.setMaskColor(DEFAULT_MASK_COLOR);
            mViewFinderView.setFrameColor(DEFAULT_FRAME_COLOR);
            mViewFinderView.setFrameThickness(Math.round(DEFAULT_FRAME_THICKNESS_DP * density));
            mViewFinderView.setFrameCornersSize(Math.round(DEFAULT_FRAME_CORNER_SIZE_DP * density));
            mViewFinderView.setFrameCornersRadius(Math.round(DEFAULT_FRAME_CORNERS_RADIUS_DP * density));
            mViewFinderView.setFrameSize(DEFAULT_FRAME_SIZE);
            mAutoFocusButton.setColorFilter(DEFAULT_AUTO_FOCUS_BUTTON_COLOR);
            mFlashButton.setColorFilter(DEFAULT_FLASH_BUTTON_COLOR);
            mAutoFocusButton.setVisibility(DEFAULT_AUTO_FOCUS_BUTTON_VISIBILITY);
            mFlashButton.setVisibility(DEFAULT_FLASH_BUTTON_VISIBILITY);
        } else {
            TypedArray a = null;
            try {
                a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CodeScannerView, defStyleAttr, defStyleRes);
                setMaskColor(a.getColor(R.styleable.CodeScannerView_maskColor, DEFAULT_MASK_COLOR));
                setFrameColor(a.getColor(R.styleable.CodeScannerView_frameColor, DEFAULT_FRAME_COLOR));
                setFrameThickness(a.getDimensionPixelOffset(R.styleable.CodeScannerView_frameThickness, Math.round(DEFAULT_FRAME_THICKNESS_DP * density)));
                setFrameCornersSize(a.getDimensionPixelOffset(R.styleable.CodeScannerView_frameCornersSize, Math.round(DEFAULT_FRAME_CORNER_SIZE_DP * density)));
                setFrameCornersRadius(a.getDimensionPixelOffset(R.styleable.CodeScannerView_frameCornersRadius, Math.round(DEFAULT_FRAME_CORNERS_RADIUS_DP * density)));
                setFrameAspectRatio(a.getFloat(R.styleable.CodeScannerView_frameAspectRatioWidth, DEFAULT_FRAME_ASPECT_RATIO_WIDTH), a.getFloat(R.styleable.CodeScannerView_frameAspectRatioHeight, DEFAULT_FRAME_ASPECT_RATIO_HEIGHT));
                setFrameSize(a.getFloat(R.styleable.CodeScannerView_frameSize, DEFAULT_FRAME_SIZE));
                setAutoFocusButtonVisible(a.getBoolean(R.styleable.CodeScannerView_autoFocusButtonVisible, DEFAULT_AUTO_FOCUS_BUTTON_VISIBLE));
                setFlashButtonVisible(a.getBoolean(R.styleable.CodeScannerView_flashButtonVisible, DEFAULT_FLASH_BUTTON_VISIBLE));
                setAutoFocusButtonColor(a.getColor(R.styleable.CodeScannerView_autoFocusButtonColor, DEFAULT_AUTO_FOCUS_BUTTON_COLOR));
                setFlashButtonColor(a.getColor(R.styleable.CodeScannerView_flashButtonColor, DEFAULT_FLASH_BUTTON_COLOR));
            } finally {
                if (a != null) {
                    a.recycle();
                }
            }
        }
        addView(mPreviewView);
        addView(mViewFinderView);
        addView(mAutoFocusButton);
        addView(mFlashButton);
    }

    @Override
    protected void onLayout(final boolean changed, final int left, final int top, final int right, final int bottom) {
        performLayout(right - left, bottom - top);
    }

    @Override
    protected void onSizeChanged(final int width, final int height, final int oldWidth, final int oldHeight) {
        performLayout(width, height);
        final SizeListener listener = mSizeListener;
        if (listener != null) {
            listener.onSizeChanged(width, height);
        }
    }

    @Override
    @SuppressLint("ClickableViewAccessibility")
    public boolean onTouchEvent(@NonNull final MotionEvent event) {
        final CodeScanner codeScanner = mCodeScanner;
        final Rect frameRect = getFrameRect();
        final int x = (int) event.getX();
        final int y = (int) event.getY();
        if (codeScanner != null && frameRect != null && codeScanner.isAutoFocusSupportedOrUnknown() && codeScanner.isTouchFocusEnabled() && event.getAction() == MotionEvent.ACTION_DOWN && frameRect.isPointInside(x, y)) {
            final int areaSize = mFocusAreaSize;
            codeScanner.performTouchFocus(new Rect(x - areaSize, y - areaSize, x + areaSize, y + areaSize).fitIn(frameRect));
        }
        return super.onTouchEvent(event);
    }

    /**
     * Get current mask color
     *
     * @see #setMaskColor
     */
    @ColorInt
    public int getMaskColor() {
        return mViewFinderView.getMaskColor();
    }

    /**
     * Set color of the space outside of the framing rect
     *
     * @param color Mask color
     */
    public void setMaskColor(@ColorInt final int color) {
        mViewFinderView.setMaskColor(color);
    }

    /**
     * Get current frame color
     *
     * @see #setFrameColor
     */
    @ColorInt
    public int getFrameColor() {
        return mViewFinderView.getFrameColor();
    }

    /**
     * Set color of the frame
     *
     * @param color Frame color
     */
    public void setFrameColor(@ColorInt final int color) {
        mViewFinderView.setFrameColor(color);
    }

    /**
     * Get current frame thickness
     *
     * @see #setFrameThickness
     */
    @Px
    public int getFrameThickness() {
        return mViewFinderView.getFrameThickness();
    }

    /**
     * Set frame thickness
     *
     * @param thickness Frame thickness in pixels
     */
    public void setFrameThickness(@Px final int thickness) {
        if (thickness < 0) {
            throw new IllegalArgumentException("Frame thickness can't be negative");
        }
        mViewFinderView.setFrameThickness(thickness);
    }

    /**
     * Get current frame corners size
     *
     * @see #setFrameCornersSize
     */
    @Px
    public int getFrameCornersSize() {
        return mViewFinderView.getFrameCornersSize();
    }

    /**
     * Set size of the frame corners
     *
     * @param size Size in pixels
     */
    public void setFrameCornersSize(@Px final int size) {
        if (size < 0) {
            throw new IllegalArgumentException("Frame corners size can't be negative");
        }
        mViewFinderView.setFrameCornersSize(size);
    }

    /**
     * Get current frame corners radius
     *
     * @see #setFrameCornersRadius
     */
    @Px
    public int getFrameCornersRadius() {
        return mViewFinderView.getFrameCornersRadius();
    }

    /**
     * Set current frame corners radius
     *
     * @param radius Frame corners radius in pixels
     */
    public void setFrameCornersRadius(@Px final int radius) {
        if (radius < 0) {
            throw new IllegalArgumentException("Frame corners radius can't be negative");
        }
        mViewFinderView.setFrameCornersRadius(radius);
    }

    /**
     * Get current frame size
     *
     * @see #setFrameSize
     */
    @FloatRange(from = 0.1, to = 1.0)
    public float getFrameSize() {
        return mViewFinderView.getFrameSize();
    }

    /**
     * Set relative frame size where 1.0 means full size
     *
     * @param size Relative frame size between 0.1 and 1.0
     */
    public void setFrameSize(@FloatRange(from = 0.1, to = 1) final float size) {
        if (size < 0.1 || size > 1) {
            throw new IllegalArgumentException("Max frame size value should be between 0.1 and 1, inclusive");
        }
        mViewFinderView.setFrameSize(size);
    }

    /**
     * Get current frame aspect ratio width
     *
     * @see #setFrameAspectRatioWidth
     * @see #setFrameAspectRatio
     */
    @FloatRange(from = 0, fromInclusive = false)
    public float getFrameAspectRatioWidth() {
        return mViewFinderView.getFrameAspectRatioWidth();
    }

    /**
     * Set frame aspect ratio width
     *
     * @param ratioWidth Frame aspect ratio width
     * @see #setFrameAspectRatio
     */
    public void setFrameAspectRatioWidth(@FloatRange(from = 0, fromInclusive = false) final float ratioWidth) {
        if (ratioWidth <= 0) {
            throw new IllegalArgumentException("Frame aspect ratio values should be greater than zero");
        }
        mViewFinderView.setFrameAspectRatioWidth(ratioWidth);
    }

    /**
     * Get current frame aspect ratio height
     *
     * @see #setFrameAspectRatioHeight
     * @see #setFrameAspectRatio
     */
    @FloatRange(from = 0, fromInclusive = false)
    public float getFrameAspectRatioHeight() {
        return mViewFinderView.getFrameAspectRatioHeight();
    }

    /**
     * Set frame aspect ratio height
     *
     * @param ratioHeight Frame aspect ratio width
     * @see #setFrameAspectRatio
     */
    public void setFrameAspectRatioHeight(@FloatRange(from = 0, fromInclusive = false) final float ratioHeight) {
        if (ratioHeight <= 0) {
            throw new IllegalArgumentException("Frame aspect ratio values should be greater than zero");
        }
        mViewFinderView.setFrameAspectRatioHeight(ratioHeight);
    }

    /**
     * Set frame aspect ratio (ex. 1:1, 15:10, 16:9, 4:3)
     *
     * @param ratioWidth  Frame aspect ratio width
     * @param ratioHeight Frame aspect ratio height
     */
    public void setFrameAspectRatio(@FloatRange(from = 0, fromInclusive = false) final float ratioWidth, @FloatRange(from = 0, fromInclusive = false) final float ratioHeight) {
        if (ratioWidth <= 0 || ratioHeight <= 0) {
            throw new IllegalArgumentException("Frame aspect ratio values should be greater than zero");
        }
        mViewFinderView.setFrameAspectRatio(ratioWidth, ratioHeight);
    }

    /**
     * Whether if auto focus button is currently visible
     *
     * @see #setAutoFocusButtonVisible
     */
    public boolean isAutoFocusButtonVisible() {
        return mAutoFocusButton.getVisibility() == VISIBLE;
    }

    /**
     * Set whether auto focus button is visible or not
     *
     * @param visible Visibility
     */
    public void setAutoFocusButtonVisible(final boolean visible) {
        mAutoFocusButton.setVisibility(visible ? VISIBLE : INVISIBLE);
    }

    /**
     * Whether if mask is currently visible
     *
     * @see #setMaskVisible
     */
    public boolean isMaskVisible() {
        return mViewFinderView.getVisibility() == VISIBLE;
    }

    /**
     * Set whether mask is visible or not
     *
     * @param visible Visibility
     */
    public void setMaskVisible(final boolean visible) {
        mViewFinderView.setVisibility(visible ? VISIBLE : INVISIBLE);
    }

    /**
     * Whether if flash button is currently visible
     *
     * @see #setFlashButtonVisible
     */
    public boolean isFlashButtonVisible() {
        return mFlashButton.getVisibility() == VISIBLE;
    }

    /**
     * Set whether flash button is visible or not
     *
     * @param visible Visibility
     */
    public void setFlashButtonVisible(final boolean visible) {
        mFlashButton.setVisibility(visible ? VISIBLE : INVISIBLE);
    }

    /**
     * Get current auto focus button color
     *
     * @see #setAutoFocusButtonColor
     */
    @ColorInt
    public int getAutoFocusButtonColor() {
        return mAutoFocusButtonColor;
    }

    /**
     * Set auto focus button color
     *
     * @param color Color
     */
    public void setAutoFocusButtonColor(@ColorInt final int color) {
        mAutoFocusButtonColor = color;
        mAutoFocusButton.setColorFilter(color);
    }

    /**
     * Get current flash button color
     *
     * @see #setFlashButtonColor
     */
    @ColorInt
    public int getFlashButtonColor() {
        return mFlashButtonColor;
    }

    /**
     * Set flash button color
     *
     * @param color Color
     */
    public void setFlashButtonColor(@ColorInt final int color) {
        mFlashButtonColor = color;
        mFlashButton.setColorFilter(color);
    }

    @NonNull
    SurfaceView getPreviewView() {
        return mPreviewView;
    }

    @NonNull
    ViewFinderView getViewFinderView() {
        return mViewFinderView;
    }

    @Nullable
    Rect getFrameRect() {
        return mViewFinderView.getFrameRect();
    }

    void setPreviewSize(@Nullable final Point previewSize) {
        mPreviewSize = previewSize;
        requestLayout();
    }

    void setSizeListener(@Nullable final SizeListener sizeListener) {
        mSizeListener = sizeListener;
    }

    void setCodeScanner(@NonNull final CodeScanner codeScanner) {
        if (mCodeScanner != null) {
            throw new IllegalStateException("Code scanner has already been set");
        }
        mCodeScanner = codeScanner;
        setAutoFocusEnabled(codeScanner.isAutoFocusEnabled());
        setFlashEnabled(codeScanner.isFlashEnabled());
    }

    void setAutoFocusEnabled(final boolean enabled) {
        mAutoFocusButton.setImageResource(enabled ? R.drawable.ic_code_scanner_auto_focus_on : R.drawable.ic_code_scanner_auto_focus_off);
    }

    void setFlashEnabled(final boolean enabled) {
        mFlashButton.setImageResource(enabled ? R.drawable.ic_code_scanner_flash_on : R.drawable.ic_code_scanner_flash_off);
    }

    private void performLayout(final int width, final int height) {
        final Point previewSize = mPreviewSize;
        if (previewSize == null) {
            mPreviewView.layout(0, 0, width, height);
        } else {
            int frameLeft = 0;
            int frameTop = 0;
            int frameRight = width;
            int frameBottom = height;
            final int previewWidth = previewSize.getX();
            if (previewWidth > width) {
                final int d = (previewWidth - width) / 2;
                frameLeft -= d;
                frameRight += d;
            }
            final int previewHeight = previewSize.getY();
            if (previewHeight > height) {
                final int d = (previewHeight - height) / 2;
                frameTop -= d;
                frameBottom += d;
            }
            mPreviewView.layout(frameLeft, frameTop, frameRight, frameBottom);
        }
        mViewFinderView.layout(0, 0, width, height);
        final int buttonSize = mButtonSize;
        mAutoFocusButton.layout(0, 0, buttonSize, buttonSize);
        mFlashButton.layout(width - buttonSize, 0, width, buttonSize);
    }

    interface SizeListener {

        void onSizeChanged(int width, int height);
    }

    private final clreplaced AutoFocusClickListener implements OnClickListener {

        @Override
        public void onClick(final View view) {
            final CodeScanner scanner = mCodeScanner;
            if (scanner == null || !scanner.isAutoFocusSupportedOrUnknown()) {
                return;
            }
            final boolean enabled = !scanner.isAutoFocusEnabled();
            scanner.setAutoFocusEnabled(enabled);
            setAutoFocusEnabled(enabled);
        }
    }

    private final clreplaced FlashClickListener implements OnClickListener {

        @Override
        public void onClick(final View view) {
            final CodeScanner scanner = mCodeScanner;
            if (scanner == null || !scanner.isFlashSupportedOrUnknown()) {
                return;
            }
            final boolean enabled = !scanner.isFlashEnabled();
            scanner.setFlashEnabled(enabled);
            setFlashEnabled(enabled);
        }
    }
}

19 Source : CaptureActivity.java
with Apache License 2.0
from yiwent

@Override
protected void onResume() {
    super.onResume();
    Log.d(TAG, "xxxxxxxxxxxxxxxxxxxonResume");
    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hreplacedurface) {
        initCamera(surfaceHolder);
    } else {
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    decodeFormats = null;
    characterSet = null;
    playBeep = true;
    final AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
        playBeep = false;
    }
    initBeepSound();
    vibrate = true;
}

19 Source : TextureRecordActivity.java
with Apache License 2.0
from yellowcath

/**
 * Created by huangwei on 2016/1/25.
 */
public clreplaced TextureRecordActivity extends Activity implements IRecordView, View.OnClickListener, OnRecordListener, IBottomMenuView {

    private SurfaceView mSurfaceView;

    static SSegmentRecorder mRecorder;

    private CameraPresenter mCameraPresenter;

    private BottomSegMenuView mBottomMenuView;

    private ImageView mFilterImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_texture_record);
        mCameraPresenter = new CameraPresenter();
        mCameraPresenter.attachView(this);
        mFilterImg = findViewById(R.id.movie_filter);
        mFilterImg.setOnClickListener(this);
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);
        mSurfaceView.getHolder().addCallback(mCameraPresenter);
        SSurfaceRecorder recorder = initVideoRecorder();
        mRecorder = new SSegmentRecorder<SSurfaceRecorder>(getApplicationContext(), recorder);
        mRecorder.addRecordListener(this);
        mBottomMenuView = findViewById(R.id.record_bottom_layout);
        mBottomMenuView.setBottomViewCallBack(this);
        mBottomMenuView.enableSVideoTouch(true);
        mBottomMenuView.enableVideoProgressLayout();
    }

    private SSurfaceRecorder initVideoRecorder() {
        SSurfaceRecorder.MEDIACODEC_API21_ENABLE = false;
        SSurfaceRecorder.MEDIACODEC_API21_ASYNC_ENABLE = true;
        ICameraProxyForRecord cameraProxyForRecord = new ICameraProxyForRecord() {

            @Override
            public void addSurfaceDataListener(PreviewSurfaceListener previewSurfaceListener, SurfaceCreatedCallback surfaceCreatedCallback) {
                RecordHelper.setPreviewSurfaceListener(previewSurfaceListener, surfaceCreatedCallback);
            }

            @Override
            public void removeSurfaceDataListener(PreviewSurfaceListener previewSurfaceListener) {
                RecordHelper.setPreviewSurfaceListener(null, null);
            }

            @Override
            public void addPreviewDataCallback(PreviewDataCallback callback) {
                RecordHelper.setPreviewDataCallback(callback);
            }

            @Override
            public void removePreviewDataCallback(PreviewDataCallback callback) {
                RecordHelper.setPreviewDataCallback(null);
            }

            @Override
            public int getVideoRotation() {
                return 0;
            }

            @Override
            public int getPreviewWidth() {
                return mCameraPresenter.getPreviewSize().height;
            }

            @Override
            public int getPreviewHeight() {
                return mCameraPresenter.getPreviewSize().width;
            }
        };
        return new SSurfaceRecorder(getApplicationContext(), cameraProxyForRecord);
    }

    @Override
    public void onClick(View v) {
        if (v == mFilterImg) {
            mFilterImg.setSelected(!mFilterImg.isSelected());
            mFilterImg.setColorFilter(mFilterImg.isSelected() ? 0xFFFF0000 : 0xFFFFFFFF);
            mCameraPresenter.enableFilter(mFilterImg.isSelected());
        }
    }

    @Override
    public void onRecordSuccess(VideoInfo videoInfo) {
    }

    @Override
    public void onRecordStart() {
    }

    @Override
    public void onRecordFail(Throwable t) {
    }

    @Override
    public void onRecordStop() {
        Intent intent = new Intent(this, PreviewActivity2.clreplaced);
        // intent.putExtra(PreviewActivity.FILEPATH, videoInfo.getVideoPath());
        startActivity(intent);
    }

    @Override
    public void onRecordPause() {
        RL.i("onRecordPause");
    }

    @Override
    public void onRecordResume() {
        RL.i("onRecordResume");
    }

    @Override
    public ISVideoRecorder requestRecordListener() {
        return mRecorder;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mBottomMenuView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBottomMenuView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCameraPresenter.detachView();
        mCameraPresenter = null;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mRecorder.cancelRecord();
    }
}

19 Source : FaceDetector.java
with Apache License 2.0
from Yee-chen

public void setUIThreadInterface(SurfaceView obj) {
    mFaceSurface = obj;
}

19 Source : CaptureActivity.java
with Apache License 2.0
from yangxch

@Override
protected void onResume() {
    super.onResume();
    // CameraManager必须在这里初始化,而不是在onCreate()中。
    // 这是必须的,因为当我们第一次进入时需要显示帮助页,我们并不想打开Camera,测量屏幕大小
    // 当扫描框的尺寸不正确时会出现bug
    cameraManager = new CameraManager(getApplication());
    viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
    viewfinderView.setCameraManager(cameraManager);
    handler = null;
    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hreplacedurface) {
        // activity在paused时但不会stopped,因此surface仍旧存在;
        // surfaceCreated()不会调用,因此在这里初始化camera
        initCamera(surfaceHolder);
    } else {
        // 重置callback,等待surfaceCreated()来初始化camera
        surfaceHolder.addCallback(this);
    }
    beepManager.updatePrefs();
    inactivityTimer.onResume();
    source = IntentSource.NONE;
    decodeFormats = null;
    characterSet = null;
}

19 Source : VitalSignsProcess.java
with Boost Software License 1.0
from YahyaOdeh

public clreplaced VitalSignsProcess extends AppCompatActivity {

    // Variables Initialization
    private static final AtomicBoolean processing = new AtomicBoolean(false);

    private SurfaceView preview = null;

    private static SurfaceHolder previewHolder = null;

    private static Camera camera = null;

    private static PowerManager.WakeLock wakeLock = null;

    // Toast
    private Toast mainToast;

    // DataBase
    public String user;

    UserDB Data = new UserDB(this);

    // ProgressBar
    private ProgressBar ProgHeart;

    public int ProgP = 0;

    public int inc = 0;

    // Beats variable
    public int Beats = 0;

    public double bufferAvgB = 0;

    // Freq + timer variable
    private static long startTime = 0;

    private double SamplingFreq;

    // SPO2 variable
    private static Double[] RedBlueRatio;

    public int o2;

    double Stdr = 0;

    double Stdb = 0;

    double sumred = 0;

    double sumblue = 0;

    // RR variable
    public int Breath = 0;

    public double bufferAvgBr = 0;

    // BloodPressure variables
    public double Gen, Agg, Hei, Wei;

    public double Q = 4.5;

    private static int SP = 0, DP = 0;

    // Arraylist
    public ArrayList<Double> GreenAvgList = new ArrayList<>();

    public ArrayList<Double> RedAvgList = new ArrayList<>();

    public ArrayList<Double> BlueAvgList = new ArrayList<>();

    public int counter = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vital_signs_process);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            user = extras.getString("Usr");
        // The key argument here must match that used in the other activity
        }
        // Get parameters from Db
        Hei = Integer.parseInt(Data.getheight(user));
        Wei = Integer.parseInt(Data.getweight(user));
        Agg = Integer.parseInt(Data.getage(user));
        Gen = Integer.parseInt(Data.getgender(user));
        if (Gen == 1) {
            Q = 5;
        }
        // XML - Java Connecting
        preview = findViewById(R.id.preview);
        previewHolder = preview.getHolder();
        previewHolder.addCallback(surfaceCallback);
        previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        ProgHeart = findViewById(R.id.VSPB);
        ProgHeart.setProgress(0);
        // WakeLock Initialization : Forces the phone to stay On
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
    }

    // Prevent the system from restarting your activity during certain configuration changes,
    // but receive a callback when the configurations do change, so that you can manually update your activity as necessary.
    // such as screen orientation, keyboard availability, and language
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    // Wakelock + Open device camera + set orientation to 90 degree
    // store system time as a start time for the replacedyzing process
    // your activity to start interacting with the user.
    @Override
    public void onResume() {
        super.onResume();
        wakeLock.acquire();
        camera = Camera.open();
        camera.setDisplayOrientation(90);
        startTime = System.currentTimeMillis();
    }

    // call back the frames then release the camera + wakelock and Initialize the camera to null
    // Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().
    // When activity B is launched in front of activity A,
    // this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
    @Override
    public void onPause() {
        super.onPause();
        wakeLock.release();
        camera.setPreviewCallback(null);
        camera.stopPreview();
        camera.release();
        camera = null;
    }

    // getting frames data from the camera and start the measuring process
    private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {

        /**
         * {@inheritDoc}
         */
        @Override
        public void onPreviewFrame(byte[] data, Camera cam) {
            // if data or size == null ****
            if (data == null)
                throw new NullPointerException();
            Camera.Size size = cam.getParameters().getPreviewSize();
            if (size == null)
                throw new NullPointerException();
            // Atomically sets the value to the given updated value if the current value == the expected value.
            if (!processing.compareAndSet(false, true))
                return;
            // put width + height of the camera inside the variables
            int width = size.width;
            int height = size.height;
            // RGB intensities initialization
            double GreenAvg;
            double RedAvg;
            double BlueAvg;
            // Getting Green intensity after applying image processing on frame data, 3 stands for green
            GreenAvg = ImageProcessing.decodeYUV420SPtoRedBlueGreenAvg(data.clone(), height, width, 3);
            // Getting Red intensity after applying image processing on frame data, 1 stands for red
            RedAvg = ImageProcessing.decodeYUV420SPtoRedBlueGreenAvg(data.clone(), height, width, 1);
            // Summing Red intensity for the whole period of recording which is 30 second
            sumred = sumred + RedAvg;
            // Getting Blue intensity after applying image processing on frame data, 2 stands for blue
            BlueAvg = ImageProcessing.decodeYUV420SPtoRedBlueGreenAvg(data.clone(), height, width, 2);
            // Summing Red intensity for the whole period of recording which is 30 second
            sumblue = sumblue + BlueAvg;
            // Adding rgb intensity values to listofarrays
            GreenAvgList.add(GreenAvg);
            RedAvgList.add(RedAvg);
            BlueAvgList.add(BlueAvg);
            // counts the number of frames for the whole period of recording " 30 s "
            ++counter;
            // To check if we got a good red intensity to process if not return to the condition and set it again until we get a good red intensity
            if (RedAvg < 200) {
                inc = 0;
                ProgP = inc;
                counter = 0;
                ProgHeart.setProgress(ProgP);
                processing.set(false);
            }
            long endTime = System.currentTimeMillis();
            // convert time to seconds to be compared with 30 seconds
            double totalTimeInSecs = (endTime - startTime) / 1000d;
            if (totalTimeInSecs >= 30) {
                // convert listofarrays to arrays to be used in processing
                Double[] Green = GreenAvgList.toArray(new Double[GreenAvgList.size()]);
                Double[] Red = RedAvgList.toArray(new Double[RedAvgList.size()]);
                Double[] Blue = BlueAvgList.toArray(new Double[BlueAvgList.size()]);
                // calculating sampling frequency
                SamplingFreq = (counter / totalTimeInSecs);
                // sending the rg arrays with the counter to make an fft process to get the heartbeats out of it
                double HRFreq = Fft.FFT(Green, counter, SamplingFreq);
                double bpm = (int) ceil(HRFreq * 60);
                double HR1Freq = Fft.FFT(Red, counter, SamplingFreq);
                double bpm1 = (int) ceil(HR1Freq * 60);
                // sending the rg arrays with the counter to make an fft process then a bandpreplaced filter to get the respiration rate out of it
                double RRFreq = Fft2.FFT(Green, counter, SamplingFreq);
                double breath = (int) ceil(RRFreq * 60);
                double RR1Freq = Fft2.FFT(Red, counter, SamplingFreq);
                double breath1 = (int) ceil(RR1Freq * 60);
                // calculating the mean of red and blue intensities on the whole period of recording
                double meanr = sumred / counter;
                double meanb = sumblue / counter;
                // calculating the standard  deviation
                for (int i = 0; i < counter - 1; i++) {
                    Double bufferb = Blue[i];
                    Stdb = Stdb + ((bufferb - meanb) * (bufferb - meanb));
                    Double bufferr = Red[i];
                    Stdr = Stdr + ((bufferr - meanr) * (bufferr - meanr));
                }
                // calculating the variance
                double varr = sqrt(Stdr / (counter - 1));
                double varb = sqrt(Stdb / (counter - 1));
                // calculating ratio between the two means and two variances
                double R = (varr / meanr) / (varb / meanb);
                // estimating SPo2
                double spo2 = 100 - 5 * (R);
                o2 = (int) (spo2);
                // comparing if heartbeat and Respiration rate are reasonable from the green and red intensities then take the average, otherwise value from green or red intensity if one of them is good and other is bad.
                if ((bpm > 45 || bpm < 200) || (breath > 10 || breath < 20)) {
                    if ((bpm1 > 45 || bpm1 < 200) || (breath1 > 10 || breath1 < 24)) {
                        bufferAvgB = (bpm + bpm1) / 2;
                        bufferAvgBr = (breath + breath1) / 2;
                    } else {
                        bufferAvgB = bpm;
                        bufferAvgBr = breath;
                    }
                } else if ((bpm1 > 45 || bpm1 < 200) || (breath1 > 10 || breath1 < 20)) {
                    bufferAvgB = bpm1;
                    bufferAvgBr = breath1;
                }
                // if the values of hr and o2 are not reasonable then show a toast that measurement failed and restart the progress bar and the whole recording process for another 30 seconds
                if ((bufferAvgB < 45 || bufferAvgB > 200) || (bufferAvgBr < 10 || bufferAvgBr > 24)) {
                    inc = 0;
                    ProgP = inc;
                    ProgHeart.setProgress(ProgP);
                    mainToast = Toast.makeText(getApplicationContext(), "Measurement Failed", Toast.LENGTH_SHORT);
                    mainToast.show();
                    startTime = System.currentTimeMillis();
                    counter = 0;
                    processing.set(false);
                    return;
                }
                Beats = (int) bufferAvgB;
                Breath = (int) bufferAvgBr;
                // estimations to estimate the blood pressure
                double ROB = 18.5;
                double ET = (364.5 - 1.23 * Beats);
                double BSA = 0.007184 * (Math.pow(Wei, 0.425)) * (Math.pow(Hei, 0.725));
                double SV = (-6.6 + (0.25 * (ET - 35)) - (0.62 * Beats) + (40.4 * BSA) - (0.51 * Agg));
                double PP = SV / ((0.013 * Wei - 0.007 * Agg - 0.004 * Beats) + 1.307);
                double MPP = Q * ROB;
                SP = (int) (MPP + 3 / 2 * PP);
                DP = (int) (MPP - PP / 3);
            }
            // if all those variable contains a valid values then swap them to results activity and finish the processing activity
            if ((Beats != 0) && (SP != 0) && (DP != 0) && (o2 != 0) && (Breath != 0)) {
                Intent i = new Intent(VitalSignsProcess.this, VitalSignsResults.clreplaced);
                i.putExtra("O2R", o2);
                i.putExtra("breath", Breath);
                i.putExtra("bpm", Beats);
                i.putExtra("SP", SP);
                i.putExtra("DP", DP);
                i.putExtra("Usr", user);
                startActivity(i);
                finish();
            }
            // keeps incrementing the progress bar and keeps the loop until we have a valid values for the previous if state
            if (RedAvg != 0) {
                ProgP = inc++ / 34;
                ProgHeart.setProgress(ProgP);
            }
            processing.set(false);
        }
    };

    private final SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera.setPreviewDisplay(previewHolder);
                camera.setPreviewCallback(previewCallback);
            } catch (Throwable t) {
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            Camera.Parameters parameters = camera.getParameters();
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            Camera.Size size = getSmallestPreviewSize(width, height, parameters);
            if (size != null) {
                parameters.setPreviewSize(size.width, size.height);
            }
            camera.setParameters(parameters);
            camera.startPreview();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
        }
    };

    private static Camera.Size getSmallestPreviewSize(int width, int height, Camera.Parameters parameters) {
        Camera.Size result = null;
        for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
            if (size.width <= width && size.height <= height) {
                if (result == null) {
                    result = size;
                } else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;
                    if (newArea < resultArea)
                        result = size;
                }
            }
        }
        return result;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent i = new Intent(VitalSignsProcess.this, StartVitalSigns.clreplaced);
        i.putExtra("Usr", user);
        startActivity(i);
        finish();
    }
}

19 Source : RespirationProcess.java
with Boost Software License 1.0
from YahyaOdeh

public clreplaced RespirationProcess extends Activity {

    // Variables Initialization
    private static final String TAG = "HeartRateMonitor";

    private static final AtomicBoolean processing = new AtomicBoolean(false);

    private SurfaceView preview = null;

    private static SurfaceHolder previewHolder = null;

    private static Camera camera = null;

    private static PowerManager.WakeLock wakeLock = null;

    // Toast
    private Toast mainToast;

    // DataBase
    public String user;

    UserDB Data = new UserDB(this);

    // ProgressBar
    private ProgressBar ProgRR;

    public int ProgP = 0;

    public int inc = 0;

    // RR variable
    public int Breath = 0;

    public double bufferAvgBr = 0;

    // Freq + timer variable
    private static long startTime = 0;

    private double SamplingFreq;

    // Arraylist
    public ArrayList<Double> GreenAvgList = new ArrayList<Double>();

    public ArrayList<Double> RedAvgList = new ArrayList<Double>();

    public int counter = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_respiration_process);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            user = extras.getString("Usr");
        // The key argument here must match that used in the other activity
        }
        // XML - Java Connecting
        preview = findViewById(R.id.preview);
        previewHolder = preview.getHolder();
        previewHolder.addCallback(surfaceCallback);
        previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        ProgRR = findViewById(R.id.HRPB);
        ProgRR.setProgress(0);
        // WakeLock Initialization : Forces the phone to stay On
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
    }

    // Prevent the system from restarting your activity during certain configuration changes,
    // but receive a callback when the configurations do change, so that you can manually update your activity as necessary.
    // such as screen orientation, keyboard availability, and language
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    // Wakelock + Open device camera + set orientation to 90 degree
    // store system time as a start time for the replacedyzing process
    // your activity to start interacting with the user.
    // This is a good place to begin animations, open exclusive-access devices (such as the camera)
    @Override
    public void onResume() {
        super.onResume();
        wakeLock.acquire();
        camera = Camera.open();
        camera.setDisplayOrientation(90);
        startTime = System.currentTimeMillis();
    }

    // call back the frames then release the camera + wakelock and Initialize the camera to null
    // Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().
    // When activity B is launched in front of activity A,
    // this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
    @Override
    public void onPause() {
        super.onPause();
        wakeLock.release();
        camera.setPreviewCallback(null);
        camera.stopPreview();
        camera.release();
        camera = null;
    }

    // getting frames data from the camera and start the heartbeat process
    private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {

        /**
         * {@inheritDoc}
         */
        @Override
        public void onPreviewFrame(byte[] data, Camera cam) {
            // if data or size == null ****
            if (data == null)
                throw new NullPointerException();
            Camera.Size size = cam.getParameters().getPreviewSize();
            if (size == null)
                throw new NullPointerException();
            // Atomically sets the value to the given updated value if the current value == the expected value.
            if (!processing.compareAndSet(false, true))
                return;
            // put width + height of the camera inside the variables
            int width = size.width;
            int height = size.height;
            double GreenAvg;
            double RedAvg;
            // 1 stands for red intensity, 2 for blue, 3 for green
            GreenAvg = ImageProcessing.decodeYUV420SPtoRedBlueGreenAvg(data.clone(), height, width, 3);
            // 1 stands for red intensity, 2 for blue, 3 for green
            RedAvg = ImageProcessing.decodeYUV420SPtoRedBlueGreenAvg(data.clone(), height, width, 1);
            GreenAvgList.add(GreenAvg);
            RedAvgList.add(RedAvg);
            // countes number of frames in 30 seconds
            ++counter;
            // To check if we got a good red intensity to process if not return to the condition and set it again until we get a good red intensity
            if (RedAvg < 200) {
                inc = 0;
                ProgP = inc;
                counter = 0;
                ProgRR.setProgress(ProgP);
                processing.set(false);
            }
            long endTime = System.currentTimeMillis();
            // to convert time to seconds
            double totalTimeInSecs = (endTime - startTime) / 1000d;
            if (totalTimeInSecs >= 30) {
                // when 30 seconds of measuring preplacedes do the following " we chose 30 seconds to take half sample since 60 seconds is normally a full sample of the heart beat
                Double[] Green = GreenAvgList.toArray(new Double[GreenAvgList.size()]);
                Double[] Red = RedAvgList.toArray(new Double[RedAvgList.size()]);
                SamplingFreq = (counter / totalTimeInSecs);
                double RRFreq = Fft2.FFT(Green, counter, SamplingFreq);
                double bpm = (int) ceil(RRFreq * 60);
                double RR1Freq = Fft2.FFT(Red, counter, SamplingFreq);
                double breath1 = (int) ceil(RR1Freq * 60);
                // The following code is to make sure that if the respirationrate from red and green intensities are reasonable
                // take the average between them, otherwise take the green or red if one of them is good
                if ((bpm > 10 || bpm < 24)) {
                    if ((breath1 > 10 || breath1 < 24)) {
                        bufferAvgBr = (bpm + breath1) / 2;
                    } else {
                        bufferAvgBr = bpm;
                    }
                } else if ((breath1 > 10 || breath1 < 24)) {
                    bufferAvgBr = breath1;
                }
                if (bufferAvgBr < 10 || bufferAvgBr > 24) {
                    inc = 0;
                    ProgP = inc;
                    ProgRR.setProgress(ProgP);
                    mainToast = Toast.makeText(getApplicationContext(), "Measurement Failed", Toast.LENGTH_SHORT);
                    mainToast.show();
                    startTime = System.currentTimeMillis();
                    counter = 0;
                    processing.set(false);
                    return;
                }
                Breath = (int) bufferAvgBr;
            }
            if (Breath != 0) {
                Intent i = new Intent(RespirationProcess.this, RespirationResult.clreplaced);
                i.putExtra("bpm", Breath);
                i.putExtra("Usr", user);
                startActivity(i);
                finish();
            }
            if (RedAvg != 0) {
                ProgP = inc++ / 34;
                ProgRR.setProgress(ProgP);
            }
            processing.set(false);
        }
    };

    private final SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera.setPreviewDisplay(previewHolder);
                camera.setPreviewCallback(previewCallback);
            } catch (Throwable t) {
                Log.e("PreviewDemo-surfaceCallback", "Exception in setPreviewDisplay()", t);
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            Camera.Parameters parameters = camera.getParameters();
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            Camera.Size size = getSmallestPreviewSize(width, height, parameters);
            if (size != null) {
                parameters.setPreviewSize(size.width, size.height);
                Log.d(TAG, "Using width=" + size.width + " height=" + size.height);
            }
            camera.setParameters(parameters);
            camera.startPreview();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
        }
    };

    private static Camera.Size getSmallestPreviewSize(int width, int height, Camera.Parameters parameters) {
        Camera.Size result = null;
        for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
            if (size.width <= width && size.height <= height) {
                if (result == null) {
                    result = size;
                } else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;
                    if (newArea < resultArea)
                        result = size;
                }
            }
        }
        return result;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent i = new Intent(RespirationProcess.this, StartVitalSigns.clreplaced);
        i.putExtra("Usr", user);
        startActivity(i);
        finish();
    }
}

19 Source : AWindow.java
with MIT License
from xugaoxiang

@Override
@MainThread
public void setSubreplacedlesView(SurfaceView subreplacedlesSurfaceView) {
    setView(ID_SUBreplacedLES, subreplacedlesSurfaceView);
}

19 Source : AWindow.java
with MIT License
from xugaoxiang

@Override
@MainThread
public void setVideoView(SurfaceView videoSurfaceView) {
    setView(ID_VIDEO, videoSurfaceView);
}

19 Source : AWindow.java
with MIT License
from xugaoxiang

private void setView(int id, SurfaceView view) {
    ensureInitState();
    if (view == null)
        throw new NullPointerException("view is null");
    final SurfaceHelper surfaceHelper = mSurfaceHelpers[id];
    if (surfaceHelper != null)
        surfaceHelper.release();
    mSurfaceHelpers[id] = new SurfaceHelper(id, view);
}

19 Source : VideoViewAdapterUtil.java
with Apache License 2.0
from xuexiangjys

public static void composeDataItem1(final ArrayList<UserStatusData> users, HashMap<Integer, SurfaceView> uids, int localUid) {
    for (HashMap.Entry<Integer, SurfaceView> entry : uids.entrySet()) {
        SurfaceView surfaceV = entry.getValue();
        surfaceV.setZOrderOnTop(false);
        surfaceV.setZOrderMediaOverlay(false);
        searchUidsAndAppend(users, entry, localUid, UserStatusData.DEFAULT_STATUS, UserStatusData.DEFAULT_VOLUME, null);
    }
    removeNotExisted(users, uids, localUid);
}

19 Source : VideoViewAdapter.java
with Apache License 2.0
from xuexiangjys

@Override
public long gereplacedemId(int position) {
    UserStatusData user = mUsers.get(position);
    SurfaceView view = user.mView;
    if (view == null) {
        throw new NullPointerException("SurfaceView destroyed for user " + user.mUid + " " + user.mStatus + " " + user.mVolume);
    }
    return (String.valueOf(user.mUid) + System.idenreplacedyHashCode(view)).hashCode();
}

19 Source : GridVideoViewContainerAdapter.java
with Apache License 2.0
from xuexiangjys

@Override
public long gereplacedemId(int position) {
    UserStatusData user = mUsers.get(position);
    SurfaceView view = user.mView;
    if (view == null) {
        throw new NullPointerException("SurfaceView destroyed for user " + (user.mUid & 0xFFFFFFFFL) + " " + user.mStatus + " " + user.mVolume);
    }
    return (String.valueOf(user.mUid) + System.idenreplacedyHashCode(view)).hashCode();
}

19 Source : RtcFragment.java
with Apache License 2.0
from xuexiangjys

/**
 * Starts/Stops the local video preview
 *
 * @param start Whether to start/stop the local preview
 * @param view  The SurfaceView in which to render the preview
 * @param uid   User ID.
 */
protected void preview(boolean start, SurfaceView view, int uid) {
    if (start) {
        rtcEngine().setupLocalVideo(new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, uid));
        rtcEngine().startPreview();
    } else {
        rtcEngine().stopPreview();
    }
}

19 Source : BlindDateRoomFragment.java
with Apache License 2.0
from xuexiangjys

private void switchToSmallVideoView(int bigBgUid) {
    HashMap<Integer, SurfaceView> slice = new HashMap<>(1);
    slice.put(bigBgUid, mUidsList.get(bigBgUid));
    Iterator<SurfaceView> iterator = mUidsList.values().iterator();
    while (iterator.hasNext()) {
        SurfaceView s = iterator.next();
        s.setZOrderOnTop(true);
        s.setZOrderMediaOverlay(true);
    }
    mUidsList.get(bigBgUid).setZOrderOnTop(false);
    mUidsList.get(bigBgUid).setZOrderMediaOverlay(false);
    mGridVideoViewContainer.initViewContainer(getActivity(), bigBgUid, slice, mIsLandscape);
    bindToSmallVideoView(bigBgUid);
    mLayoutType = LAYOUT_TYPE_SMALL;
}

19 Source : BlindDateRoomFragment.java
with Apache License 2.0
from xuexiangjys

public void onVideoMuteClicked(View view) {
    if (mUidsList.size() == 0) {
        return;
    }
    SurfaceView surfaceV = getLocalView();
    if (surfaceV == null || surfaceV.getParent() == null) {
        return;
    }
    RtcEngine rtcEngine = rtcEngine();
    mVideoMuted = !mVideoMuted;
    if (mVideoMuted) {
        rtcEngine.disableVideo();
    } else {
        rtcEngine.enableVideo();
    }
    SwitchIconView iv = (SwitchIconView) view;
    iv.setIconEnabled(!mVideoMuted);
    hideLocalView(mVideoMuted);
}

19 Source : BlindDateRoomFragment.java
with Apache License 2.0
from xuexiangjys

private void doRenderRemoteUi(final int uid) {
    if (getActivity().isFinishing()) {
        return;
    }
    if (mUidsList.containsKey(uid)) {
        return;
    }
    SurfaceView surfaceV = RtcEngine.CreateRendererView(XUtil.getContext());
    mUidsList.put(uid, surfaceV);
    boolean useDefaultLayout = mLayoutType == LAYOUT_TYPE_DEFAULT;
    surfaceV.setZOrderOnTop(true);
    surfaceV.setZOrderMediaOverlay(true);
    rtcEngine().setupRemoteVideo(new VideoCanvas(surfaceV, VideoCanvas.RENDER_MODE_HIDDEN, uid));
    if (useDefaultLayout) {
        switchToDefaultVideoView();
    } else {
        int bigBgUid = mSmallVideoViewAdapter == null ? uid : mSmallVideoViewAdapter.getExceptedUid();
        switchToSmallVideoView(bigBgUid);
    }
}

19 Source : UserStatusData.java
with Apache License 2.0
from xuexiangjys

public clreplaced UserStatusData {

    public static final int DEFAULT_STATUS = 0;

    public static final int VIDEO_MUTED = 1;

    public static final int AUDIO_MUTED = VIDEO_MUTED << 1;

    public static final int DEFAULT_VOLUME = 0;

    public UserStatusData(int uid, SurfaceView view, Integer status, int volume) {
        this(uid, view, status, volume, null);
    }

    public UserStatusData(int uid, SurfaceView view, Integer status, int volume, VideoInfoData i) {
        this.mUid = uid;
        this.mView = view;
        this.mStatus = status;
        this.mVolume = volume;
        this.mVideoInfo = i;
    }

    public int mUid;

    public SurfaceView mView;

    // if status is null, do nothing
    public Integer mStatus;

    public int mVolume;

    private VideoInfoData mVideoInfo;

    public void setVideoInfo(VideoInfoData video) {
        mVideoInfo = video;
    }

    public VideoInfoData getVideoInfoData() {
        return mVideoInfo;
    }

    @Override
    public String toString() {
        return "UserStatusData{" + "mUid=" + (mUid & 0XFFFFFFFFL) + ", mView=" + mView + ", mStatus=" + mStatus + ", mVolume=" + mVolume + '}';
    }
}

19 Source : VideoChatActivity.java
with GNU General Public License v3.0
from xmmmmmovo

// Tutorial Step 3
private void setupLocalVideo() {
    FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container);
    SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
    surfaceView.setZOrderMediaOverlay(true);
    container.addView(surfaceView);
    mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_ADAPTIVE, 0));
}

19 Source : VideoChatActivity.java
with GNU General Public License v3.0
from xmmmmmovo

// Tutorial Step 5
private void setupRemoteVideo(int uid) {
    FrameLayout container = (FrameLayout) findViewById(R.id.remote_video_view_container);
    if (container.getChildCount() >= 1) {
        return;
    }
    SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
    container.addView(surfaceView);
    mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_ADAPTIVE, uid));
    // for mark purpose
    surfaceView.setTag(uid);
    // optional UI
    View tipMsg = findViewById(R.id.quick_tips_when_use_agora_sdk);
    tipMsg.setVisibility(View.GONE);
}

19 Source : VideoChatActivity.java
with GNU General Public License v3.0
from xmmmmmovo

// Tutorial Step 10
private void onRemoteUserVideoMuted(int uid, boolean muted) {
    FrameLayout container = (FrameLayout) findViewById(R.id.remote_video_view_container);
    SurfaceView surfaceView = (SurfaceView) container.getChildAt(0);
    Object tag = surfaceView.getTag();
    if (tag != null && (Integer) tag == uid) {
        surfaceView.setVisibility(muted ? View.GONE : View.VISIBLE);
    }
}

19 Source : MainActivity.java
with Apache License 2.0
from xingaijian

public clreplaced MainActivity extends AppCompatActivity {

    private SurfaceView mainSfCamera;

    CameraSurfaceHolder mCameraSurfaceHolder = new CameraSurfaceHolder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainSfCamera = (SurfaceView) findViewById(R.id.main_sf_camera);
        // android 6.0以上动态申请权限  或targetSdkVersion设置为23以下
        if (checkCameraHardware(MainActivity.this)) {
            mCameraSurfaceHolder.setCameraSurfaceHolder(this, mainSfCamera);
        }
    }

    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hreplacedystemFeature(PackageManager.FEATURE_CAMERA)) {
            Toast.makeText(this, "搜索到摄像头硬件", Toast.LENGTH_SHORT).show();
            return true;
        } else {
            Toast.makeText(this, "不具备摄像头硬件", Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}

19 Source : SurfaceViewPreview.java
with Apache License 2.0
from wzx54321

clreplaced SurfaceViewPreview extends PreviewImpl {

    final SurfaceView mSurfaceView;

    SurfaceViewPreview(Context context, ViewGroup parent) {
        final View view = View.inflate(context, R.layout.surface_view, parent);
        mSurfaceView = view.findViewById(R.id.surface_view);
        final SurfaceHolder holder = mSurfaceView.getHolder();
        // noinspection deprecation
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holder.addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceCreated(SurfaceHolder h) {
            }

            @Override
            public void surfaceChanged(SurfaceHolder h, int format, int width, int height) {
                setSize(width, height);
                if (!ViewCompat.isInLayout(mSurfaceView)) {
                    dispatchSurfaceChanged();
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder h) {
                setSize(0, 0);
            }
        });
    }

    @Override
    Surface getSurface() {
        return getSurfaceHolder().getSurface();
    }

    @Override
    SurfaceHolder getSurfaceHolder() {
        return mSurfaceView.getHolder();
    }

    @Override
    View getView() {
        return mSurfaceView;
    }

    @Override
    Clreplaced getOutputClreplaced() {
        return SurfaceHolder.clreplaced;
    }

    @Override
    void setDisplayOrientation(int displayOrientation) {
    }

    @Override
    boolean isReady() {
        return getWidth() != 0 && getHeight() != 0;
    }
}

19 Source : WebViewFragment.java
with GNU General Public License v3.0
from wncc

@Override
public void onPause() {
    if (mCameraSource != null) {
        SurfaceView surfaceView = getView().findViewById(R.id.qr_camera_surfaceview);
        mCameraSource.stop();
        surfaceView.setVisibility(View.GONE);
    }
    super.onPause();
}

19 Source : FermiSystemMediaPlayer.java
with MIT License
from wladimir-computin

public void setSurfaceView(SurfaceView surfaceView) {
    surfaceView.getHolder().addCallback(this);
}

19 Source : RxPermissionActivity.java
with MIT License
from why168

/**
 * RxPermissionGen框架
 *
 * @author Edwin.Wu
 * @version 2017/3/19 14:17
 * @since JDK1.8
 */
public clreplaced RxPermissionActivity extends AppCompatActivity {

    private static final String TAG = "RxPermissionsSample";

    private Camera camera;

    private SurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.setLogging(true);
        setContentView(R.layout.activity_rx_permission);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        RxView.clicks(findViewById(R.id.enableCamera)).compose(rxPermissions.ensureEach(Manifest.permission.READ_EXTERNAL_STORAGE)).subscribe(new Action1<Permission>() {

            @Override
            public void call(Permission permission) {
                Log.i(TAG, "Permission result " + permission);
                if (permission.granted) {
                    releaseCamera();
                    camera = Camera.open(0);
                    try {
                        camera.setPreviewDisplay(surfaceView.getHolder());
                        camera.startPreview();
                    } catch (IOException e) {
                        Log.e(TAG, "Error while trying to display the camera preview", e);
                    }
                } else if (permission.shouldShowRequestPermissionRationale) {
                    // Denied permission without ask never again
                    Toast.makeText(RxPermissionActivity.this, "Denied permission without ask never again", Toast.LENGTH_SHORT).show();
                } else {
                    // Denied perm`ission with ask never again
                    // Need to go to the settings
                    Toast.makeText(RxPermissionActivity.this, "Permission denied, can't enable the camera", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Action1<Throwable>() {

            @Override
            public void call(Throwable t) {
                Log.e(TAG, "onError", t);
            }
        }, new Action0() {

            @Override
            public void call() {
                Log.i(TAG, "OnComplete");
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        releaseCamera();
    }

    private void releaseCamera() {
        if (camera != null) {
            camera.release();
            camera = null;
        }
    }
}

19 Source : PlayerView.java
with Apache License 2.0
from wheat7

// setSurfaceView
private void setSurfaceView(SurfaceView surfaceView) {
    mSurfaceView = surfaceView;
    mSurfaceView.getHolder().addCallback(new SurfaceCallBack());
}

19 Source : CaptureActivity.java
with Apache License 2.0
from weexteam

@Override
protected void onResume() {
    super.onResume();
    // historyManager must be initialized here to update the history
    // preference
    historyManager = new HistoryManager(this);
    historyManager.trimHistory();
    // CameraManager must be initialized here, not in onCreate(). This is
    // necessary because we don't
    // want to open the camera driver and measure the screen size if we're
    // going to show the help on
    // first launch. That led to bugs where the scanning rectangle was the
    // wrong size and partially
    // off screen.
    cameraManager = new CameraManager(getApplication());
    viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
    viewfinderView.setCameraManager(cameraManager);
    resultView = findViewById(R.id.result_view);
    statusView = (TextView) findViewById(R.id.status_view);
    handler = null;
    lastResult = null;
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // if (prefs.getBoolean(PreferencesActivity.KEY_DISABLE_AUTO_ORIENTATION,
    // true)) {
    // setRequestedOrientation(getCurrentOrientation());
    // } else {
    // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    // }
    resetStatusView();
    beepManager.updatePrefs();
    ambientLightManager.start(cameraManager);
    inactivityTimer.onResume();
    Intent intent = getIntent();
    copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true) && (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
    source = IntentSource.NONE;
    sourceUrl = null;
    scanFromWebPageManager = null;
    decodeFormats = null;
    characterSet = null;
    if (intent != null) {
        String action = intent.getAction();
        String dataString = intent.getDataString();
        if (Intents.Scan.ACTION.equals(action)) {
            // Scan the formats the intent requested, and return the result
            // to the calling activity.
            source = IntentSource.NATIVE_APP_INTENT;
            decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
            decodeHints = DecodeHintManager.parseDecodeHints(intent);
            if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
                int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
                int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
                if (width > 0 && height > 0) {
                    cameraManager.setManualFramingRect(width, height);
                }
            }
            if (intent.hasExtra(Intents.Scan.CAMERA_ID)) {
                int cameraId = intent.getIntExtra(Intents.Scan.CAMERA_ID, -1);
                if (cameraId >= 0) {
                    cameraManager.setManualCameraId(cameraId);
                }
            }
            String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
            if (customPromptMessage != null) {
                statusView.setText(customPromptMessage);
            }
        } else if (dataString != null && dataString.contains("http://www.google") && dataString.contains("/m/products/scan")) {
            // Scan only products and send the result to mobile Product
            // Search.
            source = IntentSource.PRODUCT_SEARCH_LINK;
            sourceUrl = dataString;
            decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
        } else if (isZXingURL(dataString)) {
            // Scan formats requested in query string (all formats if none
            // specified).
            // If a return URL is specified, send the results there.
            // Otherwise, handle it ourselves.
            source = IntentSource.ZXING_LINK;
            sourceUrl = dataString;
            Uri inputUri = Uri.parse(dataString);
            scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
            decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
            // Allow a sub-set of the hints to be specified by the caller.
            decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
        }
        characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
    }
    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hreplacedurface) {
        // The activity was paused but not stopped, so the surface still
        // exists. Therefore
        // surfaceCreated() won't be called, so init the camera here.
        initCamera(surfaceHolder);
    } else {
        // Install the callback and wait for surfaceCreated() to init the
        // camera.
        surfaceHolder.addCallback(this);
    }
}

19 Source : CaptureActivity.java
with Apache License 2.0
from weexteam

@Override
protected void onPause() {
    if (handler != null) {
        handler.quitSynchronously();
        handler = null;
    }
    inactivityTimer.onPause();
    ambientLightManager.stop();
    beepManager.close();
    cameraManager.closeDriver();
    // historyManager = null; // Keep for onActivityResult
    if (!hreplacedurface) {
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        surfaceHolder.removeCallback(this);
    }
    super.onPause();
}

19 Source : SimpleExoPlayer.java
with GNU General Public License v2.0
from warren-bank

@Override
public void setVideoSurfaceView(SurfaceView surfaceView) {
    setVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder());
}

19 Source : SimpleExoPlayer.java
with GNU General Public License v2.0
from warren-bank

@Override
public void clearVideoSurfaceView(SurfaceView surfaceView) {
    clearVideoSurfaceHolder(surfaceView == null ? null : surfaceView.getHolder());
}

19 Source : MyMediaPlayer.java
with GNU General Public License v3.0
from wangchen11

public clreplaced MyMediaPlayer extends MediaPlayer {

    SurfaceView mSurfaceView = null;

    public MyMediaPlayer() {
    }
}

19 Source : SurfaceViewPreview.java
with Apache License 2.0
from wajahatkarim3

clreplaced SurfaceViewPreview extends PreviewImpl {

    final SurfaceView mSurfaceView;

    SurfaceViewPreview(Context context, ViewGroup parent) {
        final View view = View.inflate(context, R.layout.surface_view, parent);
        mSurfaceView = (SurfaceView) view.findViewById(R.id.surface_view);
        final SurfaceHolder holder = mSurfaceView.getHolder();
        // noinspection deprecation
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holder.addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceCreated(SurfaceHolder h) {
            }

            @Override
            public void surfaceChanged(SurfaceHolder h, int format, int width, int height) {
                setSize(width, height);
                if (!ViewCompat.isInLayout(mSurfaceView)) {
                    dispatchSurfaceChanged();
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder h) {
                setSize(0, 0);
            }
        });
    }

    @Override
    Surface getSurface() {
        return getSurfaceHolder().getSurface();
    }

    @Override
    SurfaceHolder getSurfaceHolder() {
        return mSurfaceView.getHolder();
    }

    @Override
    View getView() {
        return mSurfaceView;
    }

    @Override
    Clreplaced getOutputClreplaced() {
        return SurfaceHolder.clreplaced;
    }

    @Override
    void setDisplayOrientation(int displayOrientation) {
    }

    @Override
    boolean isReady() {
        return getWidth() != 0 && getHeight() != 0;
    }
}

19 Source : VIACamera.java
with MIT License
from via-intelligent-vision

// public enum FAKE_MODE {
// CPURender,
// GPURender,
// }
public static VIACamera create(MODE mode, String videoPath, SurfaceView displayView) throws Exception {
    switch(mode) {
        case FakeCameraGPU:
            File f = new File(videoPath);
            if (f.exists() && f.canRead()) {
                return new FakeCameraGPU(videoPath, displayView);
            } else {
                throw new Exception(videoPath + " is not exist or can not read!");
            }
        default:
            throw new Exception("This is FakeCameraGPU Constructor, If you want to go normal Camera path, please using create(MODE mode, Context context, int index, int width, int height, SurfaceView displayView)");
    }
}

19 Source : MotionVisualizer.java
with GNU General Public License v3.0
from vbier

/**
 * Visualizes motion areas on the given mSurface view.
 */
public clreplaced MotionVisualizer implements IMotionListener {

    private final SurfaceView mMotionView;

    private final NavigationView mNavigationView;

    private final SharedPreferences mPreferences;

    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private final int mMotionTextWidth;

    private final int mDarkTextWidth;

    private final int mCameraRotation;

    private int mCorrectionAngle;

    public MotionVisualizer(SurfaceView motionView, NavigationView navigationView, SharedPreferences preferences, int cameraRotation, int scaledSize) {
        mMotionView = motionView;
        mNavigationView = navigationView;
        mPreferences = preferences;
        mCameraRotation = cameraRotation;
        int newDeviceRotation = ((Activity) mMotionView.getContext()).getWindowManager().getDefaultDisplay().getRotation();
        setDeviceRotation(newDeviceRotation);
        mMotionView.setZOrderOnTop(true);
        mMotionView.getHolder().setFormat(PixelFormat.TRANSPARENT);
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setTextSize(scaledSize);
        Rect bounds = new Rect();
        mPaint.getTextBounds(mNavigationView.getContext().getString(R.string.motion), 0, 6, bounds);
        mMotionTextWidth = bounds.width();
        mPaint.getTextBounds(mNavigationView.getContext().getString(R.string.tooDark), 0, 8, bounds);
        mDarkTextWidth = bounds.width();
    }

    @Override
    public void motionDetected(ArrayList<Point> differing) {
        boolean showPreview = mPreferences.getBoolean(Constants.PREF_MOTION_DETECTION_PREVIEW, false);
        boolean motionDetection = mPreferences.getBoolean(Constants.PREF_MOTION_DETECTION_ENABLED, false);
        if (showPreview && motionDetection && mMotionView.getHolder().getSurface().isValid()) {
            final Canvas canvas = mMotionView.getHolder().lockCanvas();
            if (canvas != null) {
                try {
                    int boxes = Integer.parseInt(mPreferences.getString(Constants.PREF_MOTION_DETECTION_GRANULARITY, "20"));
                    float xsize = canvas.getWidth() / (float) boxes;
                    float ysize = canvas.getHeight() / (float) boxes;
                    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                    if (mNavigationView.isShown()) {
                        Rect r1 = new Rect();
                        mNavigationView.getGlobalVisibleRect(r1);
                        Rect r2 = new Rect();
                        mMotionView.getGlobalVisibleRect(r2);
                        if (r1.left == 0) {
                            // drawer from left
                            canvas.clipRect(r1.right - r2.left, 0, r2.right, r2.bottom);
                        } else {
                            // drawer from right
                            canvas.clipRect(0, 0, r1.left - r2.left, r2.bottom);
                        }
                    }
                    canvas.drawText(mNavigationView.getContext().getString(R.string.motion), (canvas.getWidth() - mMotionTextWidth) / 2f, 50, mPaint);
                    for (Point p : differing) {
                        Point c = correctSensorRotation(p, mCorrectionAngle, boxes);
                        canvas.drawRect(c.x * xsize, c.y * ysize, c.x * xsize + xsize, c.y * ysize + ysize, mPaint);
                    }
                } finally {
                    mMotionView.getHolder().unlockCanvasAndPost(canvas);
                }
            }
        }
    }

    private Point correctSensorRotation(Point p, int correctionAngle, int boxes) {
        if (correctionAngle == 270) {
            return new Point(boxes - 1 - p.y, boxes - 1 - p.x);
        } else if (correctionAngle == 180) {
            return new Point(boxes - 1 - p.x, p.y);
        } else if (correctionAngle == 90) {
            return new Point(p.y, boxes - 1 - p.x);
        } else {
            return new Point(p.x, boxes - 1 - p.y);
        }
    }

    @Override
    public void noMotion() {
        boolean showPreview = mPreferences.getBoolean(Constants.PREF_MOTION_DETECTION_PREVIEW, false);
        boolean motionDetection = mPreferences.getBoolean(Constants.PREF_MOTION_DETECTION_ENABLED, false);
        if (showPreview && motionDetection && mMotionView.getHolder().getSurface().isValid()) {
            final Canvas canvas = mMotionView.getHolder().lockCanvas();
            if (canvas != null) {
                canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                mMotionView.getHolder().unlockCanvasAndPost(canvas);
            }
        }
    }

    @Override
    public void tooDark() {
        boolean showPreview = mPreferences.getBoolean(Constants.PREF_MOTION_DETECTION_PREVIEW, false);
        boolean motionDetection = mPreferences.getBoolean(Constants.PREF_MOTION_DETECTION_ENABLED, false);
        if (showPreview && motionDetection && mMotionView.getHolder().getSurface().isValid()) {
            final Canvas canvas = mMotionView.getHolder().lockCanvas();
            if (canvas != null) {
                canvas.drawText(mNavigationView.getContext().getString(R.string.tooDark), (canvas.getWidth() - mDarkTextWidth) / 2f, 50, mPaint);
                mMotionView.getHolder().unlockCanvasAndPost(canvas);
            }
        }
    }

    public void setDeviceRotation(int newDeviceRotation) {
        mCorrectionAngle = (mCameraRotation - newDeviceRotation * 90 + 360) % 360;
    }
}

19 Source : MainActivity.java
with GNU General Public License v3.0
from vbier

public void updateMotionPreferences() {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    if (mCam != null) {
        mCam.updateFromPreferences(prefs);
    }
    if (mMotionDetector != null) {
        mMotionDetector.updateFromPreferences(prefs);
    }
    SurfaceView motionView = findViewById(R.id.motionView);
    boolean showPreview = prefs.getBoolean(Constants.PREF_MOTION_DETECTION_PREVIEW, false);
    if (showPreview && mCam != null && mCam.canBeUsed()) {
        ViewGroup.LayoutParams params = motionView.getLayoutParams();
        params.height = 480;
        params.width = 640;
        motionView.setLayoutParams(params);
        motionView.setVisibility(View.VISIBLE);
    } else {
        motionView.setVisibility(View.INVISIBLE);
    }
}

19 Source : CameraSurfaceView.java
with Apache License 2.0
from Vanish136

/**
 * Created by LWK
 * TODO 录像预览SurfaceView,支持手动对焦和缩放
 * 2016/11/2
 */
public clreplaced CameraSurfaceView extends FrameLayout implements Camera.AutoFocusCallback {

    private final String TAG = "CameraSurfaceView";

    // 用于判断双击事件的两次按下事件的间隔
    private static final long DOUBLE_CLICK_INTERVAL = 200;

    // 延迟展示画面的时间
    private final int DELAY_SHOW_VIEW_DURATION = 100;

    private long mLastTouchDownTime;

    private CameraMgr mCameraMgr;

    private ZoomRunnable mZoomRunnable;

    // 对焦动画视图
    private ImageView mFocusAnimationView;

    private Animation mFocusAnimation;

    // 相机指示图片
    private ImageView mIndicatorView;

    private Animation mIndicatorAnimation;

    private boolean mIsIndicatorAnimFinished;

    private SurfaceView mSurfaceView;

    public CameraSurfaceView(Context context) {
        super(context);
        initUI(context, null);
    }

    public CameraSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initUI(context, attrs);
    }

    private void initUI(Context context, AttributeSet attrs) {
        inflate(context, R.layout.layout_camera_surface_view, this);
        setWillNotDraw(false);
        mSurfaceView = (SurfaceView) findViewById(R.id.sfv_shortvideo_record_camera_perview);
        // 添加一个占位视图,解决下面添加的对焦动画视图,若layout调整到他的上面,视图会被切掉的bug
        addView(new View(getContext()));
        // 添加相机画面指示视图
        mIndicatorView = new ImageView(context);
        mIndicatorView.setImageResource(R.drawable.ic_shortvideo_indicator);
        addView(mIndicatorView, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
        // 指示图动画
        mIndicatorAnimation = AnimationUtils.loadAnimation(context, R.anim.indicator_animation);
        mIndicatorAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIndicatorView.setVisibility(INVISIBLE);
                mIsIndicatorAnimFinished = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        // 添加对焦动画视图
        mFocusAnimationView = new ImageView(context);
        mFocusAnimationView.setVisibility(INVISIBLE);
        mFocusAnimationView.setImageResource(R.drawable.ic_shortvideo_focus);
        addView(mFocusAnimationView, new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
        // 定义对焦动画
        mFocusAnimation = AnimationUtils.loadAnimation(context, R.anim.focus_animation);
        mFocusAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mFocusAnimationView.setVisibility(INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        mIndicatorView.postDelayed(new Runnable() {

            @Override
            public void run() {
                mSurfaceView.setVisibility(VISIBLE);
                mIndicatorView.startAnimation(mIndicatorAnimation);
            }
        }, DELAY_SHOW_VIEW_DURATION);
    }

    // 关联相机管理对象
    public void setCameraManager(CameraMgr cameraMgr) {
        this.mCameraMgr = cameraMgr;
    }

    private Camera getCamera() {
        return mCameraMgr != null ? mCameraMgr.getCamera() : null;
    }

    public SurfaceView getSurfaceView() {
        return mSurfaceView;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                long downTime = System.currentTimeMillis();
                if (getCamera().getParameters().isZoomSupported() && downTime - mLastTouchDownTime <= DOUBLE_CLICK_INTERVAL) {
                    zoomPreview();
                }
                mLastTouchDownTime = downTime;
                focusOnTouch(event.getX(), event.getY());
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void onAutoFocus(boolean success, Camera camera) {
        // 设置对焦方式为视频连续对焦
        mCameraMgr.setCameraFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
    }

    /**
     * 放大预览视图
     */
    private void zoomPreview() {
        if (getCamera() == null)
            return;
        Camera.Parameters parameters = getCamera().getParameters();
        int currentZoom = parameters.getZoom();
        int maxZoom = (int) (parameters.getMaxZoom() / 2f + 0.5);
        int destZoom = 0 == currentZoom ? maxZoom : 0;
        if (parameters.isSmoothZoomSupported()) {
            getCamera().stopSmoothZoom();
            getCamera().startSmoothZoom(destZoom);
        } else {
            Handler handler = getHandler();
            if (null == handler)
                return;
            handler.removeCallbacks(mZoomRunnable);
            handler.post(mZoomRunnable = new ZoomRunnable(destZoom, currentZoom, getCamera()));
        }
    }

    public void focusOnTouch(final float x, final float y) {
        getCamera().cancelAutoFocus();
        // 设置对焦方式为自动对焦
        mCameraMgr.setCameraFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        getCamera().autoFocus(this);
        mFocusAnimation.cancel();
        mFocusAnimationView.clearAnimation();
        if (mIsIndicatorAnimFinished) {
            int left = (int) (x - mFocusAnimationView.getWidth() / 2f);
            int top = (int) (y - mFocusAnimationView.getHeight() / 2f);
            FrameLayout.LayoutParams layoutParams = (LayoutParams) mFocusAnimationView.getLayoutParams();
            layoutParams.gravity = Gravity.NO_GRAVITY;
            layoutParams.topMargin = top;
            layoutParams.leftMargin = left;
            mFocusAnimationView.setLayoutParams(layoutParams);
        }
        mFocusAnimationView.setVisibility(VISIBLE);
        mFocusAnimationView.startAnimation(mFocusAnimation);
    }

    /**
     * 放大预览视图任务
     */
    private static clreplaced ZoomRunnable implements Runnable {

        int destZoom, currentZoom;

        WeakReference<Camera> cameraWeakRef;

        public ZoomRunnable(int destZoom, int currentZoom, Camera camera) {
            this.destZoom = destZoom;
            this.currentZoom = currentZoom;
            cameraWeakRef = new WeakReference<>(camera);
        }

        @Override
        public void run() {
            Camera camera = cameraWeakRef.get();
            if (null == camera)
                return;
            boolean zoomUp = destZoom > currentZoom;
            for (int i = currentZoom; zoomUp ? i <= destZoom : i >= destZoom; i = (zoomUp ? ++i : --i)) {
                Camera.Parameters parameters = camera.getParameters();
                parameters.setZoom(i);
                camera.setParameters(parameters);
            }
        }
    }
}

19 Source : CallVideoFragment.java
with GNU General Public License v3.0
from treasure-lau

private void fixZOrder(SurfaceView video, SurfaceView preview) {
    video.setZOrderOnTop(false);
    preview.setZOrderOnTop(true);
    // Needed to be able to display control layout over
    preview.setZOrderMediaOverlay(true);
}

19 Source : PlayerView.java
with GNU General Public License v3.0
from toponteam

/**
 * Add surfaceView
 */
public void addSurfaceView() {
    try {
        Log.i(TAG, "addSurfaceView");
        SurfaceView mSurfaceView = new SurfaceView(getContext());
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceHolder.setFormat(PixelFormat.RGBA_8888);
        mSurfaceHolder.setKeepScreenOn(true);
        mSurfaceHolder.addCallback(new MySurceHoldeCallback());
        mLlSurContainer.addView(mSurfaceView, -1, -1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

19 Source : BaseVideoActivity.java
with Apache License 2.0
from tony-Shx

/**
 * Created by 宋浩祥 on 2017/4/15.
 */
public clreplaced BaseVideoActivity extends Activity {

    private final static String TAG = BaseVideoActivity.clreplaced.getSimpleName();

    protected SurfaceView mPreviewSurface;

    private SurfaceView mFaceSurface;

    protected Camera mCamera;

    protected int mCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;

    // Camera nv21格式预览帧的尺寸,默认设置640*480
    protected int PREVIEW_WIDTH = 640;

    protected int PREVIEW_HEIGHT = 480;

    // 预览帧数据存储数组和缓存数组
    protected byte[] nv21;

    protected byte[] buffer;

    // 缩放矩阵
    private Matrix mScaleMatrix = new Matrix();

    // 加速度感应器,用于获取手机的朝向
    private Accelerometer mAcc;

    // FaceDetector对象,集成了离线人脸识别:人脸检测、视频流检测功能
    private FaceDetector mFaceDetector;

    private boolean mStopTrack;

    private Toast mToast;

    private long mLastClickTime;

    private int isAlign = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SpeechUtility.createUtility(this, "appid=58c8e767");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        initUI();
        nv21 = new byte[PREVIEW_WIDTH * PREVIEW_HEIGHT * 2];
        buffer = new byte[PREVIEW_WIDTH * PREVIEW_HEIGHT * 2];
        mAcc = new Accelerometer(BaseVideoActivity.this);
        mFaceDetector = FaceDetector.createDetector(BaseVideoActivity.this, null);
    }

    private Callback mPreviewCallback = new Callback() {

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            closeCamera();
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            openCamera();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            mScaleMatrix.setScale(width / (float) PREVIEW_HEIGHT, height / (float) PREVIEW_WIDTH);
        }
    };

    private void setSurfaceSize() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        int height = (int) (width * PREVIEW_WIDTH / (float) PREVIEW_HEIGHT);
        RelativeLayout.LayoutParams params = new LayoutParams(width, height);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        mPreviewSurface.setLayoutParams(params);
        mFaceSurface.setLayoutParams(params);
    }

    @SuppressLint("ShowToast")
    @SuppressWarnings("deprecation")
    private void initUI() {
        mPreviewSurface = (SurfaceView) findViewById(R.id.sfv_preview);
        mFaceSurface = (SurfaceView) findViewById(R.id.sfv_face);
        mPreviewSurface.getHolder().addCallback(mPreviewCallback);
        mPreviewSurface.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mFaceSurface.setZOrderOnTop(true);
        mFaceSurface.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        // 点击SurfaceView,切换摄相头
        mFaceSurface.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 只有一个摄相头,不支持切换
                if (Camera.getNumberOfCameras() == 1) {
                    showTip("只有后置摄像头,不能切换");
                    return;
                }
                closeCamera();
                if (CameraInfo.CAMERA_FACING_FRONT == mCameraId) {
                    mCameraId = CameraInfo.CAMERA_FACING_BACK;
                } else {
                    mCameraId = CameraInfo.CAMERA_FACING_FRONT;
                }
                openCamera();
            }
        });
        // 长按SurfaceView 500ms后松开,摄相头聚集
        mFaceSurface.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mLastClickTime = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (System.currentTimeMillis() - mLastClickTime > 500) {
                            mCamera.autoFocus(null);
                            return true;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        RadioGroup alignGruop = (RadioGroup) findViewById(R.id.align_mode);
        alignGruop.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                switch(arg1) {
                    case R.id.detect:
                        isAlign = 0;
                        break;
                    case R.id.align:
                        isAlign = 1;
                        break;
                    default:
                        break;
                }
            }
        });
        setSurfaceSize();
        mToast = Toast.makeText(BaseVideoActivity.this, "", Toast.LENGTH_SHORT);
    }

    protected void openCamera() {
        if (null != mCamera) {
            return;
        }
        if (!checkCameraPermission()) {
            showTip("摄像头权限未打开,请打开后再试");
            mStopTrack = true;
            return;
        }
        // 只有一个摄相头,打开后置
        if (Camera.getNumberOfCameras() == 1) {
            mCameraId = CameraInfo.CAMERA_FACING_BACK;
        }
        try {
            mCamera = Camera.open(mCameraId);
            if (CameraInfo.CAMERA_FACING_FRONT == mCameraId) {
                showTip("前置摄像头已开启,点击可切换");
            } else {
                showTip("后置摄像头已开启,点击可切换");
            }
        } catch (Exception e) {
            e.printStackTrace();
            closeCamera();
            return;
        }
        Parameters params = mCamera.getParameters();
        params.setPreviewFormat(ImageFormat.NV21);
        params.setPreviewSize(PREVIEW_WIDTH, PREVIEW_HEIGHT);
        mCamera.setParameters(params);
        // 设置显示的偏转角度,大部分机器是顺时针90度,某些机器需要按情况设置
        mCamera.setDisplayOrientation(90);
        mCamera.setPreviewCallback(new PreviewCallback() {

            @Override
            public void onPreviewFrame(byte[] data, Camera camera) {
                System.arraycopy(data, 0, nv21, 0, data.length);
            }
        });
        try {
            mCamera.setPreviewDisplay(mPreviewSurface.getHolder());
            mCamera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (mFaceDetector == null) {
            // 创建单例失败,与 21001 错误为同样原因,参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
            showTip("创建对象失败,请确认 libmsc.so 放置正确,\n 且有调用 createUtility 进行初始化");
        }
    }

    private void closeCamera() {
        if (null != mCamera) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    private boolean checkCameraPermission() {
        int status = checkPermission(permission.CAMERA, Process.myPid(), Process.myUid());
        return PackageManager.PERMISSION_GRANTED == status;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != mAcc) {
            mAcc.start();
        }
        mStopTrack = false;
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (!mStopTrack) {
                    if (null == nv21) {
                        continue;
                    }
                    synchronized (nv21) {
                        System.arraycopy(nv21, 0, buffer, 0, nv21.length);
                    }
                    // 获取手机朝向,返回值0,1,2,3分别表示0,90,180和270度
                    int direction = Accelerometer.getDirection();
                    boolean frontCamera = (Camera.CameraInfo.CAMERA_FACING_FRONT == mCameraId);
                    // 前置摄像头预览显示的是镜像,需要将手机朝向换算成摄相头视角下的朝向。
                    // 转换公式:a' = (360 - a)%360,a为人眼视角下的朝向(单位:角度)
                    if (frontCamera) {
                        // SDK中使用0,1,2,3,4分别表示0,90,180,270和360度
                        direction = (4 - direction) % 4;
                    }
                    if (mFaceDetector == null) {
                        // 创建单例失败,与 21001 错误为同样原因,参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
                        showTip("创建对象失败,请确认 libmsc.so 放置正确,\n 且有调用 createUtility 进行初始化");
                        break;
                    }
                    String result = mFaceDetector.trackNV21(buffer, PREVIEW_WIDTH, PREVIEW_HEIGHT, isAlign, direction);
                    // Log.d(TAG, "result:"+result);
                    FaceRect[] faces = ParseResult.parseResult(result);
                    Canvas canvas = mFaceSurface.getHolder().lockCanvas();
                    if (null == canvas) {
                        continue;
                    }
                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
                    canvas.setMatrix(mScaleMatrix);
                    if (faces == null || faces.length <= 0) {
                        mFaceSurface.getHolder().unlockCanvasAndPost(canvas);
                        continue;
                    }
                    if (null != faces && frontCamera == (Camera.CameraInfo.CAMERA_FACING_FRONT == mCameraId)) {
                        for (FaceRect face : faces) {
                            face.bound = PictureUtil.RotateDeg90(face.bound, PREVIEW_WIDTH, PREVIEW_HEIGHT);
                            if (face.point != null) {
                                for (int i = 0; i < face.point.length; i++) {
                                    face.point[i] = PictureUtil.RotateDeg90(face.point[i], PREVIEW_WIDTH, PREVIEW_HEIGHT);
                                }
                            }
                            PictureUtil.drawFaceRect(canvas, face, PREVIEW_WIDTH, PREVIEW_HEIGHT, frontCamera, false);
                        }
                    } else {
                        Log.d(TAG, "faces:0");
                    }
                    mFaceSurface.getHolder().unlockCanvasAndPost(canvas);
                }
            }
        }).start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeCamera();
        if (null != mAcc) {
            mAcc.stop();
        }
        mStopTrack = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mFaceDetector) {
            // 销毁对象
            mFaceDetector.destroy();
        }
    }

    private void showTip(final String str) {
        mToast.setText(str);
        mToast.show();
    }
}

19 Source : CaptureActivity.java
with Apache License 2.0
from TommyLemon

/**
 * 初始化,必须在setContentView之后
 *  @param context
 *  @param viewfinderView
 */
protected void init(Activity context, SurfaceView surfaceView, ViewfinderView viewfinderView) {
    this.context = context;
    this.surfaceView = surfaceView;
    this.viewfinderView = viewfinderView;
    CameraManager.init(getApplication());
    hreplacedurface = false;
    inactivityTimer = new InactivityTimer(this);
}

19 Source : CameraManager.java
with GNU Affero General Public License v3.0
from threema-ch

/**
 * Opens the camera driver and initializes the hardware parameters.
 *
 * @param holder The surface object which the camera will draw preview frames into.
 * @throws IOException Indicates the camera driver failed to open.
 */
public synchronized void openDriver(SurfaceHolder holder, SurfaceView surfaceView) throws IOException {
    OpenCamera theCamera = camera;
    if (theCamera == null) {
        theCamera = OpenCameraInterface.open(OpenCameraInterface.NO_REQUESTED_CAMERA);
        if (theCamera == null) {
            throw new IOException("Camera.open() failed to return object from driver");
        }
        camera = theCamera;
    }
    if (!initialized) {
        initialized = true;
        configManager.initFromCameraParameters(theCamera);
        if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) {
            setManualFramingRect(requestedFramingRectWidth, requestedFramingRectHeight);
            requestedFramingRectWidth = 0;
            requestedFramingRectHeight = 0;
        }
    }
    Camera cameraObject = theCamera.getCamera();
    Camera.Parameters parameters = cameraObject.getParameters();
    // Save these, temporarily
    String parametersFlattened = parameters == null ? null : parameters.flatten();
    try {
        configManager.setDesiredCameraParameters(theCamera, false);
    } catch (RuntimeException re) {
        // Driver failed
        logger.info("Camera rejected parameters. Setting only minimal safe-mode parameters");
        logger.info("Resetting to saved camera params: " + parametersFlattened);
        // Reset:
        if (parametersFlattened != null) {
            parameters = cameraObject.getParameters();
            parameters.unflatten(parametersFlattened);
            try {
                cameraObject.setParameters(parameters);
                configManager.setDesiredCameraParameters(theCamera, true);
            } catch (RuntimeException re2) {
                // Well, darn. Give up
                logger.info("Camera rejected even safe-mode parameters! No configuration");
            }
        }
    }
    if (parameters != null) {
        // adjust surface view to match aspect ratio
        Camera.Size previewSize = cameraObject.getParameters().getPreviewSize();
        boolean rotated = theCamera.getOrientation() == 90 || theCamera.getOrientation() == 270;
        int previewWidth = rotated ? previewSize.height : previewSize.width;
        int previewHeight = rotated ? previewSize.width : previewSize.height;
        int containerWidth = ((FrameLayout) surfaceView.getParent()).getWidth();
        int containerHeight = ((FrameLayout) surfaceView.getParent()).getHeight();
        float aspectRatio = Math.min((float) containerWidth / (float) previewWidth, (float) containerHeight / (float) previewHeight);
        // adjust the bounds of the preview to fully match at least one edge of the container by keeping the original aspect ratio of the camera image
        if (aspectRatio >= 1) {
            previewHeight = Math.round((float) previewHeight * aspectRatio);
            previewWidth = Math.round((float) previewWidth * aspectRatio);
        }
        android.widget.FrameLayout.LayoutParams params = new android.widget.FrameLayout.LayoutParams(previewWidth, previewHeight);
        surfaceView.setLayoutParams(params);
        surfaceView.setX((float) (containerWidth - previewWidth) / 2);
        surfaceView.setY((float) (containerHeight - previewHeight) / 2);
    }
    cameraObject.setPreviewDisplay(holder);
}

19 Source : CaptureActivity.java
with GNU Affero General Public License v3.0
from threema-ch

private void initCamera(SurfaceHolder surfaceHolder, SurfaceView surfaceView) {
    if (surfaceHolder == null) {
        throw new IllegalStateException("No SurfaceHolder provided");
    }
    if (cameraManager.isOpen()) {
        // Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
        return;
    }
    try {
        cameraManager.openDriver(surfaceHolder, surfaceView);
        // Creating the handler starts the preview, which can also throw a RuntimeException.
        if (handler == null) {
            handler = new CaptureActivityHandler(this, cameraManager);
        }
    } catch (Exception e) {
        Toast.makeText(this, R.string.msg_camera_framework_bug, Toast.LENGTH_LONG).show();
        returnResult(null);
    }
}

19 Source : CameraOld.java
with MIT License
from ThinkKeep

@Override
public void setDisplayPreview(SurfaceView surfaceView) {
    this.surfaceView = surfaceView;
}

19 Source : CompassActivity.java
with MIT License
from thegenuinegourav

public clreplaced CompreplacedActivity extends Activity {

    private static final String TAG = "CompreplacedActivity";

    private Compreplaced compreplaced;

    SurfaceView cameraPreview;

    SurfaceHolder previewHolder;

    Camera camera;

    boolean inPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compreplaced);
        compreplaced = new Compreplaced(this);
        compreplaced.arrowView = (ImageView) findViewById(R.id.main_image_hands);
        final EditText editText = (EditText) findViewById(R.id.search_button);
        editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // do here your stuff f
                    editText.setText("");
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });
        inPreview = false;
        cameraPreview = (SurfaceView) findViewById(R.id.cameraPreview);
        previewHolder = cameraPreview.getHolder();
        previewHolder.addCallback(surfaceCallback);
        previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "start compreplaced");
        compreplaced.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        compreplaced.stop();
        if (inPreview) {
            camera.stopPreview();
        }
        camera.release();
        camera = null;
        inPreview = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        compreplaced.start();
        camera = Camera.open();
        camera.setDisplayOrientation(90);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "stop compreplaced");
        compreplaced.stop();
    }

    private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
        Camera.Size result = null;
        for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
            if (size.width <= width && size.height <= height) {
                if (result == null) {
                    result = size;
                } else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;
                    if (newArea > resultArea) {
                        result = size;
                    }
                }
            }
        }
        return (result);
    }

    SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {

        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera.setPreviewDisplay(previewHolder);
            } catch (Throwable t) {
                Log.e(TAG, "Exception in setPreviewDisplay()", t);
            }
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = getBestPreviewSize(width, height, parameters);
            if (size != null) {
                parameters.setPreviewSize(size.width, size.height);
                camera.setParameters(parameters);
                camera.startPreview();
                inPreview = true;
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
        // not used
        }
    };
}

19 Source : ThreeImgActivity.java
with Apache License 2.0
from TaoPaox

public clreplaced ThreeImgActivity extends AppCompatActivity {

    private SurfaceView surfaceview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three_img);
        initView();
    }

    private void initView() {
        surfaceview = (SurfaceView) findViewById(R.id.surfaceview);
        surfaceview.getHolder().addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (holder == null) {
                    return;
                }
                Paint paint = new Paint();
                paint.setAntiAlias(true);
                paint.setStyle(Paint.Style.STROKE);
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.d);
                // 先锁定当前surfaceView的画布
                Canvas canvas = holder.lockCanvas();
                // 执行绘制操作
                canvas.drawBitmap(bitmap, 0, 0, paint);
                // 解除锁定并显示在界面上
                holder.unlockCanvasAndPost(canvas);
            }

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

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
            }
        });
    }
}

19 Source : CameraActivity.java
with Apache License 2.0
from TaoPaox

public clreplaced CameraActivity extends AppCompatActivity {

    private SurfaceView surfaceview;

    private Camera camera;

    private boolean isPreview;

    private boolean isRecording;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        initView();
    }

    private void initView() {
        surfaceview = (SurfaceView) findViewById(R.id.surfaceview);
        surfaceview.getHolder().addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                    // Camera,open() 默认返回的后置摄像头信息
                    camera = Camera.open();
                    // 此处也可以设置摄像头参数
                    // 得到摄像头的参数
                    Camera.Parameters parameters = camera.getParameters();
                    // 设置照片的质量
                    parameters.setJpegQuality(100);
                    // 设置预览尺寸
                    parameters.setPreviewSize(1920, 1080);
                    // 设置照片尺寸
                    parameters.setPictureSize(1920, 1080);
                    // 连续对焦模式
                    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                    camera.setParameters(parameters);
                    // 设置角度,此处 CameraId 我默认 为 0 (后置)
                    // CameraId 也可以 通过 参考 Camera.open() 源码 方法获取
                    setCameraDisplayOrientation(CameraActivity.this, 0, camera);
                    // 通过SurfaceView显示取景画面
                    camera.setPreviewDisplay(holder);
                    // 开始预览
                    camera.startPreview();
                    // 设置是否预览
                    isPreview = true;
                } catch (IOException e) {
                    Log.e("surfaceCreated", e.toString());
                }
            }

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

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (camera != null) {
                    if (isPreview) {
                        // 正在预览
                        camera.stopPreview();
                        camera.release();
                    }
                }
            }
        });
    }

    /**
     * 设置 摄像头的角度
     *
     * @param activity 上下文
     * @param cameraId 摄像头ID(假如手机有N个摄像头,cameraId 的值 就是 0 ~ N-1)
     * @param camera   摄像头对象
     */
    public static void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        // 获取摄像头信息
        Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        // 获取摄像头当前的角度
        int degrees = 0;
        switch(rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            // 前置摄像头
            result = (info.orientation + degrees) % 360;
            // compensate the mirror
            result = (360 - result) % 360;
        } else {
            // 后置摄像头
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }
}

19 Source : CaptureActivity.java
with MIT License
from szvone

@Override
protected void onResume() {
    super.onResume();
    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.scanner_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hreplacedurface) {
        initCamera(surfaceHolder);
    } else {
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    decodeFormats = null;
    characterSet = null;
    playBeep = true;
    AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
        playBeep = false;
    }
    initBeepSound();
    vibrate = true;
// quit the scan view
// cancelScanButton.setOnClickListener(new OnClickListener() {
// 
// @Override
// public void onClick(View v) {
// CaptureActivity.this.finish();
// }
// });
}

See More Examples