【问题标题】:Get Context in a Service在服务中获取上下文
【发布时间】:2011-09-20 17:35:35
【问题描述】:

有没有可靠的方法从Service 获取Context

我想为ACTION_PHONE_STATE_CHANGED 注册一个广播接收器,但我不需要我的应用程序始终获取此信息,因此我没有将它放在Manifest 中。

但是,当我需要此信息时,我不能让广播接收器被 GC 杀死,因此我在 Service 中注册广播接收器。

因此,我需要一个Context 来呼叫registerReceiver()。 当我不再需要 ACTION_PHONE_STATE_CHANGED 时,我会注销它。

有什么建议吗?

【问题讨论】:

    标签: android broadcastreceiver android-service


    【解决方案1】:

    【讨论】:

    • 我有这个问题,但结果是没有上下文的工作线程。我在构造线程时通过上下文解决了这个问题。
    • 注意:服务中的上下文在服务中的 onStart 或 onStartCommand 之前是不可见的:stackoverflow.com/questions/7619917/…
    • 这可能是stackoverflow中票数最高的最短答案
    • 考虑到收到的答案和赞成票的大小,我认为 SO 中没有其他答案能胜过这个:)
    • 这4个字刚好解决了我3个小时一直在努力解决的问题。
    【解决方案2】:

    Service 扩展 ContextWrapper 扩展 Context。因此ServiceContext。 在服务中使用'this'关键字。

    【讨论】:

      【解决方案3】:
      1. Service 扩展 ContextWrapper
      2. ContextWrapper 扩展 Context

      所以……

      Context context = this;
      

      (在服务或活动类中)

      【讨论】:

        【解决方案4】:

        由于ServiceContext,因此变量上下文必须是this

        DataBaseManager dbm = Utils.getDataManager(this);   
        

        【讨论】:

          【解决方案5】:

          以防万一有人收到NullPointerException,您需要获取onCreate(). 中的上下文

          ServiceContext,所以这样做:

          @Override
          public void onCreate() {
              super.onCreate();
              context = this;
          }
          

          【讨论】:

            【解决方案6】:

            因为Service本身已经是一个Context

            你甚至可以通过:

            Context mContext = this;
            

            Context mContext = [class name].this;  //[] only specify the class name
            // mContext = JobServiceSchedule.this; 
            

            【讨论】:

              【解决方案7】:

              如果您想要服务上下文,请使用this 关键字。如果你想要活动上下文,你可以通过使用像这样的静态变量来访问它

              public static Context context;
              

              在活动onCreate()

              context=this;
              

              现在您可以在服务中访问该上下文

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2011-10-21
                • 2014-08-16
                • 1970-01-01
                • 1970-01-01
                • 2018-12-03
                • 2013-11-23
                • 2017-11-24
                相关资源
                最近更新 更多