Update UI from a background worker - java

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:
Service
Normal Java thread
Asynctask
or what...
Which is the most appropriate with my requirements?
Thanks!

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.

A Service is the most suitable candidate in your case.

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

Related

Calling child thread method from parent thread

I have a Chat program (running on android) that runs a ui (Chat_client) and then creates an ChatThread that runs communication. I have managed making the client thread call a parent method (using post) but not vsv. I want the parent to call the send method on the client side after the user pushes send button. Help greatly appreciated!
//BUTTON SEND METHOD in parent class. (Chat-thread is running already)
public void send (View view) {
//THIS IS NOT WORKING
chatThread.sendLine(userInput.getText().toString());
}
//Method in child class
public void sendLine (String line){
to_server.println(line);
}
Ok so after some research I arrived at the following solution.
The child thread opens the socket and then creates another thread that reads from socket. The child thread has handler and looper (message que) to which the UI thread sends messages to send through the socket.
Voila!

Long network operation needs to update the UI in Android many times

my Activity shows to the user some data, which are download from a web server. Data could change over the time, so the web server communicates new updates to the connected clients.
So the work of my application is basically this:
while ( true ) {
wait for updates;
update the UI;
}
This code could run forever, and during its life it should update the UI many times.
What class should I use to implement this code?
Thread or Runnable seems the easiest solutions to my problem, but how could I comunicate to the UI thread?
onServerChangesListener... refresh UI
public void serverStateWrappr(){
Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
_localstr = getStuff((String) msg.obj)
updateAdapter(_localstr)
}}
from the thread which has a handleRef ...
while (onChangesForClient) {
Message msg = Message.obtain();
msg.what=1;
msg.obj=newData;
//TODO this is the comment for UI
mhandleRef.sendMessage(msg);
}
}
You should probably go with an asyncTask, calling runOnUiThread when you need to update the UI. Have a look to this question to see how activity.runOnUiThread() should be used
IMHO AsyncTask is preferrable, because it gives you more fine-grained control over your background task via onPreExecute(), onPostExecute()

Android - Make app send heartbeat to server

I need to implement a regular heartbeat.
The heartbeat itself is a simple HTTP-GET call to my server.
The thing is I want to send it as long as my app is open. When I close the app the sending should stop.
I read a few things about Services and AlarmManager but how can I call/stop them when navigating through my app activities?
This also seems nice but still the same problem:
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
try{
//do your code here
//also call the same runnable
handler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(runable, 1000);
Could anybody maybe post a good example or a link?
Thanks!
The thing is I want to send it as long as my app is open. When I close
the app the sending should stop
In android a bit harder than in iOS, but lets do it:
In Android you don't have a callback at application level when the app it goes to background or is killed. Instead of thins you should handle at each Activity onStop Method for example. Take a look at Activity lifecycle:
or onDestroy method. Note:
When an activity it isn't visible anymore it can be because your app is gone to background, closed or other activity is visible. You have to decide which case is and use your HTTP Get / Post, or stop it , when needed.
Here is a sample code with Async task to send data over HTTP.
I implemented a simple timeout using a similar Handler to your code. When an Activity calls onPause trigger the timeout on a 10 second delay, when an Activity calls onResume cancel that call with removeRunnable(...) if the timeout code fires you know the user has left your app (this is the reason for the 10 second timeout, to give a new Activity time to launch if there is one).
You could add something in your timeout code to kill the heartbeat. e.g. cancel the heartbeat Runnable

Prevent stopping android service

I've a Service that is called from an Activity with this code:
startService(new Intent(AMC_Activity.this,CallService.class));
Service is running good for about 20-30 minutes, but after that service stop running, I know that I can use 'foreground' service, but by using that I should show a notification, so, is there any other way to prevent service stop running?
I am not sure but i think you are starting your service from UI thread and after that you are putting your in application background so after sometime your activity instance getting lost and that UI thread also killed at that time.
Solution
Create a new Thread and start service with that Thread instead of UI Thread, because service is doing work on that Thread whoever Thread is invoking it.
//This code will be in class body.
private Thread thread1 = new Thread(){
public void run(){
startService(new Intent(AMC_Activity.this,CallService.class));
}
}
//Now this code will be call when you are going to start the service, i.e. Under onCreate()
thread1.start();
It may helpful to you.
If you use a TaskManager App on your device you should take care that it doesn't kill your app and/or service too.

How can I implement threads in this scenario?

I haven't got any code at the moment but I have a situation where I will be implementing an Java application onto a wireless sensor. There can only be one main method.
There will be multiple other wireless sensors that can connect to my sensor. My sensor needs to do a calculation based on thhe information provided to me by the other sensors. Each sensor can choose whether or not they want to participate in the calculation. Every 1 second, my sensor does a calculation.
So basically, what I need is to listen for incoming sensors, provide them with a thread to interact with, and retrieve the information from each sensor.
My question is, in my application, how do I listen for incoming sensors (blocking call) and also free my application to carry out its calculations?
From a high level, this is what your application will do
==Main Thread==
start socket
Start processing thread
accept an incoming connection (this will cause the thread to block until a connection occurs)
start new thread to handle socket (handler thread) (alternatively use a thread pool, but that is more complicated)
return to 3
==Handler Thread==
Receive open socket from main thread
Save data coming in from socket to be given to processing thread
Finish and close socket
==Processing Thread==
Wait 1 second
Process data retrieved from step 2 of Handler Thread
Return to 1
You need another thread that receives the information of all the communication threads. You should look at the utilities in java.util.concurrent such a BlockingQueue that let threads pass data to one another thread-safely.
Most of all you should read a lot about multi-threading: it is not a trivial topic.
This will get you started. Add error/exception checking/handling as necessary.
public class Test {
static class WorkTask42 implements Runnable {
public void run() {
// background work
}
}
public static void main(String... args) throws Exception {
// repeat for each background task
WorkTask42 wt = new WorkTask42();
Thread a = new Thread(wt);
a.setDeamon(true);
a.start();
}
}

Categories

Resources