Я в настоящее время реализую пользовательскую функцию камеры, используя Surfaceview. Теперь я хочу реализовать следующее: когда я перехожу на другой экран и возвращаюсь, я хочу запустить его снова, но это не работает. Так что я использую Finish () onPause, но я хочу найти лучший способ. Ошибки, которые я сделал, заключаются в следующем. Буду очень признателен, если вы подскажете, как это решить.
**MainActivity.java**
public class MainActivity extends AppCompatActivity {
Button cameraButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
final CameraPreview surfaceView = (CameraPreview) findViewById(R.id.main);
surfaceView.setBackground(ContextCompat.getDrawable(this, R.drawable.human_icon_21));
SurfaceHolder holder;
holder = surfaceView.getHolder();
holder.addCallback(surfaceView);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraButton = (Button) findViewById(R.id.button);
cameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
surfaceView.takePhoto(new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
String str = String.format(Environment.getExternalStorageDirectory()+"/Pictures/DICM/android_hong_test.jpg",
System.currentTimeMillis());
outStream = new FileOutputStream(str);
outStream.write(data);
outStream.close();
Intent intent = new Intent(MainActivity.this,
ResultActivity.class);
intent.putExtra("strParamName", str);
startActivity(intent);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
}
Toast.makeText(getApplicationContext(),
"Picture Saved", Toast.LENGTH_LONG).show();
}
});
}
});
}
@Override
protected void onPause() {
super.onPause();
//finish();
}
}
**cameraview.java**
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
String TAG = "WOW";
public List<Camera.Size> prSupportedPreviewSizes;
private Camera.Size prPreviewSize;
public Camera mCamera;
public CameraPreview(Context context) {
super(context);
}
public CameraPreview(Context context, AttributeSet attrs) {
super(context, attrs);
mCamera = Camera.open();
prSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
}
public boolean takePhoto(Camera.PictureCallback handler){
if(mCamera != null){
mCamera.takePicture(null,null,handler);
return true;
}else{
return false;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
Camera.Parameters parameters = mCamera.getParameters();
if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
parameters.set("orientation", "portrait");
mCamera.setDisplayOrientation(90);
parameters.setRotation(90);
} else {
parameters.set("orientation", "landscape");
mCamera.setDisplayOrientation(0);
parameters.setRotation(0);
}
mCamera.setParameters(parameters);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v("jyp@@@","surfaceDestroyed ");
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (holder.getSurface() == null){
return;
}
// 우선 멈춘다
try {
mCamera.stopPreview();
} catch (Exception e){
// 프리뷰가 존재조차 하지 않는 경우다
}
Camera.Parameters parameters = mCamera.getParameters();
List<String> focusModes = parameters.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
//
// Camera.Size size = getBestPreviewSize(w, h);
Log.v("jyp@@@","surfaceChanged width: "+prPreviewSize.width);
Log.v("jyp@@@","surfaceChanged height: "+prPreviewSize.height);
parameters.setPreviewSize(prPreviewSize.width, prPreviewSize.height);
mCamera.setParameters(parameters);
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.v("jyp@@@","onMeasure()");
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
Log.v("jyp@@@","width: "+width);
Log.v("jyp@@@","height: "+height);
setMeasuredDimension(width, height);
if (prSupportedPreviewSizes != null) {
prPreviewSize = getOptimalPreviewSize(prSupportedPreviewSizes, width, height);
Log.v("jyp@@@","prPreviewSize.width: "+prPreviewSize.width);
Log.v("jyp@@@","prPreviewSize.height: "+prPreviewSize.height);
}
}
public Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) h / w;
if (sizes == null)
return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
for (Camera.Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
}