我正在尝试获取 FragmentStackSupport
Activity 的上下文并在内部静态类中使用它。
我已经在内部静态类中实例化了 FragmentStackSupport
,并且正在使用 getBaseContext()
获取 FragmentStackSupport
的上下文。
将外部类上下文放入 GCMRegistar.checkDevice(thisContext)
不会在代码中给出错误,但会导致应用程序崩溃。
我不能使用“this”或 FragmentStackSupport.this
因为内部类是静态的。如果类(class)是公开的,“这个”会起作用......
如何为 checkDevice()
方法获取正确的上下文?
public class FragmentStackSupport extends SherlockFragmentActivity {
int mStackLevel = 1;
//...
public static class CountingFragment extends SherlockFragment implements OnClickListener{
//...
FragmentStackSupport FSSContext;
static CountingFragment newInstance(int num) {
CountingFragment f = new CountingFragment();
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FSSContext= new FragmentStackSupport();
FSSContext.getBaseContext();
Context thisContext;
//
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(thisContext);
}
}
}
最佳答案
如果我理解正确并且你正在尝试获取 FSSContext,这应该可以工作
GCMRegistrar.checkDevice(CountingFragment.this.FSSContext);
您可以使用 OuterClassName.this 访问匿名内部类的周围类(而简单的“this”指的是内部类)
编辑:抱歉,我错过了这个问题的要点。根据 checkDevice 的文档,它旨在获取应用程序上下文 - 在您的崩溃示例中,您将传递给它一个 Activity 上下文(它可能与相关的 Activity 一起被销毁)。请改用 Context.getApplicationContext() 。另请注意,如果设备不支持 GCM,checkDevice 会抛出 UnsupportedOperationException,因此该调用应位于 try/catch block 中。
关于android - 如何将类的上下文放入内部静态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12291162/