How do I use getWindowManager() by another java file

劉孟儒 picture 劉孟儒 · Aug 14, 2013 · Viewed 41k times · Source

I want to use getWindowManager() in my MainActivity, but I don't want to write this method directly in it.

Here is my MainActivity code

public class MainActivity extends Activity {
@Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  String d= new DisplayMessageActivity().getWeithAndHeight(d);
 }

and here is my DisplayMessageActivity code

public class DisplayMessageActivity extends Activity {

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    ....
    ....
    setContentView(textView);
}
public String getWeithAndHeight(String url) {  
    DisplayMetrics dm = new DisplayMetrics();  
    *getWindowManager().getDefaultDisplay().getMetrics(dm);*
    int width = dm.widthPixels;
    int height = dm.heightPixels;  
    String w=new String(""+width);
    String h=new String(""+height);
    url=url+"&23=w%3A"+w+"%20h%3A"+h+"%20d%3A"; 
    return url;
}  
}

my code break at getWindowManager(), please tell me why. Thank you very much.

Answer

Boris Mocialov picture Boris Mocialov · Aug 14, 2013
public String getWeithAndHeight(Context context, String url) {  
    DisplayMetrics dm = new DisplayMetrics();  
    ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
    //....
}