开发者

How to get Display object from my service class?

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 exten开发者_JAVA百科ds 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();
    }

}


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜