I have an Android background thread whose creator is long gone. But the thread keeps running and logging data all the time. I want to pass or send this data to the current running activity that did not create the thread.
What do I have to do? Google? That brings up stuff about passing work to the background so as to not block the main 开发者_运维问答UI thread. That's not what I want. I want to pass/send the data to the new currently running activity.
Typically if you are doing a background thread of that sort you want to use a Service to hold the thread. In your Activity you just bind to the Service, and when you get the Service instance you can pass it a Handler. The thread in the service can then access the Handler and send Messages through the Handler to the Activity. When the Activity finishes you unbind()
, clear the Handler and its as if you were never there.
OK, so this 'logging' thread is trundling along on its own, shoving input onto some disk file, or whatever. If some other thread wants to 'hook' this data, it has to signal the logging thread to call something else with the data as well as logging it. The logging thread is normally waiting on some input queue for stuff to log, yes? If so, send the thread a message on its input queue to tell it to call method XXXX with all the data to be logged. The logging thread can keep a list of all events to call on each logging action.
Does that make sense? Basically, it's an expansion on what Marie is suggesting. The logger thread would get messages and switch on some 'Ecommand' enumeration field in the message. Pseudo Pascal:
case inMessage.command of : ElogString:logThis(inMessage.logString); EaddNotification:notifierList.add(inMessage.event); EdeleteNotification:notifierList.delete(inMessage.event); end;
The 'logThis' function would write the logString to the disk file and then call every event in notifierList with the data.
Does this make sense? It did when I wrote it, but been on the Abbot ale tonight, (5%).
Rgds, Martin
ok the answer is very simple, use Handler and keep passing this handler to the methods that you use the handler then will be your connector to the main activity, and will be able to change the GUI too if needed, as follow :
final Handler someHandler=new Handler(){
public void handleMessage(Message msg)
{ switch(msg.what){
case 0: dosomething(); break;
case 1: dosomething(); break;
case 2: dosomething(); break;
}
}
declare this handler the same way as you declare any method don't nest it in any method every time that you need to pass some data to the main activity, or GUI, simple call to the handler for example :
public void downLoadData(Handler h)
{
h.sendEmptyMessage(34);
someThread=new threadClass(h);
}
and so on...
hope this helps, Best regards.
精彩评论