I'm working on an app where an "updater" constantly asks for data from a server. If it receives new data, the data is sent via LocalBroadcast to an activity. For this purpose I need the current Context which i pass in the constructor. Furthermore, the new data is written to a Singleton class (to store it trough the runtime of the app).
The problem is, that I need constantly new Context for my LocalBroadcast but its only passed one time in the constructor. Does someone have an idea of how can I get the current context everytime the LocalBroadcast shall send something?
I found this answer but im always warned of putting context classes in static fields. (Get application context from non activity singleton class)
Thanks for reading and for every advice. Here is my "Updater" Code:
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();
}
}
}
}