[英]Get Context in non-activity class multiple times
我正在開發一個“更新程序”不斷從服務器請求數據的應用程序。 如果它接收到新數據,則將數據通過LocalBroadcast發送到活動。 為此,我需要我在構造函數中傳遞的當前Context。 此外,新數據將被寫入Singleton類(以通過應用程序的運行時進行存儲)。
問題是,我需要為LocalBroadcast不斷添加新的Context,但是它在構造函數中僅傳遞了一次。 有人知道每次LocalBroadcast發送消息時如何獲取當前上下文嗎?
我找到了這個答案,但我總是警告將上下文類放在靜態字段中。 ( 從非活動單例類獲取應用程序上下文 )
感謝您的閱讀和每條建議。 這是我的“更新程序”代碼:
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
是靜態上下文。 由於它使用應用程序上下文,因此不會造成活動泄漏。
最好是在Android https://developer.android.com/training/run-background-service/create-service.html中了解后台服務
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.