android - How to get Display object from my service class? -


because many of activities need check screen size following code:

display display = getwindowmanager().getdefaultdisplay(); int screenwidth = display.getwidth(); int screenheight = display.getheight(); 

i decide move code each activity class service class, code can defined in 1 place , invoked every activity class.

so, made service class below:

public class myservice {       private  display display;      public int screenwidth, screenheight;       public myservice(){          display = getwindowmanager().getdefaultdisplay(); //error here           screenwidth = display.getwidth();          screenheight = display.getheight();       }       public int getscreenwidth(){           return this.screenwidth;      } } 

because service class not extends activity, can not directly use getwindowmanager(). know how rid of problem have display instance in service class not necessary extends activity class?

that's activity can access screen width following:

public class myactivity extends activity{    myservice service;    @override   public void oncreate(bundle savedinstancestate) {        super.oncreate(savedinstancestate);        setcontentview(r.layout.main);         service= new myservice();         int swidth = service.getscreenwidth();     }  } 

using width , height of screen in pixels not design , can achieve want passing current activity static method located in other class accessible activities should execute code.

public class myservice {     static public int getscreenwidth(activity activity){          return activity.getwindowmanager().getdefaultdisplay().getwidth();     } } 

another note is confusing call service when not android service (it shouldn't android service)


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -