android - Camera Preview not visible after App Resumes -


i developing app requires access camera. have accessed well. there 2 issues. preview stretched when phone vertical. secondly, camera preview isn't visible when resume app. camera.open() function opens camera not able see preview. have tried available on forum nothing solving problem.

-thanks in advance!

//camera activity file  @suppresslint("simpledateformat") public class cameraactivity extends activity { private camera mcamera; private camerapreview mpreview; private framelayout preview; private button bcapture; private button bgallery; private static final string tag = "cameraactivity"; private static final int pick_image_request = 1; private textview tvcheck; public final static string extra_message = "com.epfl.mycamera.message";     @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     getwindow().requestfeature(window.feature_no_title);     getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, windowmanager.layoutparams.flag_fullscreen);     setcontentview(r.layout.activity_camera);     if (checkcamerahardware(getbasecontext())){         // create instance of camera         mcamera = getcamerainstance();         // create our preview view , set content of our activity.         mpreview = new camerapreview(this, mcamera, cameraactivity.this);         preview = (framelayout) findviewbyid(r.id.camera_preview);         preview.addview(mpreview);         //adding camera button         bcapture = (button) findviewbyid(r.id.bcapture);         //button listener storing images         bcapture.setonclicklistener( new view.onclicklistener() {             @override             public void onclick(view v) {                 mcamera.takepicture(null, null, null, jpegcallback);                 mcamera.startpreview();                 log.d(tag, "takepicture");             }         });         //adding gallery button         bgallery = (button) findviewbyid (r.id.bgallery);         bgallery.setonclicklistener(new view.onclicklistener() {                     @override             public void onclick(view v) {                 tvcheck = (textview) findviewbyid (r.id.tvcheck);                 selectimagefromgallery();             }         });     }         log.d(tag, "oncreate"); } /******************************************************************/  public void selectimagefromgallery() {     intent intent = new intent();     intent.settype("image/*");     intent.setaction(intent.action_get_content);     startactivityforresult(intent.createchooser(intent, "select picture"),pick_image_request); }  @override protected void onactivityresult(int arequestcode, int aresultcode, intent adata) {     switch (arequestcode) {         case pick_image_request:             handleimage(adata);             break;         default:              tvcheck.settext("you can select images.");             break;     }     super.onactivityresult(arequestcode, aresultcode, adata); }   private void handleimage(intent adata) {     if ((adata != null) && (adata.getdata() != null)) {         uri selectedimage = adata.getdata();         string[] filepathcolumn = {mediacolumns.data};         cursor cursor = getcontentresolver().query(selectedimage, filepathcolumn, null, null, null);         cursor.movetofirst();         log.d("imageactivity", "after extracting file path");         int columnindex = cursor.getcolumnindex(filepathcolumn[0]);         string picturepath = cursor.getstring(columnindex);         cursor.close();         log.d("imageactivity", "after closing cursor");         setcontentview(r.layout.activity_image_old); //setting view image         imageview imgview = (imageview) findviewbyid(r.id.ivgallery);         imgview.setimagebitmap(bitmapfactory.decodefile(picturepath));         button blivecamera = (button) findviewbyid(r.id.bcamerapreview);         blivecamera.setonclicklistener(new view.onclicklistener() {                     @override             public void onclick(view v) {                 setcontentview(r.layout.activity_camera);                 mcamera.startpreview();             }         });     }      else {         tvcheck.settext("you did not select image");     } }  /****************************************************************/  /** stores jpeg picture */ picturecallback jpegcallback = new picturecallback() {     public void onpicturetaken(byte[] data, camera camera) {         try {             file mediastoragedir = new file(environment                             .getexternalstoragepublicdirectory(environment.directory_pictures),"mycamera");             // saving image sd card file operation             string timestamp = new simpledateformat("yyyymmdd_hhmmss").format(new date());             file mediafile;             mediafile = new file(mediastoragedir.getpath() + file.separator +"img_"+ timestamp + ".jpg");             fileoutputstream outstream = new fileoutputstream(mediafile);                outstream.write(data);             outstream.close();             sendbroadcast(new intent(intent.action_media_mounted, uri.parse("file://"+ environment.getexternalstoragedirectory())));             log.d(tag, "onpicturetaken - wrote bytes: " + data.length);         } catch (filenotfoundexception e) {             e.printstacktrace();         } catch (ioexception e) {             e.printstacktrace();         } {         }      log.d(tag, "onpicturetaken - jpeg");     } };   /***************************************************************/  /** check if device has camera */ private boolean checkcamerahardware(context context) {     if (context.getpackagemanager().hassystemfeature(packagemanager.feature_camera)){          log.d(tag, "camera available");         return true;     } else {         log.d(tag, "no camera found");         return false;     } }  /** safe way instance of camera object. */ public camera getcamerainstance(){     camera c = null;     try {         int = camera.getnumberofcameras();         releasecamera(); //in case camera being accessed other app.         log.d(tag, "number of cameras "+i +"\n");         c = camera.open(); // attempt camera instance         log.d(tag, "camera opened");     }     catch (exception e){          log.d(tag, "camera can't accessed");     }     return c; // returns null if camera unavailable }    @override     protected void onpause() {         super.onpause();         releasecamera();              // release camera on pause event     }      private void releasecamera(){         if (mcamera != null){             mpreview.getholder().removecallback(mpreview);             mcamera.release();        // release camera other applications         }     }      @override     public void onresume() {         super.onresume();           // camera instance activity achieves full user focus         if (mcamera == null) {            getcamerainstance();              mcamera.startpreview();         }     }  } 

this camera preview class:

@suppresslint({ "viewconstructor", "sdcardpath" }) public class camerapreview extends surfaceview implements surfaceholder.callback { private static final string tag = "camerapreview"; private surfaceholder mholder; private camera mcamera; private size mpreviewsize;  // private activity cameraactivity;  @suppresswarnings("deprecation") public camerapreview(context context, camera camera, activity activity) {     super(context);     mcamera = camera;     //cameraactivity = activity;     // install surfaceholder.callback notified when     // underlying surface created , destroyed.     mholder = getholder();     mholder.addcallback(this);     mholder.settype(surfaceholder.surface_type_push_buffers); }  public void surfacecreated(surfaceholder holder) {     // surface has been created, tell camera draw preview.          try {         mcamera.setpreviewdisplay(holder);         //add camera preview call here.         mcamera.startpreview();     } catch (ioexception e) {         log.d(tag, "error setting camera preview: " + e.getmessage());     } }   public void surfacedestroyed(surfaceholder holder) {     // empty. take care of releasing camera preview in activity.  }  public void surfacechanged(surfaceholder holder, int format, int w, int h) {     // if preview can change or rotate, take care of events here.     // make sure stop preview before resizing or reformatting it.      if (mholder.getsurface() == null){       // preview surface not exist       return;     }      // stop preview before making changes     try{           mcamera.stoppreview();         } catch (exception e){           // ignore: tried stop non-existent preview         }       // set preview size , make resize, rotate or     // reformatting changes here     camera.parameters parameters = mcamera.getparameters();     list<size> localsizes = mcamera.getparameters().getsupportedpreviewsizes();     mpreviewsize = localsizes.get(0);     log.d(tag, "width " + mpreviewsize.width);     log.d(tag, "height " + mpreviewsize.height);      parameters.setpreviewsize(mpreviewsize.width, mpreviewsize.height );     mholder.setfixedsize(mpreviewsize.width, mpreviewsize.height);     requestlayout();     mcamera.setparameters(parameters);      //start preview new settings     try {             mcamera.setpreviewdisplay(mholder);             mcamera.setdisplayorientation(90);             //setcameradisplayorientation(cameraactivity, 0, mcamera);             mcamera.startpreview();     } catch (exception e){         log.d(tag, "error starting camera preview: " + e.getmessage());     } } } 

you create camerapreview oncreate() of activity. camera instance released onpause(), , new 1 opened onresume(). therefore, need set surface again.


Comments