Reputation: 1433
I want to port my client from Java Swing(Java client
) to Android(Android client
).
Basically, my Java client
have a thread, which run a forever while loop to receive UDP packets, and base on content of UDP packets, UI of the corresponding JFrame will be updated.
Now I want my Android client
has a background worker
like the thread in the Java client
, and that worker
will be initialized in the main activity
. Then when there are some requests from the UDP socket, the main activity
will start some corresponding activities (Chat Activities), then there are some other requests come from the UDP socket, the worker
will update on the activity(this activity can be main activity or a Chat Activity) which is being displayed on the screen.
So my question is what the background worker
should be:
Which is the most appropriate with my requirements?
Thanks!
Upvotes: 0
Views: 1249
Reputation: 1616
There is a class Application class for each android application . First extend it and it will be initialized on very first time your app will start even before your Activity . Initialize/ start your normal java thread to perfrom background work here . The key advantage will be you can get instance of this application class anywhere from the app (It means you can control on the background thread from anywhere in the applicaion . Send background http request etc.. whatever ....) .Then initialize the handler on the UI thread of particular activity upon which you want to do changes and do something like this.
private Handler myHandler ;
public void checkBackgroundAndUpdateUi()
{
if(conetxt.getApplicationContext().getStatus == completed)
{
initializeHandler();
handler.postRunnable(myRunnable);
}
}
Runnable myRunnable = new Runnable(){
public void run()
{
// update your UI views here .....
}
};
private void initializeHandler(){
myHandler = new Handler ();
}
Upvotes: 0
Reputation: 10241
The background worker should be a service, because
A Service is an application component that can perform long-running operations in the background and does not provide a user interface.
while your UI will be a activity, your service will read the UDP packets and the activity will be modified accordingly.
Upvotes: 1