Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the correct DisplayMetrics from an AppWidget in Android?

I need to determine the screen density at runtime in an Android AppWidget. I've set up an HDPI emulator device (avd). If set up a regular executable project, and insert this code into the onCreate method:

DisplayMetrics dm = getResources().getDisplayMetrics();
Log.d("MyTag", "screen density " + dm.densityDpi);

This outputs "screen density 240" as expected.

However, if I set up an AppWidget project, and insert this code into the onUpdate method:

DisplayMetrics dm = context.getResources().getDisplayMetrics();
Log.d("MyTag", "screen density " + dm.densityDpi);

This outputs "screen density 160". I noticed, hooking up the debugger, that the mDefaultDisplay member of the Resources object here is null in the AppWidget case.

Similarly, if I get a resource at runtime using the Resources object obtained from context.getResources() in the AppWidget, it returns the wrong resource based on screen density. For instance, I have a 60x60px drawable for mdpi, and an 80x80 drawable for hdpi. If I get this Drawable object using context.getResources().getDrawable(...), it returns the 60x60 version.

Is there any way to correctly deal with resources at runtime from the context of an AppWidget?

Thanks!

like image 844
ManicBlowfish Avatar asked Apr 15 '10 06:04

ManicBlowfish


People also ask

How do I get DisplayMetrics?

DisplayMetrics dm = new DisplayMetrics(); getWindowManager(). getDefaultDisplay(). getMetrics(dm); int width = dm.

What is AppWidgetProvider?

AppWidgetProvider merely parses the relevant fields out of the Intent that is received in onReceive(Context,Intent) , and calls hook methods with the received extras.


1 Answers

This feels like a bug. If you can create a sample project that demonstrates the error, post an issue on the Android issue tracker. If you think of it, add a comment here pointing to the issue.

like image 56
CommonsWare Avatar answered Sep 29 '22 20:09

CommonsWare