add camera preview

This commit is contained in:
tibbi 2016-04-13 22:48:18 +02:00
parent b66ecf8769
commit 6150c51f57
3 changed files with 45 additions and 7 deletions

View File

@ -23,4 +23,5 @@ dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.jakewharton:butterknife:7.0.1'
}

View File

@ -4,16 +4,28 @@ import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MainActivity extends AppCompatActivity {
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private static final String TAG = MainActivity.class.getSimpleName();
@Bind(R.id.surfaceView) SurfaceView surfaceView;
private Camera camera;
private boolean isOpen;
private SurfaceHolder surfaceHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
}
@Override
@ -34,7 +46,13 @@ public class MainActivity extends AppCompatActivity {
try {
releaseCamera();
camera = Camera.open();
isOpen = (camera != null);
if (camera != null) {
isOpen = true;
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
} catch (Exception e) {
Log.e(TAG, "openCamera exception " + e.getMessage());
}
@ -46,4 +64,22 @@ public class MainActivity extends AppCompatActivity {
camera = null;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
openCamera();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
camera.stopPreview();
}
}
}

View File

@ -2,10 +2,11 @@
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>