简体   繁体   English

多次在非活动类中获取上下文

[英]Get Context in non-activity class multiple times

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. 如果它接收到新数据,则将数据通过LocalBroadcast发送到活动。 For this purpose I need the current Context which i pass in the constructor. 为此,我需要我在构造函数中传递的当前Context。 Furthermore, the new data is written to a Singleton class (to store it trough the runtime of the app). 此外,新数据将被写入Singleton类(以通过应用程序的运行时进行存储)。

The problem is, that I need constantly new Context for my LocalBroadcast but its only passed one time in the constructor. 问题是,我需要为LocalBroadcast不断添加新的Context,但是它在构造函数中仅传递了一次。 Does someone have an idea of how can I get the current context everytime the LocalBroadcast shall send something? 有人知道每次LocalBroadcast发送消息时如何获取当前上下文吗?

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

    }

}

Change 更改

this.cntxt = context;

To

cntxt = context.getApplicationContext();

instead. 代替。 Where cntxt is a static context. 其中cntxt是静态上下文。 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 最好是在Android https://developer.android.com/training/run-background-service/create-service.html中了解后台服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM