gpt4 book ai didi

java - 多次获取非 Activity 类中的Context

转载 作者:行者123 更新时间:2023-12-02 11:47:47 25 4
gpt4 key购买 nike

我正在开发一个应用程序,其中“更新程序”不断向服务器请求数据。如果它收到新数据,数据将通过 LocalBroadcast 发送到 Activity 。为此,我需要在构造函数中传递的当前上下文。此外,新数据被写入 Singleton 类(通过应用程序的运行时存储它)。

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

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

感谢您的阅读和每条建议。这是我的“更新程序”代码:

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

关于java - 多次获取非 Activity 类中的Context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48082188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com