没有活动的getContext

时间:2011-06-21 20:34:33

标签: android configuration android-context aspect-ratio

在启动任何活动之前是否可以获得设备纵横比?

我正在根据我的设备是识别为“long”还是“not_long”来设置宽度。这应该在活动启动之前很久就可以使用,但我不确定在哪里可以得到这个变量。执行此方法时,活动不可用。另外,为了避免内存泄漏,我不想将活动传递给包含以下方法的类。

以下是失败的通话方法:

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;
    }

3 个答案:

答案 0 :(得分:0)

这是在执行哪里?我没有看到你如何执行代码,也没有实例化继承自Context的东西。 Service继承自Context,而BroadcastReceiver的onReceive则赋予Context。

此外,您可以直接从调用此方法的位置传入Configuration对象,而不是传入Context。

答案 1 :(得分:0)

从活动中调用此方法时。你可以传递“this”作为getDefaultWidth()方法的参数。然后你可以将它用作上下文。

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

并在activitym中称之为

int width = getDefaultWidth(this)

答案 2 :(得分:0)

您的应用程序的应用程序上下文是在任何活动之前创建的。应用程序具有有效的上下文,因此您可以使用它来获取所需的任何内容,设置静态或成员变量,然后在第一个活动中引用它。

可以通过添加扩展Application的新类并在AndroidManifest.xml中进行小的更改来处理Application上下文

清单:

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

将新类添加到扩展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;
}

从您的活动中,只需执行此操作即可获得宽度:

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