多次获取非activityclass的上下文

Get Context in non-activity class multiple times

我正在开发一个 "updater" 不断从服务器请求数据的应用程序。如果它接收到新数据,则通过 LocalBroadcast 将数据发送到 activity。为此,我需要在构造函数中传递的当前上下文。此外,新数据被写入单例 class(通过应用程序的运行时存储它)。

问题是,我的 LocalBroadcast 需要不断更新上下文,但它只在构造函数中传递了一次。有人知道每次 LocalBroadcast 发送内容时如何获取当前上下文吗?

我找到了这个答案,但我总是警告不要将上下文 classes 放在静态字段中。 (Get application context from non activity singleton class)

感谢阅读和每一个建议。 这是我的 "Updater" 代码:

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;

import java.util.Arrays;


public class ClientUpdater extends Thread {
    ClientCommunication cComm;              //this is my class which manages the Server-Client-Communication
    Intent BroadcastIntentUpdate;           //Intent for the LocalBroadcast
    Context cntxt;                          //stores the context passed in the constructor
    GlobalClass Obj1;                       //Instance of my Singleton

    public ClientUpdater(ClientCommunication cComm, Context context) {
        this.cComm = cComm;
        this.cntxt = context;
        BroadcastIntentUpdate = new Intent("update");
    }

    public void run(){
        while(true){

            String vomS1 = cComm.sendData("updateChat" + "~" + "$empty$");      //sends an update request to the server an receives the current chat-state
            if(!vomS1.equalsIgnoreCase("timeout")){

                Obj1 = GlobalClass.getInstance();
                String[] update = GlobalClass.decode(vomS1, ";");               //decodes the receives message                  
                String[] altchat = Obj1.getChat();                              //loads the stored chat protocoll from singleton


                if(!Arrays.equals(update, altchat)){                            //if the received message has new data...

                    BroadcastIntentUpdate.putExtra("message", update);
                    //for ".getInstance(cntxt)" the current Context is always needed right?
                    LocalBroadcastManager.getInstance(cntxt).sendBroadcast(BroadcastIntentUpdate);          //...it's sent to the activity
                    Obj1.setChat(update);                                                                                           //...and stored in the singleton
                }
            }    


            try {
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

改变

this.cntxt = context;

cntxt = context.getApplicationContext();

相反。其中 cntxt 是静态上下文。它不会造成 activity 泄漏,因为它使用应用程序上下文。

后台服务最好在Android了解一下 https://developer.android.com/training/run-background-service/create-service.html