开发者

getContext without activity

Is it possible to get device aspect ratio before launch开发者_StackOverflow社区ing any activity?

I am trying to setup the width based on whether my device is identified as 'long' or 'not_long'. This should be available long before the activity is launched but I am not sure where I can get this variable. Activity is NOT available at the time this method is executed. Also in order to avoid memory leaks I do not want to pass activity into the class that contains the following method.

Here is the failing call method:

public int getDefaultWidth() { 
        Configuration myConfig = new Configuration();
        myConfig.setToDefaults();
        myConfig = getResources().getConfiguration();

        switch (myConfig.screenLayout & Configuration.SCREENLAYOUT_LONG_MASK) {

            case Configuration.SCREENLAYOUT_LONG_NO: {
                return this._defaultWidth;
            }
            case Configuration.SCREENLAYOUT_LONG_YES: {
                return this._defaultWidthLong;
            }
            case Configuration.SCREENLAYOUT_LONG_UNDEFINED: {
                return this._defaultWidth;
            }
        }
        return this._defaultWidth;
    }


Your app's Application context is created before any activities. An Application has a valid context, so you could use that to fetch whatever you need, set a static or member variable, and then reference that in your first activity.

An Application context can be handled by adding a new class that extends Application and making a small change in AndroidManifest.xml

Manifest:

<application android:enabled="true"...
   android:name=".Foo">
...
</application>

Add the new class to your project that extends Application:

public class Foo extends Application {

private int mWidth;

@Override
public void onCreate() {
    super.onCreate();
    // do stuff to set mWidth using the Application context like:
    // mWidth = getResources().getConfiguration().blahblahblah
}   

public int getWidth() {
    return mWidth;
}

From your activity, simply do this to get width:

int width = ((Foo)getApplication()).getWidth();


Where is this is executing? I don't see how you could be executing code and not have something instantiated that inherits from Context. Service inherits from Context and a BroadcastReceiver's onReceive is given a Context.

Also, instead of passing a Context in, you could just pass in a Configuration object from where ever this method is being called.


When you call this method from an activity. you can pass "this" as a parameter for getDefaultWidth() method. Then you can use it as a context.

public int getDefaultWidth(Context context) { ... }

and in the activitym call it like

int width = getDefaultWidth(this)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜