0

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();
            }
        }

    }

}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Elias
  • 45
  • 6
  • "im always warned of putting context classes in static field"; There's no static field in that code; I don't generally deal with android so i can't say for sure (which is why I'm leaving a comment rather than an answer) but that code looks like it should be ultimately safe to use. There's a background task service in the android sdk, as far as I remember, I'd suggest using that rather than a thread. it should help with your context issue as well. – Wayne Jan 03 '18 at 17:29
  • yes after your and HendraWDs comments I think about using a background service as well, thanks for your time – Elias Jan 03 '18 at 17:50

1 Answers1

1

Change

this.cntxt = context;

To

cntxt = context.getApplicationContext();

instead. Where cntxt is a static context. It will not create activity leak, since it uses application context.

It is better if you learn about background service in Android https://developer.android.com/training/run-background-service/create-service.html

HendraWD
  • 2,984
  • 2
  • 31
  • 45
  • Thanks for the answer. If i write `cntxt = context.getApplicationContext();` is the cntxt variable always "refreshed" when used or do i misunderstand something? This would be what i need. And yes, you are right, background services are also a thing, maybe i will change that – Elias Jan 03 '18 at 17:48
  • using the application context is as it would suggest, it uses the context for the application. The context that you originally receive in your code is for the individual Receiver/UIComponent/Whatever that is supplying the context. The application context doesn't renew/refresh, but is always valid, nonetheless. – Wayne Jan 03 '18 at 17:54
  • There are many things out there that you could use too instead of background service, like JobScheduler, FirebaseJobScheduler, AlarmManager, etc. I prefer FirebaseJobScheduler though. It will not always "refreshed", except you create the ClientUpdater object, since it is reassigned from there. Although reassigned, the instance is the same. 1 android application has 1 application context instance, so it will not recreated except you close and re-open your app. – HendraWD Jan 03 '18 at 17:55