Android camera app gives error on back and home button - android

My Application gives error "Unfortunately PhotoComment has stopped" when I am pressing back or home button. But when I am reopening app from task manager it works.
this is my mainactivity.java
package com.cameratag;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity{
private CameraSurfaceView cameraView;
private ImageView imageResult;
private ImageView imageResult2;
private FrameLayout framenew;
private TextView snapPhoto;
private boolean takePicture = true;
private Bitmap image = null;
private String lastPreviewImgPath = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupcamera();
}
public void setupcamera(){
cameraView = new CameraSurfaceView(getApplicationContext());
imageResult = new ImageView(getApplicationContext());
imageResult.setBackgroundColor(Color.GRAY);
framenew = (FrameLayout) findViewById(R.id.frame);
snapPhoto = (TextView) findViewById(R.id.textView1);
framenew.addView(imageResult);
framenew.addView(cameraView);
}
public void captureHandler(View view){
if(takePicture){
cameraView.capture(jpegHandler);
}
else{
takePicture = true;
cameraView.preview();
framenew.bringChildToFront(cameraView);
imageResult.setImageBitmap(null);
snapPhoto.setText("Capture");
}
}
public void zoomMinusHandler(View view){
cameraView.zoomMinus();
}
public void zoomPilusHandler(View view){
cameraView.zoomPilus();
}
public Camera.PictureCallback jpegHandler = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
image = BitmapFactory.decodeByteArray(data, 0, data.length);
imageResult.setImageBitmap(image);
imageResult2 = imageResult;
LayoutParams params = imageResult.getLayoutParams();
params.width = framenew.getWidth();
params.height = framenew.getHeight();
imageResult2.setLayoutParams(params);
//framenew.bringChildToFront(imageResult);
//snapPhoto.setText("Take Picture");
//takePicture = false;
File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "NNCam");
if (!directory.exists()) {
if (!directory.mkdirs()) {
//Log.e(TAG, "Failed to create storage directory.");
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss").format(new Date(System.currentTimeMillis()));
String filename = "/IMG_" + timeStamp + ".jpg";
if(image!=null){
saveImage(directory.getPath(),filename,image);
cameraView.preview();
}
}
};
public void saveImage(String path, String imgname, Bitmap image){
try{
FileOutputStream fos = new FileOutputStream(path+imgname);
BufferedOutputStream stream = new BufferedOutputStream(fos);
image.compress(CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
}
catch(FileNotFoundException e){
}
catch(IOException e){
}
lastPreviewImgPath = path+imgname;
Bitmap bitmap = BitmapFactory.decodeFile(lastPreviewImgPath);
ImageView myImageView = (ImageView)findViewById(R.id.lastPreview);
myImageView.setImageBitmap(bitmap);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
cameraView.release();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
cameraView.reconnect();
}
#Override
public void onPause() {
super.onPause();
cameraView.release();
}
}
and this is surfaceview class
package com.cameratag;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private Context context;
private SurfaceHolder mHolder;
public Camera camera = null;
public int zoomValue = 0;
public CameraSurfaceView(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// TODO Auto-generated constructor stub
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
Camera.Size cs = sizes.get(0);
List<Camera.Size> sizes2 = parameters.getSupportedPreviewSizes();
Camera.Size cs2 = sizes2.get(0);
parameters.setPreviewSize(cs2.width, cs2.height);
parameters.setPictureSize(cs.width, cs.height);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
camera.setPreviewDisplay(mHolder);
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
int rrr = 0;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if(rotation==0)rrr=90;
else if(rotation==1)rrr=0;
else if(rotation==3)rrr=180;
else rrr=270;
camera.setDisplayOrientation(rrr);
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
camera.stopPreview();
camera = null;
}
public void capture(Camera.PictureCallback jpegHandler){
camera.takePicture(null, null, jpegHandler);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int rrr = 0;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if(rotation==0)rrr=90;
else if(rotation==1)rrr=0;
else if(rotation==3)rrr=180;
else rrr=270;
//camera.stopPreview();
camera.setDisplayOrientation(rrr);
//camera.startPreview();
}
public void preview(){
camera.startPreview();
}
public void reconnect(){
try {
camera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
public void zoomMinus() {
Camera.Parameters parameters = camera.getParameters();
// TODO Auto-generated method stub
if(parameters.isZoomSupported()){
if(zoomValue>0){
zoomValue-=2;
parameters.setZoom(zoomValue);
if(parameters.isSmoothZoomSupported()){
camera.startSmoothZoom(zoomValue);
}
else{
camera.setParameters(parameters);
}
}
}
}
public void zoomPilus() {
Camera.Parameters parameters = camera.getParameters();
// TODO Auto-generated method stub
if(parameters.isZoomSupported()){
if(zoomValue<parameters.getMaxZoom()){
zoomValue+=2;
parameters.setZoom(zoomValue);
if(parameters.isSmoothZoomSupported()){
camera.startSmoothZoom(zoomValue);
}
else{
camera.setParameters(parameters);
}
}
}
}
public void release() {
// TODO Auto-generated method stub
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
}
}
Please help.

#Override
protected void onPause() {
super.onPause();
// if (inPreview) {
// mCamera.stopPreview();
// }
// mCamera.release();
// mCamera = null;
// inPreview = false;
mCamera.setPreviewCallback(null);
super.onPause();
// mCamera.stopPreview();
}

I was having a similar issue, the trick is to also setup the camera inside of onResume().
The issue was that the app does not call onCreate() every time you go to an activity with the back button, sometimes it simply pauses the activity. onResume() is called whenever the activity returns to the foreground and is a more reliable place to set up the camera.
#Override
protected void onResume()
{
super.onResume();
if( camera == null )
{
camera = Camera.open();
}
}

try to put your release code in try catch block
try{
if (camera != null){
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
}
}

I have found the solution for my own. You only need to change surfaceDestroyed method to this.
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
try{
camera.stopPreview();
camera.release();
camera = null;
}
catch(NullPointerException e){
//e.printStackTrace();
}
}
and on onRestoreInstanceState to this.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
cameraView = null;
setupcamera();
//cameraView.reconnect();
}

Related

Android camera startPreview failed error

I want to simply take a photo in android (actually with an overlay image....but do it later, I am now failing in the first step...), the log catch an error of 'start preview failed'. The following is my code:
package com.example.camera_test;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraFilming extends Activity implements SurfaceHolder.Callback{
private Camera camera = null;
private SurfaceView preview;
private SurfaceHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
((Setting)getApplication()).getDeviceDisplaySize();
preview = (SurfaceView)findViewById(R.id.camera_surface);
holder = preview.getHolder();
holder.addCallback(this);
}
private void startCamera(){
camera = Camera.open();
}
#Override
public void onBackPressed(){
super.onBackPressed();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
startCamera();
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
}
}
I run it on a real device and then it gets no problem...conclusion: don't do camera simulation on an AVD emulator!!!

Android Flashlight Won't Turn Off

I am making an app that uses touchless gestures to turn off and on the flashilight in my Android app. It turns on just fine, but I can't get it to turn back off. Thanks in advance for any help.
Here is my MainActivity.java
package com.proximitysensorapp.primo.app;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.TextView;
import java.io.IOException;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
public class MainActivity extends Activity implements SensorEventListener, Callback
{
SensorManager sm;
Sensor s;
TextView et1;
Intent Activitynew;
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
public void TurnOn(View view)
{
if (FlashAvailable() && camera != null)
{
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
//camera.startPreview();
try
{
camera.setPreviewDisplay(surfaceHolder);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public void TurnOff(View view) {
if (FlashAvailable() && camera != null) {
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
//camera.stopPreview();
}
}
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
s = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
Activitynew = new Intent(MainActivity.this, Activity2.class);
surfaceView = (SurfaceView) this.findViewById(R.id.surface1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void onResume()
{
super.onResume();
try {
camera = Camera.open();
} catch (Exception e) {
//---exception handling here---
Log.d("Flashlight", e.toString());
}
}
#Override
public void onPause() {
super.onPause();
TurnOff(null);
camera.release();
}
private Boolean FlashAvailable() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1)
{
}
#Override
public void onSensorChanged(SensorEvent event)
{
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY)
{
int temp = (int) event.values[0];
if (temp==1)
{
TurnOff(null);
}
else if (temp==0)
{
TurnOn(null);
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
you should add
mCamera.stopPreview();
mCamera.release();
inside your turnoff method

Camera preview stops on activity restart

I made a camera preview app for android and everything works fine even when I press the power button to make device asleep, and waking it up again. But when my activity goes to background (like pressing home button) and then it comes to foreground again the program stops.
This is my activity code:
package com.example.campreview;
import com.example.campreview.CameraPreview;
import com.example.campreview.R;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.view.Menu;
import android.view.View;
public class ScanActivity extends Activity {
private CameraPreview CamPrev = null;
private FrameLayout PreviewFrm;
private Camera cam = null;
private Handler atfcs;
private ImageScanner scnr;
private boolean hascam = false;
private boolean prvng = true;
private boolean paused = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
PreviewFrm = (FrameLayout)findViewById(R.id.PreviewFrm);
StartCamera();
if (cam != null) {
hascam = true;
atfcs = new Handler();
CamPrev = new CameraPreview(this, cam, PreviewCB, AutoFocusCB);
PreviewFrm.addView(CamPrev);
}
}
#Override
public void onPause() {
ReleaseCamera();
paused = true;
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (paused) StartPreview();
}
private boolean StartCamera() {
boolean r = true;
if (cam == null) {
try {
cam = Camera.open();
} catch (Exception e) {
cam = null;
r = false;
}
if (cam != null) {
try {
Camera.Parameters p = cam.getParameters();
if (p.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO))
p.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
if (p.getSupportedFlashModes().contains(Camera.Parameters.FLASH_MODE_OFF))
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
if (p.getSupportedPreviewFormats().contains(ImageFormat.NV21))
p.setPreviewFormat(ImageFormat.NV21);
Camera.Size s = null;
int a = 0, b;
for (Camera.Size z : p.getSupportedPreviewSizes()) {
b = z.width * z.height;
if (Math.abs(b - 307200) < Math.abs(a - 307200)) { //640x480 is the best
s = z;
a = b;
}
}
if (a != 0) p.setPreviewSize(s.width, s.height);
cam.setParameters(p);
cam.setDisplayOrientation(90);
if (CamPrev != null) cam.setPreviewDisplay(CamPrev.getHolder());
} catch (Exception e) {
r = false;
cam.release();
cam = null;
}
}
}
return r;
}
private void ReleaseCamera() {
if (cam != null) {
StopPreview();
cam.release();
cam = null;
}
}
public void StartPreview() {
if ((!prvng) & hascam) {
if (StartCamera()) {
cam.setPreviewCallback(PreviewCB);
cam.startPreview();
cam.autoFocus(AutoFocusCB);
prvng = true;
}
}
}
public void StopPreview() {
if (prvng) {
cam.stopPreview();
cam.setPreviewCallback(null);
prvng = false;
}
}
private Runnable DoAutoFocus = new Runnable() {
public void run() {
if (prvng) cam.autoFocus(AutoFocusCB);
}
};
AutoFocusCallback AutoFocusCB = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
atfcs.postDelayed(DoAutoFocus, 1000);
}
};
PreviewCallback PreviewCB = new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
//
}
};
}
And this is the preview code:
package com.example.campreview;
import java.io.IOException;
import android.view.SurfaceView;
import android.view.SurfaceHolder;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder hldr;
private Camera cam;
private PreviewCallback pcb;
private AutoFocusCallback afcb;
public CameraPreview(Context context, Camera camera, PreviewCallback previewCb, AutoFocusCallback autoFocusCb) {
super(context);
cam = camera;
pcb = previewCb;
afcb = autoFocusCb;
hldr = getHolder();
hldr.addCallback(this);
//hldr.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
cam.setPreviewDisplay(holder);
} catch (IOException e) {
// No Code
}
}
public void surfaceDestroyed(SurfaceHolder holder) {}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (hldr.getSurface() == null) return;
try {
cam.stopPreview();
} catch (Exception e){
// No Code
}
try {
cam.setPreviewDisplay(hldr);
cam.setPreviewCallback(pcb);
cam.startPreview();
cam.autoFocus(afcb);
} catch (Exception e) {
// No Code
}
}
}
Is there any idea how can I solve this problem?
I found the problem. It seems the SurfaceView that is made in program destroys on activity stop. So I replaced it with a SurfaceView in my layout.
package com.example.campreview;
import com.example.campreview.R;
import java.io.IOException;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
public class ScanActivity extends Activity implements OnClickListener {
private SurfaceView PreviewSfc;
private Camera cam = null;
private Handler atfcs;
private boolean hascam = false;
private boolean validdisplay = false;
private boolean prvng = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
PreviewSfc = (SurfaceView)findViewById(R.id.PreviewSfc);
PreviewSfc.getHolder().addCallback(SurfaceCB);
//PreviewSfc.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
StartCamera();
if (cam != null) {
hascam = true;
atfcs = new Handler();
}
}
#Override
public void onPause() {
ReleaseCamera();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
StartPreview();
}
private boolean StartCamera() {
boolean r = true;
if (cam == null) {
try {
cam = Camera.open();
} catch (Exception e) {
cam = null;
r = false;
}
if (cam != null) {
try {
Camera.Parameters p = cam.getParameters();
if (p.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO))
p.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
if (p.getSupportedFlashModes().contains(Camera.Parameters.FLASH_MODE_OFF))
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
if (p.getSupportedPreviewFormats().contains(ImageFormat.NV21))
p.setPreviewFormat(ImageFormat.NV21);
Camera.Size s = null;
int a = 0, b;
for (Camera.Size z : p.getSupportedPreviewSizes()) {
b = z.width * z.height;
if (Math.abs(b - 307200) < Math.abs(a - 307200)) { //640x480 is the best
s = z;
a = b;
}
}
if (a != 0) p.setPreviewSize(s.width, s.height);
cam.setParameters(p);
cam.setDisplayOrientation(90);
if (validdisplay) cam.setPreviewDisplay(PreviewSfc.getHolder());
} catch (Exception e) {
r = false;
cam.release();
cam = null;
}
}
}
//if (!r) Error message that failed to start camera
return r;
}
private void ReleaseCamera() {
if (cam != null) {
StopPreview();
cam.release();
cam = null;
}
}
public void StartPreview() {
if ((!prvng) & (hascam) & (validdisplay)) {
if (StartCamera()) {
cam.setPreviewCallback(PreviewCB);
cam.startPreview();
cam.autoFocus(AutoFocusCB);
prvng = true;
}
}
}
public void StopPreview() {
if (prvng) {
cam.stopPreview();
cam.setPreviewCallback(null);
prvng = false;
}
}
private Runnable DoAutoFocus = new Runnable() {
public void run() {
if (prvng) cam.autoFocus(AutoFocusCB);
}
};
AutoFocusCallback AutoFocusCB = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
atfcs.postDelayed(DoAutoFocus, 1000);
}
};
PreviewCallback PreviewCB = new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
//
}
};
SurfaceHolder.Callback SurfaceCB = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
if (cam != null) {
try {
cam.setPreviewDisplay(holder);
} catch (IOException e) {
// No Code
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
validdisplay = true;
StartPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
validdisplay = false;
}
};
}

Android Camera Program

I am new to Android I have written a small program to take pictures and save them in the internal memory disk. My program is successfully launched but when I take pictures no data is written to the memory disk.
Below is my code. What am I missing?
package com.lab2;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.os.Environment;
public class Lab2_cameraActivity extends Activity implements SurfaceHolder.Callback {
/** Called when the activity is first created. */
private Camera mCamera;
private SurfaceHolder mHolder;
private SurfaceView mSurfaceView;
private Button mbutton1;
private ShutterCallback shutter;
private PictureCallback raw;
private PictureCallback postview;
AutoFocusCallback AFCallback = new AutoFocusCallback(){
#Override
public void onAutoFocus(boolean success, Camera camera) {
// TODO Auto-generated method stub
if (success){
mCamera.takePicture(shutter, raw, postview, jpeg);//take photo
}else{
Toast.makeText(Lab2_cameraActivity.this, "in else...",Toast.LENGTH_LONG).show();
}
}
};
/*jpeg callback occurs when the compressed image is available*/
PictureCallback jpeg = new PictureCallback(){
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
File file = new File("/mnt/sdcard/");
try {
outStream = new FileOutputStream(file.toString()+"photo.jpg");
outStream.write(data);
outStream.close();
Toast.makeText(Lab2_cameraActivity.this, "Photo Saved...",Toast.LENGTH_LONG).show();
mCamera.startPreview();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
/*when surface destroyed, stop preview*/
if(mCamera != null){
mCamera.stopPreview();
mCamera.release();//release camera resources
mCamera = null;
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mCamera = Camera.open();//open camera
try {
mCamera.setPreviewDisplay(holder);//set surface to display
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
/*when surface changed, reset camera parameters for preview*/
mCamera.getParameters();//get default parameters
Camera.Parameters parameters= mCamera.getParameters();
/*you can set your own parameters in there*/
mCamera.setParameters(parameters);//set parameters if parameters has been changed
mCamera.startPreview();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mbutton1 = (Button)findViewById(R.id.button1);
mSurfaceView = (SurfaceView)findViewById(R.id.surfaceView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mbutton1.setOnClickListener(new Button.OnClickListener()
{
#Override
public void onClick(View v) {
mCamera.autoFocus(AFCallback);
}
});
}
}
you should not specify '/mnt/whatever/' path to your sdcard, use getExternalFilesDir() to get the correct path.
your callback is not called, unless you specify it in mCamera.takePicture(null, null, jpeg);
do you really have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
in your AndroidManifest.xml file?

getting gps position after taking photo

I tried to get the gps position when i taking a photo. i saved the position of the location-listener when the LocationChanged method is running in a variable and want to show it when i take a photo. Is this the right way? I use android 2.3.6.
Here my code:
package com.exercise;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class AndroidCamera extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
Button buttonTakePicture;
final int RESULT_SAVEIMAGE = 0;
public Location test;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
LinearLayout layoutBackground = (LinearLayout)findViewById(R.id.background);
layoutBackground.setOnClickListener(new LinearLayout.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
buttonTakePicture.setEnabled(false);
camera.autoFocus(myAutoFocusCallback);
}});
}
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
String Text = "Lat = " + loc.getLatitude() + "|Long = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
// final TextView tv = (TextView) findViewById(R.id.text);
// tv.setText(tv.getText()+ "||" + Text);
test = loc;
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}
AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback(){
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
// TODO Auto-generated method stub
buttonTakePicture.setEnabled(true);
}};
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
// Toast.makeText(AndroidCamera.this,
// "Image saved: " + uriTarget.toString(),
// Toast.LENGTH_LONG).show();
// test.getLatitude();
// test.getLongitude();
// String Text = "Lat = " + test.getLatitude() + "|Long = " + test.getLongitude();
// Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
if (test==null){
Toast.makeText(AndroidCamera.this, "null", Toast.LENGTH_SHORT).show();
}
else{
test.getLatitude();
String ausgabe = String.valueOf(test.getLatitude());
Toast.makeText(AndroidCamera.this, ausgabe, Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
Yes, this is a fair way to do it. By the way, you can instead .requestSingleUpdate(), since you'll be wanting only one update. You should also probably not wait until the GPS information arrives (and, you can also specify something different than a gps provider, like, any provider, which may respond quicker -- as opposed to a possible cold start from GPS). If none of that works, you can always query for the last known location. Since the update may not arrive for a while, you should probably save the image data somewhere lazily (without location information), and then update the information when location becomes available.

Categories

Resources