How can i put two different threads on a single service? - android

can someone give me the code example that shows how to use two different threads on a single service? i didnt find the way to do it in google, then i need a code example...
one waiting 5 seconds and the other waiting 60 seconds, with different code

You can use the ScheduledExecutorService to create and run scheduled events, then set them up like this:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
final Runnable r1 = new Runnable() {
#Override
public void run() {
Log.i("TestStuff", "r1 ran at " + new Date());
}
};
final Runnable r2 = new Runnable() {
#Override
public void run() {
Log.i("TestStuff", "r2 ran " + new Date());
}
};
scheduler.schedule(r1, 5, TimeUnit.SECONDS);
scheduler.schedule(r2, 60, TimeUnit.SECONDS);
Note that the threads can't do anything on the UI, but you did mention a "single service", so i'm assuming you're doing all non-UI things anyway.

Thread t5 = new Thread(Runnable_that_waits_5_seconds);
Thread t60 = new Thread(Runnable_that_waits_60_seconds);
t5.start();
t60;start();
Now you just need to define your runnables.
Also, you should give your runnables a way to detect that they've been interrupted and terminate if they do, and interrupt each thread in your service's clean-up code.

Related

Different delay time with Handler

I have been using 5 Handler tasks in my application with different post delays but all of them are working at a different speed irrespective of the delay time that I have specified, is there a better way to get exact time delay in between of multiple tasks,
Sample Code:
H2 = new Handler();
R2 = new Runnable()
{ #Override
public void run()
{ H2.postDelayed(R2, 100);
//Do something
}
};
H2.postDelayed(R2, 0);
Task would run in variable time intervals sometimes way more variable.

How to delay execution android

I am building an android board game which features AI. The AI gets a turn and has to invoke a series of actions after which it posts invalidate to my custom view to update.
I need to slow down these actions so the user gets to see the AI having its turn rather than it flashing by.
I have tried something along these lines
try {
doFirstThing();
Thread.sleep(500)
//post invalidate
doNextThing();
Thread.sleep(1000)
//post invalidate
}
catch (Exception e) {
}
However this is having absolutely no effect. Also this is running in a separate thread if this wasn't obvious.
Whats my best option I've looked at handler but they don't need right as i need to execute a series of tasks in sequence updating the view each time.
Using a Handler, which is a good idea if you are executing from a UI thread...
final Handler h = new Handler();
final Runnable r2 = new Runnable() {
#Override
public void run() {
// do second thing
}
};
Runnable r1 = new Runnable() {
#Override
public void run() {
// do first thing
h.postDelayed(r2, 10000); // 10 second delay
}
};
h.postDelayed(r1, 5000); // 5 second delay
Just to add a sample :
The following code can be executed outside of the UI thread.
Definitely, Handler must be use to delay task in Android
Handler handler = new Handler(Looper.getMainLooper());
final Runnable r = new Runnable() {
public void run() {
//do your stuff here after DELAY milliseconds
}
};
handler.postDelayed(r, DELAY);

Destroying Runnable in android

I am using the following code to access a url:
final Handler handler = new Handler();
Runnable runnable = new Runnable()
{
public void run()
{
img.setImageBitmap(returnBitmap("fromurl"));
handler.postDelayed(this, 50);
}
};
handler.postDelayed(runnable, 2000);
I observed that if the server is not up the app takes ages to close correctly if I hit the back button. Is there anyway way I could speed up the exit procedure.
Runnables will exit automatically when finished with their run() method. If you are employing a loop to do some work, the solution that Jay Ho suggested will help exit from the loop cleanly. If you want to prevent the Handler from executing the runnable (before it posts) you can use handler.removeCallbacksAndMessages(null)1 to clear the queue. Placing it in onDestroy() is your best bet. Otherwise, you're on your own. Once you've spawned a thread, you're at the mercy of the Android operating system to terminate it once its done.
Side note: I've run into problems like this before, and it's usually a call to a system service or the implementation of a Broadcast Listener or Alarm that mucks up the exit process.
private Runnable runnable = new Runnable() {
private boolean killMe=false;
public void run() {
//some work
if(!killMe) {
img.setImageBitmap(returnBitmap("fromurl"));
handler.postDelayed(this, 50);
}
}
public void kill(){
killMe=true;
}
};
ThreadPoolExecutor threadPoolExecutor = Executors.newSingleThreadExecutor();
Runnable longRunningTask = new Runnable();
// submit task to threadpool:
Future longRunningTaskFurure = threadPoolExecutor.submit(longRunningTask);
... ...
// At some point in the future, if you want to kill the task:
longRunningTaskFuture.cancel(true);
... ...

How to Delay Execution of Code For X Amount of Time in Android

On button click I want to begin a timer of 5 minutes and then execute a method that will check for certain conditions and set off alerts if conditions are right. I've seen examples with timers and postDelay, but don't really understand why one would use one vs another. What is the best way to accomplish what I am trying to do? I don't want to lock up the UI during the 5 minutes. The user should be free to use the app as normal during the countdown.
EDIT: I am trying the postDelayed suggestion but visual studio is not liking something about my code. It looks exactly like examples I've found. My be a mono for android thing.
Handler h = new Handler();
Runnable r = new Runnable(){
public void run()
{
Dialog d = inst2.showBuilder(this, "test", "test");
d.Show();
}
};
h.postDelayed(r, 5000);
Specifically the code block inside of run throws all kinds of "} expected" and "a namespace cannot directly contain members such as fields or methods" exceptions.
Try using Timer Object :
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask()
{
#Override
public void run()
{
// Your code goes here
}
}, 1000); // 1sec
final Handler handler = new Handler();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
handler.post(new Runnable()
{
public void run()
{
// YOUR Code
}
});
}
}, 1000); // 1sec
You can start a simple Thread that will sleep in background for 5 minutes and then call a function. While the thread sleeps in background the UI will not freeze. When the thread finish executing what you want you can set off alerts by sending some intents as notifications and receive them in some Broadcast Receivers.
Hope this helps
Use Handler.postDelayed(Runnable block); method to execute delay, as android also not recommend to use timer.
Handler h = new Handler();
Action myAction = () =>
{
// your code that you want to delay here
};
h.PostDelayed(myAction, 1000);

Android Async, Handler or Timer?

Every 5 seconds, I want to call my webservice and get text (not images), then display it in my ImageAdapter. What would be the best way to accomplish this?
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
callWebservice();
}
};
handler.postDelayed(r, 5000);
It depends if you want to use a different thread or not. Do you want the user to be able to interact with the application on the UI Thread while the images are downloading? If so, then I would definitely use an AsyncTask with a small ProgressBar (style="#android:style/Widget.ProgressBar.Small")
If you don't care about threading then what #inazaruk said.
Edit: the truth is most modern apps that retrieve data from a web service will use an AsyncTask with a discreet little loader in the corner just to let the user know it's updating.
Edit 2: here's an example of using a TimerTask to run something every 5 seconds. The key is the runOnUiThread(). There may be better ways to tie all the elements together but this accurately portrays all the pieces.
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
CallWebService();
}
}, 0, 1000);
}
private void CallWebService()
{
this.runOnUiThread(fetchData);
}
private Runnable fetchData = new Runnable() {
public void run() {
asyncTask.execute();
}
};
You should call asynctask inside the application main thread. Asynctask can't be called in a background thread.

Categories

Resources