2

Because many of my Activities need to check the screen size with the following code:

Display display = getWindowManager().getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();

I decide to move this code from each activity class to a service class, so that the code can be defined in one place and invoked by every activity class.

So, I made my service class like 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 my service class does not extends Activity, I can not directly use getWindowManager(). I would like to know how to get rid of this problem to have the Display instance in my service class which is not necessary to extends Activity class?

That's I would like my activity can access the screen width like 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();
    }

}
Mellon
  • 37,586
  • 78
  • 186
  • 264

1 Answers1

2

Using the width and height of the screen in pixels is usually not good design , but you can achieve what you want by simply passing the current activity to a static method located in some other class accessible by all the activities that should execute the code.

public class MyService {
    static public int getScreenWidth(Activity activity){
         return activity.getWindowManager().getDefaultDisplay().getWidth();
    }
}

another note is that it is confusing to call it service when it is not an android Service (it shouldn't be an android service)

getekha
  • 2,495
  • 3
  • 18
  • 20
  • @ getekha , if using width and height in pixels is not a good design, I would like to know what is the better approach? For example, if I would like to define my layout component to occupy 1/3 of screen height. – Mellon Jul 21 '11 at 10:02
  • Read http://developer.android.com/guide/practices/screens_support.html and http://developer.android.com/guide/topics/ui/layout-objects.html . If your making a game or something else where you need better control of individual pixels to create the effects you want, using the screen size might be the correct way to go, but usually it is not – getekha Jul 21 '11 at 10:21