Android - onPause and onResume -
i have code randomly draws red circles. didn't work until had pause , resume methods in both classes. without pause , resume methods, screen black , not change. why did need onpause
, onresume
method , why in both classes?
the commented code pause/resume methods.
public class randomcircles extends activity { mysurfaceview mysurfaceview; /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); mysurfaceview = new mysurfaceview(this); setcontentview(mysurfaceview); } /* @override protected void onresume() { // todo auto-generated method stub super.onresume(); mysurfaceview.onresumemysurfaceview(); } @override protected void onpause() { // todo auto-generated method stub super.onpause(); mysurfaceview.onpausemysurfaceview(); }*/ class mysurfaceview extends surfaceview implements runnable{ thread thread = null; surfaceholder surfaceholder; volatile boolean running = false; private paint paint = new paint(paint.anti_alias_flag); random random; public mysurfaceview(context context) { super(context); // todo auto-generated constructor stub surfaceholder = getholder(); random = new random(); } /*public void onresumemysurfaceview(){ running = true; thread = new thread(this); thread.start(); } public void onpausemysurfaceview(){ boolean retry = true; running = false; while(retry){ try { thread.join(); retry = false; } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } }*/ @override public void run() { // todo auto-generated method stub while(running){ if(surfaceholder.getsurface().isvalid()){ canvas canvas = surfaceholder.lockcanvas(); //... actual drawing on canvas int x = random.nextint(getwidth()); if(getwidth() - x < 100) x -= 100; else if(getwidth() - x > getwidth() - 100) x += 100; int y = random.nextint(getheight()); if(getheight() - y < 100) y -= 100; else if(getheight() - x > getheight() - 100) y += 100; int radius; radius = 100; paint paint = new paint(); paint.setstyle(paint.style.fill); paint.setcolor(color.white); canvas.drawpaint(paint); // use color.parsecolor define html colors paint.setcolor(color.parsecolor("#cd5c5c")); canvas.drawcircle(x, y, radius, paint); surfaceholder.unlockcanvasandpost(canvas); } } } } }
the first 2 onpause()
, onresume()
methods part of activity
life cycle , invoked when activity
paused/resumed.
this image illustrates android activity
life cycle. can read on here
the reason works additional onresume
, onpause
methods in activity
because invoke surfaceview
onpausemysurfaceview()
, onresumemysurfaceview()
methods respective methods in activity
. if didn't that, surfaceview
methods never have been called , never stopped/started thread.
Comments
Post a Comment