android - AsyncTask progress dialog not showing & still skipping frames -
i have 2 asynctasks contain code save photo , video file. used working asynctask code other classes created, yet reason not working here. here 2 problems:
i see no progress dialog
i still see messages in console "skipped 276 frames! doing work on main thread."
but how can when have saving in doinbackground()
? photo , video save, know doinbackground()
runs. don't know why progress dialog boxes not show @ all. looked on stack answers that, nothing addressed situation. have context correct, no parameters in onpreexecute()
, not using get()
, , other answers problem did not apply.
thanks help.
update
thanks @perosperk, moved imageview
contacts out of doinbackground()
, meant had call click listener somewhere else. put toast
results in onpostexecute()
, these changes totally worked! see progress dialog expected both photo , video. :) below working code, although post snippets of changed code, since had reached character limit stacko:
working makephotovideo.java
public void enableclicklistener(){ mimageview.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { // saves photo & sets imageview new savephototask().execute(); } }); } private bitmap setpic() { /*taken out code ...*/ /* set bitmap imageview, make sure videoview cleared replace imageview */ mimageview.setimagebitmap(mimagebitmap); // enable click listener here, don't save empty files before enableclicklistener(); // make sure video view invisible mvideouri = null; return mimagebitmap; } private class savephototask extends asynctask<bitmap, void, bitmap>{ @override protected void onpreexecute() { super.onpreexecute(); // instantiate photo progress dialog progressphoto = new progressdialog(makephotovideo.this); progressphoto.setmessage("saving cute photo ..."); //set progress bar cancelable on button progressphoto.setcancelable(true); progressphoto.show(); } @override protected bitmap doinbackground(bitmap... params) { photosave(mimagebitmap); return mimagebitmap; } @override protected void onpostexecute(bitmap result) { progressphoto.dismiss(); if (successphoto) { toast toast = toast.maketext(getapplicationcontext(), "cute photo saved!", toast.length_long); linearlayout toastlayout = (linearlayout) toast.getview(); toastlayout.setbackgroundcolor(getresources().getcolor(r.color.toast_color)); textview toasttv = (textview) toastlayout.getchildat(0); toasttv.settextsize(25); toast.setgravity(gravity.center_vertical, 0, 80); toast.show(); } else { toast.maketext(getapplicationcontext(), "error during image saving", toast.length_short).show(); } mimageview.setonclicklistener(null); } } // saves photo sd card private boolean photosave(final bitmap bitmapphoto){ /*taken out code ...*/ return successphoto; } private class savevideotask extends asynctask<uri, void, uri> { @override protected void onpreexecute() { super.onpreexecute(); // instantiate video progress dialog progressvideo = new progressdialog(makephotovideo.this); progressvideo.setmessage("saving cute video ..."); //set progress bar cancelable on button progressvideo.setcancelable(true); progressvideo.show(); } @override protected uri doinbackground(uri... params) { return videosave(mvideouri); } @override protected void onpostexecute(uri result) { progressvideo.dismiss(); if (successvideo) { toast toast = toast.maketext(getapplicationcontext(), "cute video saved!", toast.length_short); linearlayout toastlayout = (linearlayout) toast.getview(); toastlayout.setbackgroundcolor(getresources().getcolor(r.color.toast_color)); textview toasttv = (textview) toastlayout.getchildat(0); toasttv.settextsize(30); toast.setgravity(gravity.center_vertical, 0, 80); toast.show(); } else { toast.maketext(getapplicationcontext(), "error during video saving", toast.length_short).show(); } } } // enables videoview listener protected void enabletouchlistener(){ // click video save mvideoview.setontouchlistener(new view.ontouchlistener() { public boolean ontouch(view v, motionevent event) { if(event.getaction() == motionevent.action_up) { new savevideotask().execute(); } return true; } }); } private void handlecameraphoto() { setrequestedorientation(activityinfo.screen_orientation_locked); if (mcurrentphotopath != null) { setpic(); galleryaddpic(); mcurrentphotopath = null; } } // post recorded video videoview private uri handlecameravideo(intent intent) { setrequestedorientation(activityinfo.screen_orientation_locked); mvideouri = intent.getdata(); mvideoview.setvideouri(mvideouri); mimagebitmap = null; mvideoview.setvisibility(view.visible); mimageview.setvisibility(view.invisible); mvideoview.start(); enabletouchlistener(); return mvideouri; }
below un-working code
makephotovideo.java
package org.azurespot.makecute; import android.app.progressdialog; import android.content.context; import android.content.intent; import android.content.pm.activityinfo; import android.content.pm.packagemanager; import android.content.pm.resolveinfo; import android.content.res.configuration; import android.graphics.bitmap; import android.graphics.bitmapfactory; import android.graphics.matrix; import android.net.uri; import android.os.asynctask; import android.os.bundle; import android.os.environment; import android.provider.mediastore; import android.support.v7.app.actionbaractivity; import android.util.log; import android.view.gravity; import android.view.menuitem; import android.view.motionevent; import android.view.view; import android.widget.button; import android.widget.imageview; import android.widget.linearlayout; import android.widget.textview; import android.widget.toast; import android.widget.videoview; import org.azurespot.r; import org.azurespot.cutecollection.cutecollection; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.text.simpledateformat; import java.util.date; import java.util.list; import java.util.random; public class makephotovideo extends actionbaractivity { private static final int action_take_photo = 1; private static final int action_take_video = 2; private static final string bitmap_storage_key = "viewbitmap"; private static final string imageview_visibility_storage_key = "imageviewvisibility"; private imageview mimageview; private bitmap mimagebitmap; private static final string video_storage_key = "viewvideo"; private static final string videoview_visibility_storage_key = "videoviewvisibility"; private videoview mvideoview; private uri mvideouri; private file filevideo; private string mcurrentphotopath; string videopath; private int position = 0; int targeth; int targetw; private static final string jpeg_file_prefix = "img_"; private static final string jpeg_file_suffix = ".jpg"; private photostoragedirfactory mphotostoragedirfactory = null; private progressdialog progressphoto; private progressdialog progressvideo; /* photo album application */ private string getalbumname() { return getstring(r.string.album_name); } @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_make_photo_video); // instantiate photo progress dialog progressphoto = new progressdialog(makephotovideo.this); // instantiate video progress dialog progressvideo = new progressdialog(makephotovideo.this); mimageview = (imageview) findviewbyid(r.id.taken_photo); mvideoview = (videoview) findviewbyid(r.id.video_view); mimageview.setvisibility(view.visible); mvideoview.setvisibility(view.invisible); mimageview.setsaveenabled(true); button photobtn = (button) findviewbyid(r.id.click); setbtnlistenerordisable(photobtn, mtakepiconclicklistener, mediastore.action_image_capture); button videobtn = (button) findviewbyid(r.id.record_video); setbtnlistenerordisable(videobtn, mtakevidonclicklistener, mediastore.action_video_capture); mphotostoragedirfactory = new basephotodirfactory(); // shows carat near app icon in actionbar getsupportactionbar().setdisplayuselogoenabled(false); getsupportactionbar().setdisplayhomeasupenabled(true); } public void viewcollection(view v){ // finishes/restarts activity unsaved video not corrupt intent intent = getintent(); finish(); startactivity(intent); // goes cute collection activity intent = new intent(this, cutecollection.class); startactivity(i); } private file getalbumdir() { file storagedir = null; if (environment.media_mounted.equals(environment.getexternalstoragestate())) { storagedir = mphotostoragedirfactory.getalbumstoragedir(getalbumname()); if (storagedir != null) { if (! storagedir.mkdirs()) { if (! storagedir.exists()){ log.d("camera", "failed create directory"); return null; } } } } else { log.v(getstring(r.string.app_name), "external storage not mounted read/write."); } return storagedir; } private file createimagefile() throws ioexception { // create image file name string timestamp = new simpledateformat("yyyymmdd_hhmmss").format(new date()); string imagefilename = jpeg_file_prefix + timestamp + "_"; file albumf = getalbumdir(); file imagef = file.createtempfile(imagefilename, jpeg_file_suffix, albumf); return imagef; } private file setupphotofile() throws ioexception { file f = createimagefile(); mcurrentphotopath = f.getabsolutepath(); return f; } private bitmap setpic() { mimageview.setvisibility(view.visible); mvideoview.setvisibility(view.invisible); /* there isn't enough memory open more couple camera photos */ /* pre-scale target bitmap file decoded */ /* size of image */ bitmapfactory.options bmoptions = new bitmapfactory.options(); bmoptions.injustdecodebounds = true; if (getresources().getconfiguration().orientation == configuration.orientation_landscape){ targeth = 570; targetw = 960; } else if (getresources().getconfiguration().orientation == configuration.orientation_portrait){ targeth = 960; targetw = 570; } bitmapfactory.decodefile(mcurrentphotopath, bmoptions); int photow = bmoptions.outwidth; int photoh = bmoptions.outheight; /* figure out way needs reduced less */ int scalefactor = math.min(photow/targetw, photoh/targeth); /* set bitmap options scale image decode target */ bmoptions.injustdecodebounds = false; bmoptions.inpreferredconfig = bitmap.config.rgb_565; bmoptions.insamplesize = scalefactor; bmoptions.inbitmap = mimagebitmap; bmoptions.inpurgeable = true; /* decode jpeg file bitmap */ mimagebitmap = bitmapfactory.decodefile(mcurrentphotopath, bmoptions); if (getresources().getconfiguration().orientation == configuration.orientation_portrait) { mimagebitmap = rotatebitmap(mimagebitmap, 90); } return mimagebitmap; } private class savephototask extends asynctask<bitmap, void, bitmap>{ @override protected void onpreexecute() { super.onpreexecute(); progressphoto.setmessage("saving cute photo ..."); //set progress bar cancelable on button progressphoto.setcancelable(true); progressphoto.show(); } @override protected bitmap doinbackground(bitmap... params) { savephoto(mimagebitmap); return mimagebitmap; } @override protected void onpostexecute(bitmap result) { progressphoto.dismiss(); /* associate bitmap imageview, make sure videoview * cleared replace imageview */ mimageview.setimagebitmap(mimagebitmap); mvideouri = null; } } // save photo sd card private void savephoto(final bitmap bitmapphoto){ // set onclicklistener save photo mimageview.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { boolean success = false; file photodir = new file(environment.getexternalstoragepublicdirectory (environment.directory_pictures) + "/cute photos"); photodir.mkdirs(); random generator = new random(); int n = 10000; n = generator.nextint(n); string photoname = "photo" + n + ".jpg"; file filephoto = new file(photodir, photoname); try { fileoutputstream out = new fileoutputstream(filephoto); bitmapphoto.compress(bitmap.compressformat.jpeg, 100, out); out.flush(); out.close(); success = true; } catch (exception e) { e.printstacktrace(); } if (success) { toast toast = toast.maketext(getapplicationcontext(), "cute photo saved!", toast.length_long); linearlayout toastlayout = (linearlayout) toast.getview(); toastlayout.setbackgroundcolor(getresources().getcolor(r.color.toast_color)); textview toasttv = (textview) toastlayout.getchildat(0); toasttv.settextsize(25); toast.setgravity(gravity.center_vertical, 0, 80); toast.show(); } else { toast.maketext(getapplicationcontext(), "error during image saving", toast.length_short).show(); } } }); } private class savevideotask extends asynctask<uri, void, uri> { @override protected void onpreexecute() { super.onpreexecute(); progressvideo.setmessage("saving cute video ..."); //set progress bar cancelable on button progressvideo.setcancelable(true); progressvideo.show(); } @override protected uri doinbackground(uri... params) { return savevideo(mvideouri); } @override protected void onpostexecute(uri result) { progressvideo.dismiss(); } } // save video sd card protected uri savevideo(final uri urivideo){ // click video save mvideoview.setontouchlistener(new view.ontouchlistener() { boolean success = false; boolean savedonce = false; public boolean ontouch(view v, motionevent event) { if(event.getaction() == motionevent.action_up) { if (mvideoview.isplaying()) { mvideoview.pause(); } if (!savedonce) { try { // make directory file viddir = new file(android.os.environment .getexternalstoragepublicdirectory (environment.directory_movies) + file.separator + "cute videos"); viddir.mkdirs(); // create unique identifier random generator = new random(); int n = 100; n = generator.nextint(n); // create file name string videoname = "video" + n + ".mp4"; filevideo = new file(viddir.getabsolutepath(), videoname); videopath = filevideo.getabsolutepath(); filevideo.setwritable(true, false); outputstream out = new fileoutputstream(filevideo); inputstream in = getcontentresolver().openinputstream(urivideo); byte buffer[] = new byte[1024]; int length = 0; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } out.close(); in.close(); success = true; } catch (exception e) { e.printstacktrace(); } if (success) { toast toast = toast.maketext(getapplicationcontext(), "cute video saved!", toast.length_short); linearlayout toastlayout = (linearlayout) toast.getview(); toastlayout.setbackgroundcolor(getresources().getcolor(r.color.toast_color)); textview toasttv = (textview) toastlayout.getchildat(0); toasttv.settextsize(30); toast.setgravity(gravity.center_vertical, 0, 80); toast.show(); } else { toast.maketext(getapplicationcontext(), "error during video saving", toast.length_short).show(); } savedonce = true; } } return true; } }); return urivideo; } public bitmap rotatebitmap(bitmap source, int angle) { matrix matrix = new matrix(); matrix.set(matrix); matrix.setrotate(angle); return bitmap.createbitmap(source, 0, 0, source.getwidth(), source.getheight(), matrix, false); } private void galleryaddpic() { intent mediascanintent = new intent("android.intent.action.media_scanner_scan_file"); file f = new file(mcurrentphotopath); uri contenturi = uri.fromfile(f); mediascanintent.setdata(contenturi); this.sendbroadcast(mediascanintent); } private void dispatchtakepictureintent(int actioncode) { intent takepictureintent = new intent(mediastore.action_image_capture); switch(actioncode) { case action_take_photo: file f; try { f = setupphotofile(); log.d("tag", "value of f in picture intent: " + f); mcurrentphotopath = f.getabsolutepath(); takepictureintent.putextra(mediastore.extra_output, uri.fromfile(f)); } catch (ioexception e) { e.printstacktrace(); f = null; mcurrentphotopath = null; } break; default: break; } // switch startactivityforresult(takepictureintent, actioncode); } // captures video android camera component protected void dispatchtakevideointent() { intent takevideointent = new intent(mediastore.action_video_capture); if (takevideointent.resolveactivity(getpackagemanager()) != null) { // set video image quality high takevideointent.putextra(mediastore.extra_video_quality, 1); // limit video 30 seconds takevideointent.putextra(mediastore.extra_duration_limit, 30); startactivityforresult(takevideointent, action_take_video); } } private void handlecameraphoto() { setrequestedorientation(activityinfo.screen_orientation_locked); if (mcurrentphotopath != null) { setpic(); // saves photo & sets imageview new savephototask().execute(); galleryaddpic(); mcurrentphotopath = null; } } // post recorded video videoview private uri handlecameravideo(intent intent) { setrequestedorientation(activityinfo.screen_orientation_locked); mvideouri = intent.getdata(); mvideoview.setvideouri(mvideouri); mimagebitmap = null; mvideoview.setvisibility(view.visible); mimageview.setvisibility(view.invisible); mvideoview.start(); new savevideotask().execute(); return mvideouri; } // click listener android camera button (not app's button) button.onclicklistener mtakepiconclicklistener = new button.onclicklistener() { @override public void onclick(view v) { dispatchtakepictureintent(action_take_photo); // releases orientation lock setrequestedorientation(activityinfo.screen_orientation_unspecified); } }; button.onclicklistener mtakevidonclicklistener = new button.onclicklistener() { @override public void onclick(view v) { dispatchtakevideointent(); // releases orientation lock setrequestedorientation(activityinfo.screen_orientation_unspecified); } }; // intent data how photo , video transfer views @override protected void onactivityresult(int requestcode, int resultcode, intent data) { switch (requestcode) { case action_take_photo: { if (resultcode == result_ok) { handlecameraphoto(); } break; } case action_take_video: { if (resultcode == result_ok) { handlecameravideo(data); } break; } } } /*taken out code ...*/ }
do following changes use asynctask
current implementation :
1. move onclick method code of mimageview
button inside doinbackground
2. add if (success) {...}else{...}
block in onpostexecute
onclick of mimageview
button
3. start savephototask
task on mimageview
button click heavy task in background thread
Comments
Post a Comment