【问题标题】:How to get the context of a class into an inner static class如何将类的上下文获取到内部静态类中
【发布时间】:2012-09-05 23:34:09
【问题描述】:

我正在尝试获取FragmentStackSupport Activity 的上下文并在内部静态类中使用它。

我已经在内部静态类中实例化了FragmentStackSupport,我正在使用getBaseContext() 来获取FragmentStackSupport 的上下文。

将外部类上下文放入GCMRegistar.checkDevice(thisContext) 不会在代码中产生错误,但会使应用程序崩溃。

我不能使用 'this' 或 FragmentStackSupport.this 因为内部类是静态的。如果课程是公开的,“这个”会起作用......

如何为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);

}
}
}

【问题讨论】:

  • 将公共静态更改为私有无效。它产生了更多错误。

标签: android static google-cloud-messaging inner-classes android-context


【解决方案1】:

如果我理解正确并且您正在尝试获取 FSSContext,这应该可以工作

GCMRegistrar.checkDevice(CountingFragment.this.FSSContext);

您可以使用 OuterClassName.this 访问匿名内部类的周围类(而简单的“this”指的是内部类)

编辑:抱歉,我错过了这个问题的要点。根据 checkDevice 的文档,它旨在获取应用程序上下文 - 在您的崩溃示例中,您正在向它传递一个 Activity 上下文(它可能与相关的 Activity 一起被销毁)。请改用 Context.getApplicationContext()。另请注意,如果设备不支持 GCM,则 checkDevice 会引发 UnsupportedOperationException,因此该调用应位于 try/catch 块中。

【讨论】:

  • GCMRegistrar.checkDevice(CountingFragment.this.FSSContext); 正在使程序崩溃,我收到一个 ': Unable to start activity , NullPointerException 错误。还有其他技术吗?
【解决方案2】:

我找到了答案,但是我不确定它为什么会起作用。但是因为我用的是sherlock action bar,所以不得不使用那个库的具体方法

GCMRegistrar.checkDevice(getSherlockActivity().getApplicationContext());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多