I want to execute some code on like each 10 seconds (example only), and for this purpose I am using TimerTask.The problem is that within the run() method of TimerTask class, I am implementing looper.prepare and looper.loop , due to some handlers involved.The looper.loop seems to not return after first execution and therefore my TimerTask starts executes once and that is it. I tried using looper.quit(), but that didnt help either.Is there any nice way of making it work?
A small example :
public class Timez extends TimerTask {
public void run () {
Looper.prepare();
// some code here
Looper.loop();
}
}
Thanks in advance.
Related
I'm new to Android, so apologies if I'm missing anything obvious.
I'm writing an app that does something every few hundred milliseconds. The frequency varies, but no more often than every 300 or so.
Currently I have a class DoEvery that implements Runnable that is scheduled every X milliseconds using scheduleAtFixedRate from the main thread. That is working, but I want to add an animation that is started every time DoEvery.run executes using Drawable.start() and from what I've read it doesn't seem like that is possible since Drawable.start() needs to be run on the main thread. Using scheduleAtFixedRate also seems to make it difficult to change the frequency later.
Is there a way to start the animation from the DoEvery class? Or is there a better way to run something on a regular basis like this?
You could try this.
new Thread(new Runnable() {
#Override public void run() {
//I'm in the thread.
//if you are not in the Activity, pass the activity instance to your class
// and use myActivity.runOnUiThread(...)
runOnUiThread(new Runnable() {
#Override public void run() {
//I'm in the main thread
}
});
}
}).start();
I've created a nested class within my Activity
public class MissionsActivity extends Activity {
class UpdateMissions implements Runnable {
#Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
[...]
}
[...]
}
In the thread I have to read a file and update some TextFields in the layout. I've tried implementing the run() method with a while(true) that reads and updates the fields, but the app just crashes when I start that Activity.
UPDATE: I've called the execute() method inside the onCreate() method of the UI Activity. The Task is only working the first time I enter the Activity, if i change and go back it won't do anything.
Hey a solution could be trying to use Java's Executor Framework. Put the following code in your Activity.
With executors, you can use a cachedThreadPool() singleThreadExecutor() fixedThreadPoolExecutor(int numOfThreads) etc.
Executors.newSingleThreadExecutor().submit(new Runnable() {
#Override
public void run() {
//Your task here.
}
});
Please note there are numerous Threading Models and techniques in Android, some Android Specific, some based in Android.
AsyncTask
HandlerThread
You can use an AsyncTask. It allows you to load the file and show the progress on ui thread until the load it's finished.
Here you have a good example Download a file with Android, and showing the progress in a ProgressDialog
I would recommend using RxJava or Live Data if you are more advance in developing but also the first solution is fine enough for beginning
https://developer.android.com/topic/libraries/architecture/livedata.html
I have a method invoked by onClickListener
#Override
public Object getData() {
Thread t = new Thread(new testThread());
t.start();
return false;
}
it start the new Thread well, but when I am trying to do both:
private class testThread implements Runnable{
#Override
public void run() {
OuterClass.this.myActivity.runOnUiThread(new Runnable(){ ... });
OuterClass.this.myActivity.uiHandler.post(new Runnable(){ ... });
...
nothing happens. UI hang up and no Runnable never run (I see it during careful debugging).
Why? Everything should work or even if it fail, why the UI hangs??
Please help!
SOLVED!!! The problem was in method which invokes getData (outside the scope), it never finished failing into infinite loop. Since that scheduled Runnables never started as I think. Now everything works .
AsyncTask is better. It is easier to use, you don't have to manually manage so many threads, and it keeps your code clean.
The doInBackground() method will do your lengthy task on an alternate thread. If you want to update your UI when the task is running, use the publishProgress() method, and if you want to update the UI after the work is done, use onPostExecute().
As to your question on why the UI hangs, see if you are using any method that takes very long or blocks for some reason in the runOnUiThread() method. If any code takes time, remove it from this method.
I'm using a timertask in the main activity in order to update some data repeatedly every X seconds.
This data is of static form, so it's a public static method
is this a bad technique? I mean, using static methods like this
I know there's this thing called Service, but there aren't really many examples online on how to use it in order to update every X seconds a variable that should be then accessed by some activity
so my question is, what's the difference between using a timer task and a service? is a timertask just a time counter and nothing else? does it run in parallel if it's being used with a handler or not? and what happens if you have something like this:
handler = new Handler();
t = new Timer();
task = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//do stuff;
}
});
}
};
t.schedule(task, 0, 10000);
how exactly does this code work? what does it do? does it run in parallel? why even if I leave the activity where this code is first being called, it still runs? what makes it run in this case?
thanks in advance
TimerTask is part of standard Java and can be use for delayed or repeated execution for some piece of (Runnable) code. It's use is discouraged on Android. You can use a Handler instead.
A Service can be used as a independent and UI-less part of your Android application. It can run and create it's own threads and can be started for UI or with Intents through a AlarmManager for example.
It think want you want is a Service which creates it's own thread and does some work. When the work is done, memory will be freed on Android when the garbage collector kicks in, something you do not control and that's a good thing.
I am a new Android developer. I am using the Handler class to schedule some operations. So I am creating runnable objects that calls some of my instance methods.
But I have a problem. Sometimes my run() method in Runnable object is called twice.
What could be the problem??
and there is the code
//deneme is a Handler.
deneme.postDelayed(new Runnable() {
#Override
public void run()
{
randomOyna();
//the instance method that I call.
}
}, 1000);
If don't schedule your Handler to run on another Thread than the UI-thread, there might be a hidden delay in the execution because your Runnable will also run on the UI-thread and thus will only be allowed to run when there is "time" for it. With this hidden delay, it might seem like it is run twice but in reality it's just and over-delayed running before a regular delayed Runnable.
Can't see a mistake just by looking the hint you gave us... But you might try plain old java to run threads instead of handler... Good luck...
Look here for more details